UNPKG

@code-yeongyu/senpi

Version:

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

193 lines • 9.23 kB
/** * Print mode (single-shot): Send prompts, output result, exit. * * Used for: * - `pi -p "prompt"` - text output * - `senpi --mode json "prompt"` - JSON event stream */ import { describeProviderFailureForUser, stripTurnRetrySuppressionPrefix, } from "@earendil-works/pi-ai"; import { flushRawStdout, waitForRawStdoutBackpressure, writeRawStdout } from "../core/output-guard.js"; import { describeFallbackExhaustion } from "../core/retry-fallback/exhaustion.js"; import { usageLimitCause, usageLimitScope } from "../core/retry-fallback/usage-limit.js"; import { killTrackedDetachedChildren } from "../utils/shell.js"; import { toJsonEvent } from "./json-event.js"; import { formatProviderNativeBody, formatProviderNativeSummary } from "./provider-native-rendering.js"; /** * Run in print (single-shot) mode. * Sends prompts to the agent and outputs the result. */ export async function runPrintMode(runtimeHost, options) { const { mode, messages = [], initialMessage, initialImages } = options; let session = runtimeHost.session; let unsubscribe; let unsubscribeBackpressure; let disposed = false; const signalCleanupHandlers = []; const disposeRuntime = async () => { if (disposed) return; disposed = true; unsubscribe?.(); unsubscribeBackpressure?.(); // Print mode ends right after: a signal calls process.exit, and the normal path returns to main, whose // process exits once the loop drains (handles extensions leave open are reclaimed at shutdown, senpi#2292). await runtimeHost.dispose({ processExit: true }); }; const registerSignalHandlers = () => { const signals = ["SIGTERM"]; if (process.platform !== "win32") { signals.push("SIGHUP"); } for (const signal of signals) { const handler = () => { killTrackedDetachedChildren(); void disposeRuntime().finally(() => { process.exit(signal === "SIGHUP" ? 129 : 143); }); }; process.on(signal, handler); signalCleanupHandlers.push(() => process.off(signal, handler)); } }; registerSignalHandlers(); runtimeHost.setRebindSession(async () => { await rebindSession(); }); const rebindSession = async () => { session = runtimeHost.session; await session.bindExtensions({ mode: mode === "json" ? "json" : "print", commandContextActions: { waitForIdle: () => session.waitForIdle(), newSession: async (newSessionOptions) => runtimeHost.newSession(newSessionOptions), fork: async (entryId, forkOptions) => { const result = await runtimeHost.fork(entryId, forkOptions); return { cancelled: result.cancelled }; }, navigateTree: async (targetId, navigateOptions) => { const result = await session.navigateTree(targetId, { summarize: navigateOptions?.summarize, customInstructions: navigateOptions?.customInstructions, replaceInstructions: navigateOptions?.replaceInstructions, label: navigateOptions?.label, expectedLeafId: navigateOptions?.expectedLeafId, }); return { cancelled: result.cancelled }; }, editAssistantMessage: async (entryId, text, editOptions) => { const result = await session.editAssistantMessage(entryId, text, { summarize: editOptions?.summarize, customInstructions: editOptions?.customInstructions, expectedLeafId: editOptions?.expectedLeafId, }); return { cancelled: result.cancelled, unchanged: result.unchanged, entryId: result.entryId }; }, editUserMessage: async (entryId, text, editOptions) => { const result = await session.editUserMessage(entryId, text, { summarize: editOptions?.summarize, customInstructions: editOptions?.customInstructions, expectedLeafId: editOptions?.expectedLeafId, }); return { cancelled: result.cancelled, unchanged: result.unchanged, entryId: result.entryId }; }, switchSession: async (sessionPath, switchOptions) => { return runtimeHost.switchSession(sessionPath, switchOptions); }, reload: async () => { await session.reload(); }, }, onError: (err) => { console.error(`Extension error (${err.extensionPath}): ${err.error}`); }, }); unsubscribe?.(); unsubscribeBackpressure?.(); unsubscribe = session.subscribe((event) => { if (event.type === "retry_fallback_applied") { console.error(`Model fallback: ${event.from} -> ${event.to} (${usageLimitCause(event.from, event.limit) ?? event.reason})`); } else if (event.type === "retry_fallback_exhausted") { console.error(`Model fallback exhausted: ${event.chainKey} (${describeFallbackExhaustion(event).replaceAll("\n", "; ")})`); for (const refusal of event.refusals ?? []) { console.error(`Model fallback refused ${refusal.model}: ${refusal.detail}`); } } else if (event.type === "retry_fallback_reverted") { const cause = event.cause === "fallback-unusable" ? ` (${event.from} cannot serve right now)` : ""; console.error(`Model fallback reverted: ${event.from} -> ${event.to}${cause}`); } if (mode === "json") { writeRawStdout(`${JSON.stringify(toJsonEvent(event))}\n`); } }); unsubscribeBackpressure = mode === "json" ? session.agent.subscribe(async () => { await waitForRawStdoutBackpressure(); }) : undefined; }; try { if (mode === "json") { const header = session.sessionManager.getHeader(); if (header) { writeRawStdout(`${JSON.stringify(header)}\n`); } } await rebindSession(); if (initialMessage) { await session.prompt(initialMessage, { images: initialImages, sessionTitlePrompt: false }); } for (const message of messages) { await session.prompt(message, { sessionTitlePrompt: false }); } await session.waitForSettledSessionWork(); const lastMessage = session.state.messages.findLast((message) => message.role === "assistant"); const failed = lastMessage?.role === "assistant" && (lastMessage.stopReason === "error" || lastMessage.stopReason === "aborted"); const exitCode = failed ? 1 : 0; if (mode === "text") { if (lastMessage?.role === "assistant") { const assistantMsg = lastMessage; if (failed) { // A provider-stream stall or transport drop keeps the classifier wording // on the message; stderr gets the plain-language version instead. const described = assistantMsg.errorCause?.type === "usage_limit" && assistantMsg.errorCause.scope === "account" ? assistantMsg.errorMessage : describeProviderFailureForUser(assistantMsg.errorMessage, { model: `${assistantMsg.provider}/${assistantMsg.model}`, usageLimit: usageLimitScope(assistantMsg), }); console.error(described ?? (stripTurnRetrySuppressionPrefix(assistantMsg.errorMessage ?? "") || `Request ${assistantMsg.stopReason}`)); } else { for (const content of assistantMsg.content) { if (content.type === "text") { writeRawStdout(`${content.text}\n`); } else if (content.type === "providerNative") { writeRawStdout(`${formatProviderNativeSummary(assistantMsg, content, false)}\n`); writeRawStdout(`${formatProviderNativeBody(content, false)}\n`); } } } } } return exitCode; } catch (error) { console.error(error instanceof Error ? error.message : String(error)); return 1; } finally { for (const cleanup of signalCleanupHandlers) { cleanup(); } await disposeRuntime(); await flushRawStdout(); } } //# sourceMappingURL=print-mode.js.map