UNPKG

@code-yeongyu/senpi

Version:

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

152 lines • 7.25 kB
import { freshEscapeResidueRetry } from "./escape-residue.js"; import { TOOL_NAMES } from "./family.js"; import { parseAskUserAnswerFrame } from "./format.js"; import { ASK_USER_SETTLEMENT_ENTRY, emitAskUserClosed } from "./notify.js"; import { getPendingQuestions } from "./registry.js"; import { DEFAULT_ASK_USER_TIMEOUT_MS, toCanonical, } from "./schema.js"; import { deliverAnswer, startQuestion } from "./tool.js"; export const ASK_USER_RESUMED_ENTRY = "ask-user:resumed"; function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function variantFor(name) { if (name === TOOL_NAMES.claude) return "claude"; if (name === TOOL_NAMES.codex) return "codex"; return undefined; } function findDanglingQuestions(entries) { const results = new Set(); const accepted = new Set(); const resumed = new Set(); const settled = new Set(); for (const entry of entries) { if (entry.type === "message" && entry.message.role === "user") { const content = entry.message.content; const texts = typeof content === "string" ? [content] : content.flatMap((part) => (part.type === "text" ? [part.text] : [])); for (const text of texts) { const frame = parseAskUserAnswerFrame(text); if (frame) settled.add(frame.requestId); } } if (entry.type === "custom" && entry.customType === ASK_USER_RESUMED_ENTRY && isRecord(entry.data)) { const toolCallId = entry.data.toolCallId; if (typeof toolCallId === "string") resumed.add(toolCallId); } if (entry.type === "message" && entry.message.role === "toolResult") { results.add(entry.message.toolCallId); const details = entry.message.details; if (!entry.message.isError && isRecord(details) && details.accepted === true && details.status === "pending") { accepted.add(entry.message.toolCallId); } } if (entry.type === "custom" && entry.customType === ASK_USER_SETTLEMENT_ENTRY && isRecord(entry.data) && typeof entry.data.requestId === "string") settled.add(entry.data.requestId); } const dangling = []; for (let index = entries.length - 1; index >= 0; index--) { const entry = entries[index]; if (entry?.type !== "message" || entry.message.role !== "assistant") continue; const content = entry.message.content; for (let blockIndex = content.length - 1; blockIndex >= 0; blockIndex--) { const block = content[blockIndex]; if (block?.type !== "toolCall" || block.incomplete === true) continue; const variant = variantFor(block.name); if (!variant || settled.has(block.id)) continue; const call = { toolCallId: block.id, variant, args: block.arguments }; const request = requestFromCall(call, DEFAULT_ASK_USER_TIMEOUT_MS); if (results.has(block.id) && (request?.waitForAnswer === true || !accepted.has(block.id))) continue; if (resumed.has(block.id)) continue; dangling.push(call); } } return dangling; } /** The restorable request, or undefined when the recorded arguments no longer form a valid question set. */ function requestFromCall(dangling, timeoutMs) { try { return toCanonical(dangling.variant, dangling.args, { requestId: dangling.toolCallId, timeoutMs, }); } catch { return undefined; } } /** * A call that cannot be restored never reaches the UI: it settles as * orphaned-after-restart, like a restored question whose UI is gone, so the * model learns it was lost and can ask again. */ function settleUnrestorable(pi, ctx, dangling, timeoutMs) { const required = isRecord(dangling.args) && dangling.args.required === true; const lost = { requestId: dangling.toolCallId, questions: [], waitForAnswer: false, timeoutMs, ...(required ? { required: true } : {}), }; const response = { status: "orphaned-after-restart", answers: {}, unanswered: [] }; pi.appendEntry(ASK_USER_SETTLEMENT_ENTRY, { requestId: lost.requestId, status: response.status }); emitAskUserClosed(pi, lost.requestId, response); deliverAnswer(pi, ctx, lost, response, dangling.variant); } export async function resumeDanglingQuestion(pi, event, ctx) { // Diagnostic sizes-only startup starts no turn, so it restores nothing. if (event.sizesOnly) return; // senpi#4764: the CLI's initial runtime passes no explicit session_start // event, so a restarted CLI opening an existing session file arrives with // reason "startup" — the same as a fresh session. That is safe to include: // a fresh session has no branch entries, so findDanglingQuestions finds // nothing, while a reopened file's dangling question is restored exactly // like on the switch_session "resume" path. // Headless startup (print mode, `-p` / `--mode json`) has no question UI: // restoring there would settle the question as `orphaned-after-restart` // (sending a follow-up message and starting a model turn the user never // asked for) and write the `ask-user:resumed` marker, so a later // interactive open could never re-ask it. Skip startup restores entirely // when `ctx.hasUI` is false; resume/reload keep their existing no-UI // orphan delivery. Note: CLI `--fork <file>` also arrives as "startup" // with copied branch entries, so a fork re-presents the source's dangling // question, unlike runtime `/fork` (reason "fork", excluded above). The // event carries no signal telling a forked startup from a plain restart, // so this divergence is documented, not filtered. if (event.reason !== "resume" && event.reason !== "reload" && event.reason !== "startup") return; if (event.reason === "startup" && !ctx.hasUI) return; const pending = new Set(getPendingQuestions(ctx.sessionManager.getSessionId()).map((entry) => entry.request.requestId)); const timeoutMs = (ctx.getAskUserSettings?.().timeoutMinutes ?? DEFAULT_ASK_USER_TIMEOUT_MS / 60_000) * 60_000; for (const dangling of findDanglingQuestions(ctx.sessionManager.getBranch())) { if (pending.has(dangling.toolCallId)) continue; pending.add(dangling.toolCallId); pi.appendEntry(ASK_USER_RESUMED_ENTRY, { toolCallId: dangling.toolCallId }); const request = requestFromCall(dangling, timeoutMs); if (!request) { settleUnrestorable(pi, ctx, dangling, timeoutMs); continue; } // The runtime registration owns delivery, including after another reload. void startQuestion(pi, ctx, request, ctx.signal, { timedOut: false, unavailable: false, escapeResidue: freshEscapeResidueRetry() }, dangling.variant, { resuming: true, }); } } //# sourceMappingURL=resume.js.map