print-mode.ts 4.6 KB

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