UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

248 lines • 11.4 kB
import { classifyCursorCliError } from "./errors.js"; import { CursorCliAbortError, CursorCliPromptTooLargeError, MAX_CURSOR_CLI_PROMPT_BYTES } from "./transport.js"; export const CURSOR_CLI_CONTEXT_RECAP_MAX_BYTES = 8 * 1024; export const CURSOR_CLI_CONTEXT_RECAP_BEGIN = "===== senpi context recap ====="; export const CURSOR_CLI_CONTEXT_RECAP_END = "===== end senpi context recap ====="; function record(value) { return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined; } function byteLength(text) { return Buffer.byteLength(text, "utf8"); } function utf8Prefix(text, maxBytes) { if (byteLength(text) <= maxBytes) return text; const bytes = Buffer.from(text, "utf8"); let end = Math.max(0, Math.min(maxBytes, bytes.length)); while (end > 0 && (bytes[end] & 0xc0) === 0x80) end -= 1; return bytes.subarray(0, end).toString("utf8"); } /** * Builds the one-turn context recap from senpi's own last exchanges, wrapped in * explicit delimiters and hard-capped at `maxRecapBytes` (delimiters included). * The newest exchanges are kept; older ones are dropped first. */ export function buildCursorCliContextRecap(model, exchanges, maxRecapBytes = CURSOR_CLI_CONTEXT_RECAP_MAX_BYTES) { const usable = (exchanges ?? []).filter((exchange) => exchange.text.length > 0); if (usable.length === 0) return undefined; const header = `${CURSOR_CLI_CONTEXT_RECAP_BEGIN}\n(${model === undefined ? "chat restarted" : `model switched to '${model}'`}; recent conversation from senpi's own records follows)`; const overheadBytes = byteLength(header) + 1 + byteLength(CURSOR_CLI_CONTEXT_RECAP_END) + 1; if (overheadBytes >= maxRecapBytes) return undefined; const budget = maxRecapBytes - overheadBytes; const selected = []; let used = 0; for (let index = usable.length - 1; index >= 0; index -= 1) { const exchange = usable[index]; const line = `${exchange.role}: ${exchange.text}`; const cost = byteLength(line) + (selected.length > 0 ? 1 : 0); if (used + cost <= budget) { selected.unshift(line); used += cost; continue; } if (selected.length === 0) { selected.unshift(utf8Prefix(line, budget)); used = budget; } break; } if (selected.length === 0) return undefined; return `${header}\n${selected.join("\n")}\n${CURSOR_CLI_CONTEXT_RECAP_END}`; } function composePrompt(recap, prompt) { return recap === undefined ? prompt : `${recap}\n\n${prompt}`; } function shrinkToCeiling(recap, rawPrompt, ceilingBytes) { if (recap !== undefined) { const composed = composePrompt(recap, rawPrompt); if (byteLength(composed) <= ceilingBytes) return { prompt: composed, recapDropped: false }; if (byteLength(rawPrompt) <= ceilingBytes) return { prompt: rawPrompt, recapDropped: true }; throw new CursorCliPromptTooLargeError(byteLength(rawPrompt), ceilingBytes); } if (byteLength(rawPrompt) > ceilingBytes) { throw new CursorCliPromptTooLargeError(byteLength(rawPrompt), ceilingBytes); } return { prompt: rawPrompt, recapDropped: false }; } function isAbort(error) { if (error instanceof CursorCliAbortError) return true; const value = record(error); return value !== undefined && (value.type === "aborted" || value.kind === "aborted"); } function errorInput(error) { const value = record(error); if (value && ("exitCode" in value || "stderr" in value || "resultEvent" in value || "thrown" in value)) { return error; } return { thrown: error }; } function defaultInitFromEvent(event) { const value = record(event); if (value?.type !== "system" || value.subtype !== "init") return undefined; const chatId = typeof value.session_id === "string" ? value.session_id : undefined; const model = typeof value.model === "string" ? value.model : undefined; if (chatId === undefined || chatId.length === 0 || model === undefined || model.length === 0) { return undefined; } return { chatId, model }; } function defaultErrorFromEvent(event) { const value = record(event); if (value?.type === "malformed_stream") return { thrown: event }; if (value?.type === "result" && (value.is_error === true || value.subtype === "error")) { return { resultEvent: event }; } return undefined; } function defaultIsVisibleAssistantDelta(event) { const value = record(event); if (!value) return false; if (value.type === "assistant") { const message = record(value.message); if (!Array.isArray(message?.content)) return false; return message.content.some((item) => { const block = record(item); return block?.type === "text" && typeof block.text === "string" && block.text.length > 0; }); } return ((value.type === "assistant_delta" || value.type === "text_delta") && typeof value.delta === "string" && value.delta.length > 0); } function restartNotice(previousChatId, reason, contextReinjected) { const cause = reason === "context_overflow" ? "context overflow" : "resume failure"; return { type: "cursor_chat_restarted", message: `Cursor chat '${previousChatId}' could not continue after a ${cause}; a fresh chat was started${contextReinjected ? " and senpi's recent context was re-injected" : ""}.`, previousChatId, reason, }; } class CursorCliNoAssistantOutputError extends Error { constructor() { super("Cursor CLI attempt completed without visible assistant text"); this.name = "CursorCliNoAssistantOutputError"; } } /** * Sticky per-senpi-session chat routing for the Cursor CLI lane. This lane * spawns once per turn, so routing state is just the last observed * `system/init` per senpi session - no resident CLI process exists to manage. * The turn decision itself is pure; records change only when an init event is * observed, so cancelled or failed turns leave prior routing intact. */ export class CursorCliSessionRouter { constructor(deps = {}) { this.records = new Map(); this.nowFn = deps.now ?? Date.now; } getRecord(senpiSessionId) { const entry = this.records.get(senpiSessionId); return entry === undefined ? undefined : Object.freeze({ ...entry }); } clear(senpiSessionId) { this.records.delete(senpiSessionId); } planTurn(context, input, policy = {}) { const ceilingBytes = policy.promptCeilingBytes ?? MAX_CURSOR_CLI_PROMPT_BYTES; const resumeEnabled = (policy.resumeMode ?? "auto") === "auto"; const bound = this.records.get(context.senpiSessionId); // Chats live inside each account's HOME, so a record bound to another // account can never be resumed here. const resumable = bound !== undefined && bound.accountName === context.accountName && resumeEnabled; const resumeChatId = resumable && bound !== undefined ? bound.chatId : undefined; const modelSwitch = resumable && bound !== undefined && bound.lastModel !== input.model; const recap = modelSwitch && policy.contextRecapOnModelSwitch !== false ? buildCursorCliContextRecap(input.model, input.recentExchanges, policy.maxRecapBytes) : undefined; const shrunk = shrinkToCeiling(recap, input.prompt, ceilingBytes); return { resumeChatId, prompt: shrunk.prompt, contextRecap: shrunk.recapDropped ? undefined : recap, modelSwitch, recapDroppedForCeiling: shrunk.recapDropped, }; } /** Records the chat id and effective model reported by `system/init`. */ observeInit(context, init, at = this.nowFn()) { this.records.set(context.senpiSessionId, { accountName: context.accountName, chatId: init.chatId, lastModel: init.model, lastUsedAt: at, }); } async *runTurn(options, input) { const now = options.now ?? this.nowFn; const classify = options.classify ?? classifyCursorCliError; const errorFromEvent = options.errorFromEvent ?? defaultErrorFromEvent; const initFromEvent = options.initFromEvent ?? defaultInitFromEvent; const isVisibleAssistantDelta = options.isVisibleAssistantDelta ?? defaultIsVisibleAssistantDelta; const ceilingBytes = options.promptCeilingBytes ?? MAX_CURSOR_CLI_PROMPT_BYTES; const context = { senpiSessionId: options.senpiSessionId, accountName: options.accountName, }; const plan = this.planTurn(context, input, { resumeMode: options.resumeMode, contextRecapOnModelSwitch: options.contextRecapOnModelSwitch, maxRecapBytes: options.maxRecapBytes, promptCeilingBytes: options.promptCeilingBytes, }); let attempt = { prompt: plan.prompt, resumeChatId: plan.resumeChatId }; const previousChatId = plan.resumeChatId; let fellBack = false; while (true) { let visibleAssistantDeltaEmitted = false; try { const stream = await options.runAttempt(attempt); for await (const event of stream) { const failure = errorFromEvent(event); if (failure !== undefined) throw failure; const init = initFromEvent(event); if (init !== undefined) this.observeInit(context, init, now()); visibleAssistantDeltaEmitted ||= isVisibleAssistantDelta(event); yield event; } if (!visibleAssistantDeltaEmitted) throw new CursorCliNoAssistantOutputError(); return; } catch (error) { // Aborts and post-output failures must surface exactly as thrown; // account-level failures belong to the failover layer above. if (isAbort(error) || fellBack || previousChatId === undefined || visibleAssistantDeltaEmitted) { throw error; } const classification = classify(errorInput(error)); if (classification.kind !== "context_overflow" && classification.kind !== "other") throw error; const reason = classification.kind === "context_overflow" ? "context_overflow" : "resume_failed"; const recap = plan.contextRecap ?? buildCursorCliContextRecap(undefined, input.recentExchanges, options.maxRecapBytes); const shrunk = shrinkToCeiling(recap, input.prompt, ceilingBytes); yield restartNotice(previousChatId, reason, recap !== undefined && !shrunk.recapDropped); attempt = { prompt: shrunk.prompt, resumeChatId: undefined }; fellBack = true; } } } } /** Shared router instance; one record per senpi session, in-process. */ export const cursorCliSessionRouter = new CursorCliSessionRouter(); //# sourceMappingURL=session-router.js.map