1
/**2
* Print mode (single-shot): Send prompts, output result, exit.3
*4
* Used for:5
* - `pi -p "prompt"` - text output6
* - `pi --mode json "prompt"` - JSON event stream7
*/9
import type { AssistantMessage, ImageContent } from "@earendil-works/pi-ai";10
import type { AgentSessionRuntime } from "../core/agent-session-runtime.ts";11
import { flushRawStdout, waitForRawStdoutBackpressure, writeRawStdout } from "../core/output-guard.ts";12
import { killTrackedDetachedChildren } from "../utils/shell.ts";13
import { toJsonEvent } from "./json-event.ts";15
/**16
* Options for print mode.17
*/18
export interface PrintModeOptions {19
/** Output mode: "text" for final response only, "json" for all events */20
mode: "text" | "json";21
/** Array of additional prompts to send after initialMessage */22
messages?: string[];23
/** First message to send (may contain @file content) */24
initialMessage?: string;25
/** Images to attach to the initial message */26
initialImages?: ImageContent[];27
}29
/**30
* Run in print (single-shot) mode.31
* Sends prompts to the agent and outputs the result.32
*/33
export async function runPrintMode(runtimeHost: AgentSessionRuntime, options: PrintModeOptions): Promise<number> {34
const { mode, messages = [], initialMessage, initialImages } = options;35
let exitCode = 0;36
let session = runtimeHost.session;37
let unsubscribe: (() => void) | undefined;38
let unsubscribeBackpressure: (() => void) | undefined;39
let disposed = false;40
const signalCleanupHandlers: Array<() => void> = [];42
const disposeRuntime = async (): Promise<void> => {43
if (disposed) return;44
disposed = true;45
unsubscribe?.();46
unsubscribeBackpressure?.();47
await runtimeHost.dispose();48
};50
const registerSignalHandlers = (): void => {51
const signals: NodeJS.Signals[] = ["SIGTERM"];52
if (process.platform !== "win32") {53
signals.push("SIGHUP");54
}56
for (const signal of signals) {57
const handler = () => {58
killTrackedDetachedChildren();59
void disposeRuntime().finally(() => {60
process.exit(signal === "SIGHUP" ? 129 : 143);61
});62
};63
process.on(signal, handler);64
signalCleanupHandlers.push(() => process.off(signal, handler));65
}66
};68
registerSignalHandlers();70
runtimeHost.setRebindSession(async () => {71
await rebindSession();72
});74
const rebindSession = async (): Promise<void> => {75
session = runtimeHost.session;76
await session.bindExtensions({77
mode: mode === "json" ? "json" : "print",78
commandContextActions: {79
waitForIdle: () => session.waitForIdle(),80
newSession: async (newSessionOptions) => runtimeHost.newSession(newSessionOptions),81
fork: async (entryId, forkOptions) => {82
const result = await runtimeHost.fork(entryId, forkOptions);83
return { cancelled: result.cancelled };84
},85
navigateTree: async (targetId, navigateOptions) => {86
const result = await session.navigateTree(targetId, {87
summarize: navigateOptions?.summarize,88
customInstructions: navigateOptions?.customInstructions,89
replaceInstructions: navigateOptions?.replaceInstructions,90
label: navigateOptions?.label,91
});92
return { cancelled: result.cancelled };93
},94
switchSession: async (sessionPath, switchOptions) => {95
return runtimeHost.switchSession(sessionPath, switchOptions);96
},97
reload: async () => {98
await session.reload();99
},100
},101
onError: (err) => {102
console.error(`Extension error (${err.extensionPath}): ${err.error}`);103
},104
});106
unsubscribe?.();107
unsubscribeBackpressure?.();108
unsubscribe = session.subscribe((event) => {109
if (mode === "json") {110
writeRawStdout(`${JSON.stringify(toJsonEvent(event))}\n`);111
}112
});113
unsubscribeBackpressure =114
mode === "json"115
? session.agent.subscribe(async () => {116
await waitForRawStdoutBackpressure();117
})118
: undefined;119
};121
try {122
if (mode === "json") {123
const header = session.sessionManager.getHeader();124
if (header) {125
writeRawStdout(`${JSON.stringify(header)}\n`);126
}127
}129
await rebindSession();131
if (initialMessage) {132
await session.prompt(initialMessage, { images: initialImages });133
}135
for (const message of messages) {136
await session.prompt(message);137
}139
if (mode === "text") {140
const state = session.state;141
const lastMessage = state.messages[state.messages.length - 1];143
if (lastMessage?.role === "assistant") {144
const assistantMsg = lastMessage as AssistantMessage;145
if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {146
console.error(assistantMsg.errorMessage || `Request ${assistantMsg.stopReason}`);147
exitCode = 1;148
} else {149
for (const content of assistantMsg.content) {150
if (content.type === "text") {151
writeRawStdout(`${content.text}\n`);152
}153
}154
if (assistantMsg.stopReason === "length") {155
console.error("Response was truncated: the model reached its output token limit.");156
exitCode = 1;157
}158
}159
}160
}162
return exitCode;163
} catch (error: unknown) {164
console.error(error instanceof Error ? error.message : String(error));165
return 1;166
} finally {167
for (const cleanup of signalCleanupHandlers) {168
cleanup();169
}170
await disposeRuntime();171
await flushRawStdout();172
}173
}