@bastani/atomic 0.9.45 → 0.9.46-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +11 -0
  3. package/dist/builtin/intercom/broker/broker.ts +124 -10
  4. package/dist/builtin/intercom/broker/client.ts +177 -25
  5. package/dist/builtin/intercom/broker/multinode-router.ts +228 -27
  6. package/dist/builtin/intercom/broker/multinode-state-store.ts +10 -0
  7. package/dist/builtin/intercom/broker/recipient-receipts.ts +38 -4
  8. package/dist/builtin/intercom/broker/send-handler.ts +9 -2
  9. package/dist/builtin/intercom/broker/sql-outbox-store.ts +29 -4
  10. package/dist/builtin/intercom/group.ts +25 -0
  11. package/dist/builtin/intercom/index.bundle.mjs +177 -35
  12. package/dist/builtin/intercom/package.json +1 -1
  13. package/dist/builtin/intercom/retry-policy.ts +7 -0
  14. package/dist/builtin/intercom/types.ts +21 -0
  15. package/dist/builtin/mcp/package.json +1 -1
  16. package/dist/builtin/subagents/CHANGELOG.md +10 -0
  17. package/dist/builtin/subagents/package.json +1 -1
  18. package/dist/builtin/subagents/src/extension/index.bundle.mjs +150 -54
  19. package/dist/builtin/web-access/package.json +1 -1
  20. package/dist/builtin/workflows/CHANGELOG.md +39 -0
  21. package/dist/builtin/workflows/builtin/{chunk-6901nsd6.js → chunk-6jpwc09k.js} +1 -1
  22. package/dist/builtin/workflows/builtin/{chunk-vwx023ge.js → chunk-qhm35ntx.js} +1 -1
  23. package/dist/builtin/workflows/builtin/{chunk-jvna28mq.js → chunk-zhyqnf5g.js} +331 -68
  24. package/dist/builtin/workflows/builtin/goal.js +2 -2
  25. package/dist/builtin/workflows/builtin/index.js +3 -3
  26. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  27. package/dist/builtin/workflows/package.json +1 -1
  28. package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +1 -0
  29. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6.md +2 -2
  30. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_sol.md +2 -2
  31. package/dist/builtin/workflows/skills/prompt-engineer/references/gpt_6_1_terra.md +77 -0
  32. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  33. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +2 -0
  34. package/dist/builtin/workflows/src/extension/index.bundle.mjs +7076 -3386
  35. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +11075 -7261
  36. package/dist/builtin/workflows/src/index.js +6768 -3605
  37. package/dist/builtin/workflows/src/local-worker-entry.mjs +11075 -7261
  38. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +19 -0
  39. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  40. package/dist/core/agent-session-boundaries.js +1 -0
  41. package/dist/core/agent-session-boundaries.js.map +1 -1
  42. package/dist/core/agent-session-events.d.ts.map +1 -1
  43. package/dist/core/agent-session-events.js +2 -1
  44. package/dist/core/agent-session-events.js.map +1 -1
  45. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  46. package/dist/core/agent-session-extension-bindings.js +15 -2
  47. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  48. package/dist/core/agent-session-methods.d.ts +3 -2
  49. package/dist/core/agent-session-methods.d.ts.map +1 -1
  50. package/dist/core/agent-session-methods.js.map +1 -1
  51. package/dist/core/agent-session-prompt.d.ts +4 -2
  52. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  53. package/dist/core/agent-session-prompt.js +13 -8
  54. package/dist/core/agent-session-prompt.js.map +1 -1
  55. package/dist/core/agent-session-recovery.d.ts.map +1 -1
  56. package/dist/core/agent-session-recovery.js +92 -1
  57. package/dist/core/agent-session-recovery.js.map +1 -1
  58. package/dist/core/agent-session-transfer.d.ts.map +1 -1
  59. package/dist/core/agent-session-transfer.js +5 -0
  60. package/dist/core/agent-session-transfer.js.map +1 -1
  61. package/dist/core/agent-session.d.ts +2 -0
  62. package/dist/core/agent-session.d.ts.map +1 -1
  63. package/dist/core/agent-session.js +2 -0
  64. package/dist/core/agent-session.js.map +1 -1
  65. package/dist/core/copilot-errors.d.ts +6 -0
  66. package/dist/core/copilot-errors.d.ts.map +1 -0
  67. package/dist/core/copilot-errors.js +17 -0
  68. package/dist/core/copilot-errors.js.map +1 -0
  69. package/dist/core/execution-model-router.d.ts.map +1 -1
  70. package/dist/core/execution-model-router.js +12 -2
  71. package/dist/core/execution-model-router.js.map +1 -1
  72. package/dist/core/extensions/context-types.d.ts +7 -0
  73. package/dist/core/extensions/context-types.d.ts.map +1 -1
  74. package/dist/core/extensions/context-types.js.map +1 -1
  75. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  76. package/dist/core/extensions/runner-context.js +6 -0
  77. package/dist/core/extensions/runner-context.js.map +1 -1
  78. package/dist/core/extensions/workflow-activity-hub.d.ts +4 -0
  79. package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
  80. package/dist/core/extensions/workflow-activity-hub.js +26 -5
  81. package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
  82. package/dist/core/extensions/workflow-events.d.ts +5 -0
  83. package/dist/core/extensions/workflow-events.d.ts.map +1 -1
  84. package/dist/core/extensions/workflow-events.js.map +1 -1
  85. package/dist/core/messages.d.ts +5 -0
  86. package/dist/core/messages.d.ts.map +1 -1
  87. package/dist/core/messages.js +1 -1
  88. package/dist/core/messages.js.map +1 -1
  89. package/dist/core/model-fallback-failures.d.ts +1 -1
  90. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  91. package/dist/core/model-fallback-failures.js +37 -3
  92. package/dist/core/model-fallback-failures.js.map +1 -1
  93. package/dist/core/model-runtime-streaming.js +2 -2
  94. package/dist/core/model-runtime-streaming.js.map +1 -1
  95. package/dist/core/provider-composer.d.ts.map +1 -1
  96. package/dist/core/provider-composer.js +19 -11
  97. package/dist/core/provider-composer.js.map +1 -1
  98. package/dist/core/provider-rate-limits.d.ts +55 -6
  99. package/dist/core/provider-rate-limits.d.ts.map +1 -1
  100. package/dist/core/provider-rate-limits.js +182 -29
  101. package/dist/core/provider-rate-limits.js.map +1 -1
  102. package/dist/core/provider-request-admission.d.ts.map +1 -1
  103. package/dist/core/provider-request-admission.js +42 -18
  104. package/dist/core/provider-request-admission.js.map +1 -1
  105. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  106. package/dist/core/storage/node-sqlite.js +176 -19
  107. package/dist/core/storage/node-sqlite.js.map +1 -1
  108. package/dist/core/storage/provider.d.ts +4 -2
  109. package/dist/core/storage/provider.d.ts.map +1 -1
  110. package/dist/core/storage/provider.js +94 -5
  111. package/dist/core/storage/provider.js.map +1 -1
  112. package/dist/core/structured-output/index.d.ts.map +1 -1
  113. package/dist/core/structured-output/index.js +15 -8
  114. package/dist/core/structured-output/index.js.map +1 -1
  115. package/dist/core/structured-output/provider-failure.d.ts +17 -0
  116. package/dist/core/structured-output/provider-failure.d.ts.map +1 -0
  117. package/dist/core/structured-output/provider-failure.js +28 -0
  118. package/dist/core/structured-output/provider-failure.js.map +1 -0
  119. package/dist/core/tools/bash.d.ts.map +1 -1
  120. package/dist/core/tools/bash.js +13 -7
  121. package/dist/core/tools/bash.js.map +1 -1
  122. package/dist/core/tools/shell-task-render.d.ts +1 -0
  123. package/dist/core/tools/shell-task-render.d.ts.map +1 -1
  124. package/dist/core/tools/shell-task-render.js +7 -2
  125. package/dist/core/tools/shell-task-render.js.map +1 -1
  126. package/dist/extensions/tool-search/tool.d.ts +5 -0
  127. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  128. package/dist/extensions/tool-search/tool.js +38 -5
  129. package/dist/extensions/tool-search/tool.js.map +1 -1
  130. package/dist/index.d.ts +1 -1
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +1 -1
  133. package/dist/index.js.map +1 -1
  134. package/dist/modes/interactive/components/chat-session-host-actions.js +3 -2
  135. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  136. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  137. package/dist/modes/interactive/components/login-dialog.js +42 -14
  138. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  139. package/dist/modes/interactive/interactive-extension-context.js +2 -1
  140. package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
  141. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  142. package/dist/modes/interactive/interactive-startup.js +5 -6
  143. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  144. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  145. package/dist/modes/rpc/rpc-client-process.js +8 -1
  146. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  147. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  148. package/dist/modes/rpc/rpc-client.js +7 -1
  149. package/dist/modes/rpc/rpc-client.js.map +1 -1
  150. package/dist/utils/ansi.d.ts +2 -0
  151. package/dist/utils/ansi.d.ts.map +1 -1
  152. package/dist/utils/ansi.js +5 -0
  153. package/dist/utils/ansi.js.map +1 -1
  154. package/docs/codemode.md +1 -1
  155. package/docs/intercom/reference.md +3 -3
  156. package/docs/models/evals.md +31 -12
  157. package/docs/models/reference.md +23 -51
  158. package/docs/models.md +3 -4
  159. package/docs/providers.md +5 -15
  160. package/docs/settings.md +1 -1
  161. package/docs/storage.md +2 -2
  162. package/docs/tools.md +1 -1
  163. package/docs/workflows/api-reference.md +20 -1
  164. package/docs/workflows/operations.md +17 -4
  165. package/npm-shrinkwrap.json +64 -44
  166. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-client-process.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,MAAM,oBAAoB,CAAC;AAkB9D,MAAM,WAAW,uBAAuB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,GAAG,CAAC,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AED,kFAAkF;AAClF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAc9F"}
@@ -74,6 +74,13 @@ export function spawnRpcClientProcess(options) {
74
74
  */
75
75
  export const ENGINE_SHUTDOWN_GRACE_MS = 5_000;
76
76
  const RPC_CHILD_SHUTDOWN_GRACE_MS = 250;
77
+ /**
78
+ * How long a force-killed child may take to have its exit reported before stop
79
+ * declares it unkillable. On Windows SIGTERM and SIGKILL both become
80
+ * TerminateProcess, which only starts termination, and a loaded runner has
81
+ * reported such an exit more than 500 ms later.
82
+ */
83
+ const KILLED_CHILD_EXIT_REPORT_MS = 5_000;
77
84
  async function exitsWithin(exited, ms) {
78
85
  const deadline = new AbortController();
79
86
  try {
@@ -110,7 +117,7 @@ export async function terminateRpcClientProcess(child, processTree) {
110
117
  killProcessTree(child.pid);
111
118
  else
112
119
  child.kill("SIGKILL");
113
- if (!(await exitsWithin(exited, 250))) {
120
+ if (!(await exitsWithin(exited, KILLED_CHILD_EXIT_REPORT_MS))) {
114
121
  throw new Error(`Agent process ${child.pid ?? "unknown"} did not exit after SIGKILL`);
115
122
  }
116
123
  if (guardianFile)
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-client-process.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE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,CAAC","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { markLifecycleTiming } from \"../../core/lifecycle-timings.ts\";\nimport { ENGINE_SESSION_STORAGE_FLAG } from \"../../core/session-storage.js\";\nimport { createChildProcessEnvironment } from \"../../utils/child-process.ts\";\nimport { flushPersistentCompileCache } from \"../../utils/compile-cache.ts\";\nimport {\n\tINTERACTIVE_ENGINE_BOOTSTRAP_FLAG,\n\ttype InteractiveEngineBootstrapHandle,\n\tremoveOwnedInteractiveEngineBootstrap,\n\twriteInteractiveEngineBootstrap,\n} from \"../../utils/interactive-engine-bootstrap.ts\";\nimport { scrubInteractiveEngineEnv } from \"../../utils/interactive-engine-env.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\n\nexport interface RpcClientProcessOptions {\n\tcliPath: string;\n\tcliArgs: string[];\n\tcwd?: string;\n\tenv?: Record<string, string>;\n\truntimeExecutable?: string;\n\truntimeArgs?: string[];\n\tinteractiveEngine: boolean;\n\t/** Credential handed to the engine child through the bootstrap file, never argv or env. */\n\tinteractiveEngineApiKey?: string;\n}\n\nconst guardianFiles = new WeakMap<ChildProcess, string>();\nconst bootstrapHandles = new WeakMap<ChildProcess, InteractiveEngineBootstrapHandle>();\n\nexport function createRpcClientProcessEnvironment(\n\toverrides?: Record<string, string>,\n\tbaseEnv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n\treturn scrubInteractiveEngineEnv(createChildProcessEnvironment(overrides, baseEnv));\n}\n\nexport function spawnRpcClientProcess(options: RpcClientProcessOptions): ChildProcess {\n\tconst guardianFile = options.interactiveEngine\n\t\t? join(tmpdir(), `atomic-engine-guardian-${process.pid}-${crypto.randomUUID()}`)\n\t\t: undefined;\n\t// The engine's startup metadata travels in a 0600 file rather than the\n\t// environment: a Bun child spawned without an explicit `env` inherits the\n\t// runtime's launch-time environment, so anything placed here would remain\n\t// reachable by every descendant of the engine no matter what the engine\n\t// deletes from its own `process.env` afterwards.\n\tconst bootstrap = options.interactiveEngine\n\t\t? writeInteractiveEngineBootstrap({\n\t\t\t\thostPid: process.pid,\n\t\t\t\tguardFile: guardianFile!,\n\t\t\t\t...(options.interactiveEngineApiKey ? { apiKey: options.interactiveEngineApiKey } : {}),\n\t\t\t})\n\t\t: undefined;\n\tif (options.interactiveEngine) flushPersistentCompileCache();\n\tconst cliArgs = bootstrap\n\t\t? [...options.cliArgs, INTERACTIVE_ENGINE_BOOTSTRAP_FLAG, bootstrap.path]\n\t\t: options.cliArgs;\n\tlet child: ChildProcess;\n\ttry {\n\t\tif (options.interactiveEngine) markLifecycleTiming(\"interactive-engine-spawn\");\n\t\tchild = spawn(\n\t\t\toptions.runtimeExecutable ?? \"bun\",\n\t\t\t[...(options.runtimeArgs ?? []), ...(options.cliPath ? [options.cliPath] : []), ...cliArgs],\n\t\t\t{\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenv: createRpcClientProcessEnvironment(options.env),\n\t\t\t\tdetached: options.interactiveEngine && process.platform !== \"win32\",\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tremoveOwnedInteractiveEngineBootstrap(bootstrap);\n\t\tthrow error;\n\t}\n\tif (guardianFile) guardianFiles.set(child, guardianFile);\n\tif (bootstrap) {\n\t\tbootstrapHandles.set(child, bootstrap);\n\t\t// The child unlinks the record after reading it; this handle-scoped cleanup\n\t\t// removes the directory this process created, and only that directory.\n\t\tchild.once(\"error\", () => removeOwnedInteractiveEngineBootstrap(bootstrap));\n\t\tchild.once(\"exit\", () => removeOwnedInteractiveEngineBootstrap(bootstrap));\n\t}\n\tif (options.interactiveEngine && child.pid) {\n\t\ttrackDetachedChildPid(child.pid);\n\t\tchild.once(\"exit\", () => untrackDetachedChildPid(child.pid!));\n\t}\n\treturn child;\n}\n\n/**\n * How long a SIGTERMed interactive engine may spend running extension\n * `session_shutdown` handlers before its guardian and then a tree kill take over.\n * Builtin shutdown (MCP servers, durable workflow storage) routinely exceeds a\n * few hundred milliseconds on a loaded machine.\n */\nexport const ENGINE_SHUTDOWN_GRACE_MS = 5_000;\nconst RPC_CHILD_SHUTDOWN_GRACE_MS = 250;\n\nasync function exitsWithin(exited: Promise<void>, ms: number): Promise<boolean> {\n\tconst deadline = new AbortController();\n\ttry {\n\t\treturn await Promise.race([exited.then(() => true), sleep(ms, deadline.signal).then(() => false)]);\n\t} finally {\n\t\tdeadline.abort();\n\t}\n}\n\nexport async function terminateRpcClientProcess(child: ChildProcess, processTree: boolean): Promise<void> {\n\tremoveOwnedInteractiveEngineBootstrap(bootstrapHandles.get(child));\n\tif (child.exitCode !== null || child.signalCode !== null) return;\n\tlet resolveExit!: () => void;\n\tconst exited = new Promise<void>((resolve) => {\n\t\tresolveExit = resolve;\n\t});\n\tchild.once(\"exit\", resolveExit);\n\tconst guardianFile = guardianFiles.get(child);\n\tchild.kill(\"SIGTERM\");\n\tif (await exitsWithin(exited, processTree ? ENGINE_SHUTDOWN_GRACE_MS : RPC_CHILD_SHUTDOWN_GRACE_MS)) {\n\t\tif (guardianFile) await rm(guardianFile, { force: true });\n\t\treturn;\n\t}\n\tif (processTree && guardianFile) {\n\t\tawait writeFile(guardianFile, \"stop\");\n\t\tif (await exitsWithin(exited, 500)) {\n\t\t\tawait rm(guardianFile, { force: true });\n\t\t\treturn;\n\t\t}\n\t}\n\tif (processTree && child.pid) killProcessTree(child.pid);\n\telse child.kill(\"SIGKILL\");\n\tif (!(await exitsWithin(exited, 250))) {\n\t\tthrow new Error(`Agent process ${child.pid ?? \"unknown\"} did not exit after SIGKILL`);\n\t}\n\tif (guardianFile) await rm(guardianFile, { force: true });\n}\n\nexport function createInteractiveJsonlOptions(enabled: boolean): { maxBytesPerTurn?: number } {\n\treturn enabled ? { maxBytesPerTurn: 256 * 1024 } : {};\n}\n\n/**\n * CLI args for a replacement engine child: drop whatever session flag the\n * previous generation carried and bind the replacement to `sessionId`, so a\n * restart resumes the same conversation instead of starting a fresh one.\n */\nexport function restartCliArgs(\n\targs: readonly string[] | undefined,\n\tsessionId: string | undefined,\n\tsessionDirectory?: string,\n): string[] {\n\tconst result: string[] = [];\n\tfor (let index = 0; index < (args?.length ?? 0); index += 1) {\n\t\tconst value = args![index]!;\n\t\tif (\n\t\t\tvalue === \"--no-session\" ||\n\t\t\tvalue === \"--continue\" ||\n\t\t\tvalue === \"-c\" ||\n\t\t\tvalue === \"--resume\" ||\n\t\t\tvalue === \"-r\"\n\t\t)\n\t\t\tcontinue;\n\t\tif (\n\t\t\tvalue === \"--session\" ||\n\t\t\tvalue === \"--session-id\" ||\n\t\t\tvalue === \"--fork\" ||\n\t\t\tvalue === \"--import\" ||\n\t\t\t(value === \"--session-dir\" && sessionDirectory !== undefined) ||\n\t\t\t(value === ENGINE_SESSION_STORAGE_FLAG && (sessionDirectory !== undefined || sessionId === undefined))\n\t\t) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push(value);\n\t}\n\tif (sessionId === undefined) result.push(\"--no-session\");\n\telse result.push(\"--session\", sessionId);\n\tif (sessionDirectory !== undefined) result.push(\"--session-dir\", sessionDirectory);\n\treturn result;\n}\n\nconst MAX_STDERR_BYTES = 256 * 1024;\n\n/** Keep only the tail of a child's stderr, so a noisy child cannot grow the host. */\nexport function appendBoundedStderr(existing: string, chunk: string): string {\n\tconst next = existing + chunk;\n\tif (Buffer.byteLength(next, \"utf8\") <= MAX_STDERR_BYTES) return next;\n\tconst marker = \"\\n[stderr truncated]\";\n\tconst bytes = Buffer.from(next);\n\tlet start = bytes.length - MAX_STDERR_BYTES + Buffer.byteLength(marker);\n\twhile (start < bytes.length && (bytes[start]! & 0xc0) === 0x80) start++;\n\treturn `${bytes.subarray(start).toString(\"utf8\")}${marker}`;\n}\n\n/** Batch noisy child output outside the pipe callback without filesystem work. */\nexport function createStderrReporter(report: (message: string) => void): (data: string) => void {\n\tlet pending = \"\";\n\tlet scheduled = false;\n\treturn (data) => {\n\t\tpending = appendBoundedStderr(pending, data);\n\t\tif (scheduled) return;\n\t\tscheduled = true;\n\t\tsetImmediate(() => {\n\t\t\tconst message = pending;\n\t\t\tpending = \"\";\n\t\t\tscheduled = false;\n\t\t\treport(message);\n\t\t});\n\t};\n}\n"]}
1
+ {"version":3,"file":"rpc-client-process.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EACN,iCAAiC,EAEjC,qCAAqC,EACrC,+BAA+B,GAC/B,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC;AAClF,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACvG,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAc7C,MAAM,aAAa,GAAG,IAAI,OAAO,EAAwB,CAAC;AAC1D,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAkD,CAAC;AAEvF,MAAM,UAAU,iCAAiC,CAChD,SAAkC,EAClC,OAAO,GAAsB,OAAO,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,UAAU,CAAC,MAAM,CAAC,CAAC;IACxE,OAAO,KAAK,GAAG,KAAK,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,KAAK,CAAE,GAAG,IAAI,CAAC,KAAK,IAAI;QAAE,KAAK,EAAE,CAAC;IACxE,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE,CAAC;AAC7D,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,oBAAoB,CAAC,MAAiC;IACrE,IAAI,OAAO,GAAG,EAAE,CAAC;IACjB,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,OAAO,CAAC,IAAI,EAAE,EAAE;QACf,OAAO,GAAG,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC7C,IAAI,SAAS;YAAE,OAAO;QACtB,SAAS,GAAG,IAAI,CAAC;QACjB,YAAY,CAAC,GAAG,EAAE;YACjB,MAAM,OAAO,GAAG,OAAO,CAAC;YACxB,OAAO,GAAG,EAAE,CAAC;YACb,SAAS,GAAG,KAAK,CAAC;YAClB,MAAM,CAAC,OAAO,CAAC,CAAC;QACjB,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { markLifecycleTiming } from \"../../core/lifecycle-timings.ts\";\nimport { ENGINE_SESSION_STORAGE_FLAG } from \"../../core/session-storage.js\";\nimport { createChildProcessEnvironment } from \"../../utils/child-process.ts\";\nimport { flushPersistentCompileCache } from \"../../utils/compile-cache.ts\";\nimport {\n\tINTERACTIVE_ENGINE_BOOTSTRAP_FLAG,\n\ttype InteractiveEngineBootstrapHandle,\n\tremoveOwnedInteractiveEngineBootstrap,\n\twriteInteractiveEngineBootstrap,\n} from \"../../utils/interactive-engine-bootstrap.ts\";\nimport { scrubInteractiveEngineEnv } from \"../../utils/interactive-engine-env.ts\";\nimport { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from \"../../utils/shell.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\n\nexport interface RpcClientProcessOptions {\n\tcliPath: string;\n\tcliArgs: string[];\n\tcwd?: string;\n\tenv?: Record<string, string>;\n\truntimeExecutable?: string;\n\truntimeArgs?: string[];\n\tinteractiveEngine: boolean;\n\t/** Credential handed to the engine child through the bootstrap file, never argv or env. */\n\tinteractiveEngineApiKey?: string;\n}\n\nconst guardianFiles = new WeakMap<ChildProcess, string>();\nconst bootstrapHandles = new WeakMap<ChildProcess, InteractiveEngineBootstrapHandle>();\n\nexport function createRpcClientProcessEnvironment(\n\toverrides?: Record<string, string>,\n\tbaseEnv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n\treturn scrubInteractiveEngineEnv(createChildProcessEnvironment(overrides, baseEnv));\n}\n\nexport function spawnRpcClientProcess(options: RpcClientProcessOptions): ChildProcess {\n\tconst guardianFile = options.interactiveEngine\n\t\t? join(tmpdir(), `atomic-engine-guardian-${process.pid}-${crypto.randomUUID()}`)\n\t\t: undefined;\n\t// The engine's startup metadata travels in a 0600 file rather than the\n\t// environment: a Bun child spawned without an explicit `env` inherits the\n\t// runtime's launch-time environment, so anything placed here would remain\n\t// reachable by every descendant of the engine no matter what the engine\n\t// deletes from its own `process.env` afterwards.\n\tconst bootstrap = options.interactiveEngine\n\t\t? writeInteractiveEngineBootstrap({\n\t\t\t\thostPid: process.pid,\n\t\t\t\tguardFile: guardianFile!,\n\t\t\t\t...(options.interactiveEngineApiKey ? { apiKey: options.interactiveEngineApiKey } : {}),\n\t\t\t})\n\t\t: undefined;\n\tif (options.interactiveEngine) flushPersistentCompileCache();\n\tconst cliArgs = bootstrap\n\t\t? [...options.cliArgs, INTERACTIVE_ENGINE_BOOTSTRAP_FLAG, bootstrap.path]\n\t\t: options.cliArgs;\n\tlet child: ChildProcess;\n\ttry {\n\t\tif (options.interactiveEngine) markLifecycleTiming(\"interactive-engine-spawn\");\n\t\tchild = spawn(\n\t\t\toptions.runtimeExecutable ?? \"bun\",\n\t\t\t[...(options.runtimeArgs ?? []), ...(options.cliPath ? [options.cliPath] : []), ...cliArgs],\n\t\t\t{\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenv: createRpcClientProcessEnvironment(options.env),\n\t\t\t\tdetached: options.interactiveEngine && process.platform !== \"win32\",\n\t\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tremoveOwnedInteractiveEngineBootstrap(bootstrap);\n\t\tthrow error;\n\t}\n\tif (guardianFile) guardianFiles.set(child, guardianFile);\n\tif (bootstrap) {\n\t\tbootstrapHandles.set(child, bootstrap);\n\t\t// The child unlinks the record after reading it; this handle-scoped cleanup\n\t\t// removes the directory this process created, and only that directory.\n\t\tchild.once(\"error\", () => removeOwnedInteractiveEngineBootstrap(bootstrap));\n\t\tchild.once(\"exit\", () => removeOwnedInteractiveEngineBootstrap(bootstrap));\n\t}\n\tif (options.interactiveEngine && child.pid) {\n\t\ttrackDetachedChildPid(child.pid);\n\t\tchild.once(\"exit\", () => untrackDetachedChildPid(child.pid!));\n\t}\n\treturn child;\n}\n\n/**\n * How long a SIGTERMed interactive engine may spend running extension\n * `session_shutdown` handlers before its guardian and then a tree kill take over.\n * Builtin shutdown (MCP servers, durable workflow storage) routinely exceeds a\n * few hundred milliseconds on a loaded machine.\n */\nexport const ENGINE_SHUTDOWN_GRACE_MS = 5_000;\nconst RPC_CHILD_SHUTDOWN_GRACE_MS = 250;\n/**\n * How long a force-killed child may take to have its exit reported before stop\n * declares it unkillable. On Windows SIGTERM and SIGKILL both become\n * TerminateProcess, which only starts termination, and a loaded runner has\n * reported such an exit more than 500 ms later.\n */\nconst KILLED_CHILD_EXIT_REPORT_MS = 5_000;\n\nasync function exitsWithin(exited: Promise<void>, ms: number): Promise<boolean> {\n\tconst deadline = new AbortController();\n\ttry {\n\t\treturn await Promise.race([exited.then(() => true), sleep(ms, deadline.signal).then(() => false)]);\n\t} finally {\n\t\tdeadline.abort();\n\t}\n}\n\nexport async function terminateRpcClientProcess(child: ChildProcess, processTree: boolean): Promise<void> {\n\tremoveOwnedInteractiveEngineBootstrap(bootstrapHandles.get(child));\n\tif (child.exitCode !== null || child.signalCode !== null) return;\n\tlet resolveExit!: () => void;\n\tconst exited = new Promise<void>((resolve) => {\n\t\tresolveExit = resolve;\n\t});\n\tchild.once(\"exit\", resolveExit);\n\tconst guardianFile = guardianFiles.get(child);\n\tchild.kill(\"SIGTERM\");\n\tif (await exitsWithin(exited, processTree ? ENGINE_SHUTDOWN_GRACE_MS : RPC_CHILD_SHUTDOWN_GRACE_MS)) {\n\t\tif (guardianFile) await rm(guardianFile, { force: true });\n\t\treturn;\n\t}\n\tif (processTree && guardianFile) {\n\t\tawait writeFile(guardianFile, \"stop\");\n\t\tif (await exitsWithin(exited, 500)) {\n\t\t\tawait rm(guardianFile, { force: true });\n\t\t\treturn;\n\t\t}\n\t}\n\tif (processTree && child.pid) killProcessTree(child.pid);\n\telse child.kill(\"SIGKILL\");\n\tif (!(await exitsWithin(exited, KILLED_CHILD_EXIT_REPORT_MS))) {\n\t\tthrow new Error(`Agent process ${child.pid ?? \"unknown\"} did not exit after SIGKILL`);\n\t}\n\tif (guardianFile) await rm(guardianFile, { force: true });\n}\n\nexport function createInteractiveJsonlOptions(enabled: boolean): { maxBytesPerTurn?: number } {\n\treturn enabled ? { maxBytesPerTurn: 256 * 1024 } : {};\n}\n\n/**\n * CLI args for a replacement engine child: drop whatever session flag the\n * previous generation carried and bind the replacement to `sessionId`, so a\n * restart resumes the same conversation instead of starting a fresh one.\n */\nexport function restartCliArgs(\n\targs: readonly string[] | undefined,\n\tsessionId: string | undefined,\n\tsessionDirectory?: string,\n): string[] {\n\tconst result: string[] = [];\n\tfor (let index = 0; index < (args?.length ?? 0); index += 1) {\n\t\tconst value = args![index]!;\n\t\tif (\n\t\t\tvalue === \"--no-session\" ||\n\t\t\tvalue === \"--continue\" ||\n\t\t\tvalue === \"-c\" ||\n\t\t\tvalue === \"--resume\" ||\n\t\t\tvalue === \"-r\"\n\t\t)\n\t\t\tcontinue;\n\t\tif (\n\t\t\tvalue === \"--session\" ||\n\t\t\tvalue === \"--session-id\" ||\n\t\t\tvalue === \"--fork\" ||\n\t\t\tvalue === \"--import\" ||\n\t\t\t(value === \"--session-dir\" && sessionDirectory !== undefined) ||\n\t\t\t(value === ENGINE_SESSION_STORAGE_FLAG && (sessionDirectory !== undefined || sessionId === undefined))\n\t\t) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push(value);\n\t}\n\tif (sessionId === undefined) result.push(\"--no-session\");\n\telse result.push(\"--session\", sessionId);\n\tif (sessionDirectory !== undefined) result.push(\"--session-dir\", sessionDirectory);\n\treturn result;\n}\n\nconst MAX_STDERR_BYTES = 256 * 1024;\n\n/** Keep only the tail of a child's stderr, so a noisy child cannot grow the host. */\nexport function appendBoundedStderr(existing: string, chunk: string): string {\n\tconst next = existing + chunk;\n\tif (Buffer.byteLength(next, \"utf8\") <= MAX_STDERR_BYTES) return next;\n\tconst marker = \"\\n[stderr truncated]\";\n\tconst bytes = Buffer.from(next);\n\tlet start = bytes.length - MAX_STDERR_BYTES + Buffer.byteLength(marker);\n\twhile (start < bytes.length && (bytes[start]! & 0xc0) === 0x80) start++;\n\treturn `${bytes.subarray(start).toString(\"utf8\")}${marker}`;\n}\n\n/** Batch noisy child output outside the pipe callback without filesystem work. */\nexport function createStderrReporter(report: (message: string) => void): (data: string) => void {\n\tlet pending = \"\";\n\tlet scheduled = false;\n\treturn (data) => {\n\t\tpending = appendBoundedStderr(pending, data);\n\t\tif (scheduled) return;\n\t\tscheduled = true;\n\t\tsetImmediate(() => {\n\t\t\tconst message = pending;\n\t\t\tpending = \"\";\n\t\t\tscheduled = false;\n\t\t\treport(message);\n\t\t});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,EAAE,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GAC5E,OAAO,CAAC,UAAU,CAAC,CAErB;IACD,SAAS,IAAI,MAAM,CAElB;IAED,WAAW,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAE1C;IACD,aAAa,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAElD;IACK,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,EAAE,OAAO,SAAQ,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAUlG;IACD,OAAO,CAAC,UAAU;IAmBlB,OAAO,CAAC,SAAS;IAIjB,OAAO,CAAC,4BAA4B;IASpC,OAAO,CAAC,sBAAsB;IAG9B,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,+BAA+B;IA6BvC;;;OAGG;IACH,OAAO,CAAC,cAAc;IAatB,kFAAkF;IAClF,OAAO,CAAC,kBAAkB;IAK1B,OAAO,CAAC,sBAAsB;IAmB9B,OAAO,CAAC,aAAa;IASrB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,UAAU;IAWlB,UAAgB,OAAO,CAAC,OAAO,EAAE,cAAc,EAAE,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CA4CzG;IACD,OAAO,CAAC,aAAa;IAYrB,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,QAAQ,EAAE,WAAW,GAAG,CAAC,CAI1C;CACD"}
@@ -388,7 +388,13 @@ export class RpcClient extends RpcClientApi {
388
388
  }
389
389
  async promptAndWait(message, images, timeout = 60000) {
390
390
  const eventsPromise = this.collectEvents(timeout);
391
- await this.prompt(message, images);
391
+ const accepted = this.prompt(message, images);
392
+ // A prompt has no request deadline, so `timeout` must also end the wait while
393
+ // the prompt is still unacknowledged. Whichever settles first decides; both are
394
+ // observed so the loser's later rejection is never an unhandled rejection.
395
+ eventsPromise.catch(() => { });
396
+ accepted.catch(() => { });
397
+ await Promise.race([accepted, eventsPromise]);
392
398
  return eventsPromise;
393
399
  }
394
400
  handleLine(line, generation) {
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAO7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAC;AACnF,OAAO,EAAE,sBAAsB,EAAE,MAAM,mDAAmD,CAAC;AAC3F,OAAO,EAIN,+BAA+B,GAC/B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AACxE,OAAO,EACN,mBAAmB,EACnB,6BAA6B,EAC7B,oBAAoB,EACpB,cAAc,EACd,qBAAqB,EACrB,yBAAyB,GACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACjG,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACvH,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAuCtF,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AC;QACD,OAAO,QAAQ,CAAC;IACjB,CAAC;IACO,aAAa,CAAC,QAAqB;QAC1C,IAAI,QAAQ,CAAC,OAAO;YAAE,OAAO;QAC7B,IAAI,QAAQ,CAAC,SAAS,KAAK,4BAA4B,IAAI,QAAQ,CAAC,YAAY,EAAE,CAAC;YAClF,MAAM,IAAI,8BAA8B,CACvC,QAAQ,CAAC,YAAY,CAAC,UAAU,EAChC,QAAQ,CAAC,YAAY,CAAC,SAAS,EAC/B,SAAS,EACT,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CACpC,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IACS,IAAI,CAAI,QAAqB;QACtC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC7B,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAClC,CAAC;CACD","sourcesContent":["import type { ChildProcess } from \"node:child_process\";\nimport type { ImageContent } from \"@bastani/pi-ai/compat\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { WorkflowActivityFrame } from \"../../core/extensions/workflow-events.js\";\nimport { CredentialSynchronizationError } from \"../../core/model-runtime.js\";\nimport type { BashOutputChannel } from \"../../core/tools/bash.js\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport type { ActivityWatchdogDiagnostic } from \"../interactive-engine/activity-watchdog.ts\";\nimport type {\n\tInteractiveEngineGenerationEnded,\n\tInteractiveEngineGenerationEndedListener,\n\tInteractiveEngineGenerationEndKind,\n} from \"../interactive-engine/engine-generation.ts\";\nimport { InteractiveEngineMonitor } from \"../interactive-engine/engine-monitor.ts\";\nimport { WorkflowActivityMirror } from \"../interactive-engine/engine-workflow-activity.ts\";\nimport {\n\ttype EngineKeybindingState,\n\ttype InteractiveEngineCommand,\n\ttype InteractiveEngineMessage,\n\tserializeInteractiveEngineFrame,\n} from \"../interactive-engine/protocol.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport { QueuedWriter } from \"./queued-writer.ts\";\nimport { RpcClientApi, type RpcCommandBody } from \"./rpc-client-api.ts\";\nimport {\n\tappendBoundedStderr,\n\tcreateInteractiveJsonlOptions,\n\tcreateStderrReporter,\n\trestartCliArgs,\n\tspawnRpcClientProcess,\n\tterminateRpcClientProcess,\n} from \"./rpc-client-process.js\";\nimport { collectRpcEvents, runUserBashWithUpdates, waitForRpcIdle } from \"./rpc-client-waits.ts\";\nimport { DEFAULT_REQUEST_TIMEOUT_MS, LONG_LIVED_COMMANDS, RESTART_CANCELLED_MESSAGE } from \"./rpc-command-timeouts.ts\";\nimport { RpcEventBuffer } from \"./rpc-event-buffer.ts\";\nimport { GenerationBuffer } from \"./rpc-generation-buffer.ts\";\nimport { RpcPendingRequests } from \"./rpc-pending-requests.ts\";\nimport { RpcTerminalDrain } from \"./rpc-terminal-drain.ts\";\nimport { markRpcTransportFailure, rpcTransportError } from \"./rpc-transport-error.ts\";\nimport type { RpcCommand, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse } from \"./rpc-types.ts\";\n\nexport type { ModelInfo, RpcCommandBody } from \"./rpc-client-api.ts\";\nexport type { RpcEvent } from \"./rpc-types.ts\";\n\nexport interface RpcClientOptions {\n\tcliPath?: string;\n\tcwd?: string;\n\tenv?: Record<string, string>;\n\tprovider?: string;\n\tmodel?: string;\n\targs?: string[];\n\truntimeExecutable?: string;\n\truntimeArgs?: string[];\n\t/**\n\t * Bounded deadline (ms) applied to short metadata/control requests. Long-lived\n\t * commands (see LONG_LIVED_COMMANDS) never use this timer. Defaults to 30s.\n\t */\n\trequestTimeoutMs?: number;\n\tinteractiveEngine?: {\n\t\tonDiagnostic: (diagnostic: ActivityWatchdogDiagnostic) => void;\n\t\tonActivityChange?: (active: boolean) => void;\n\t\t/**\n\t\t * Heartbeat observer. Deliberately NOT a generic engine-message listener:\n\t\t * subscribing there drains the buffered startup custom-UI messages into the\n\t\t * first subscriber and stops buffering for the real controllers.\n\t\t */\n\t\tonHeartbeat?: () => void;\n\t\t/**\n\t\t * Credential for the engine child. Delivered through the protected\n\t\t * bootstrap file, never through the child's environment or argv.\n\t\t */\n\t\tapiKey?: string;\n\t};\n}\n\nexport type RpcEventListener = (event: RpcEvent) => void;\n\n/** Longest an explicit quit waits for the child to acknowledge it before stopping an unresponsive engine anyway. */\nconst EXPLICIT_QUIT_ACK_TIMEOUT_MS = 1000;\n\nexport class RpcClient extends RpcClientApi {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate extensionUIListeners: Array<(request: RpcExtensionUIRequest) => void> = [];\n\tprivate readonly pendingExtensionUIRequests = new GenerationBuffer<RpcExtensionUIRequest>();\n\tprivate engineMessageListeners: Array<(message: InteractiveEngineMessage) => void> = [];\n\tprivate latestEngineKeybindingState: EngineKeybindingState | undefined;\n\tprivate readonly workflowActivity = new WorkflowActivityMirror();\n\tprivate readonly pendingEngineMessages = new GenerationBuffer<InteractiveEngineMessage>();\n\tprivate readonly pendingProjectTrustFrames = new GenerationBuffer<string>();\n\tprivate boundGeneration = 0;\n\tprivate explicitQuitAck: { generation: number; acknowledge: () => void } | undefined;\n\tprivate readonly pendingRequests = new RpcPendingRequests();\n\t/** Bumped by every explicit stop; a restart holds a permit across its own stop. */\n\tprivate restartRevision = 0;\n\tprivate stopPromise: Promise<void> | undefined;\n\tprivate readonly terminalDrain = new RpcTerminalDrain();\n\tprivate stdoutDrained: Promise<void> = Promise.resolve();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate exitError: Error | null = null;\n\tprivate engineMonitor: InteractiveEngineMonitor | undefined;\n\tprivate eventBuffer: RpcEventBuffer | undefined;\n\tprivate stdinWriter: QueuedWriter | undefined;\n\tprivate generation = 0;\n\tprivate lastEndedGeneration = 0;\n\tprivate generationEndedListeners: InteractiveEngineGenerationEndedListener[] = [];\n\t/**\n\t * The latest generation-end event, retained so a subscriber that attaches\n\t * after the child died still observes it. A child can exit between\n\t * `start()` returning and the runtime constructing its listeners.\n\t */\n\tprivate retainedGenerationEnd: InteractiveEngineGenerationEnded | undefined;\n\tprivate readonly activeActivityIds = new Set<string>();\n\tprivate enginePid: number | undefined;\n\n\tprivate declare options: RpcClientOptions;\n\n\tconstructor(options: RpcClientOptions = {}) {\n\t\tsuper();\n\t\tthis.options = options;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tconst generation = ++this.generation;\n\t\tthis.exitError = null;\n\t\tthis.stderr = \"\";\n\t\tthis.activeActivityIds.clear();\n\t\tthis.enginePid = undefined;\n\t\tthis.engineMonitor = this.options.interactiveEngine\n\t\t\t? new InteractiveEngineMonitor(this.options.interactiveEngine.onDiagnostic, (message) =>\n\t\t\t\t\tthis.observeInteractiveEngineMessage(message, generation),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tthis.eventBuffer = this.engineMonitor ? new RpcEventBuffer((event) => this.emitEvent(event)) : undefined;\n\t\tconst childProcess = spawnRpcClientProcess({\n\t\t\tcliPath,\n\t\t\tcliArgs: args,\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: this.options.env,\n\t\t\truntimeExecutable: this.options.runtimeExecutable,\n\t\t\truntimeArgs: this.options.runtimeArgs,\n\t\t\tinteractiveEngine: this.engineMonitor !== undefined,\n\t\t\t...(this.options.interactiveEngine?.apiKey\n\t\t\t\t? { interactiveEngineApiKey: this.options.interactiveEngine.apiKey }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.process = childProcess;\n\t\tthis.stdinWriter = new QueuedWriter(childProcess.stdin!);\n\n\t\tchildProcess.once(\"exit\", (code, signal) =>\n\t\t\tthis.failGeneration(this.createProcessExitError(code, signal), generation, \"exit\"),\n\t\t);\n\t\tchildProcess.once(\"error\", (rawError) => this.failGeneration(rawError, generation, \"process-error\"));\n\t\tchildProcess.stdin?.on(\"error\", (rawError) => this.failGeneration(rawError, generation, \"stdin-error\"));\n\t\tconst reportStderr = createStderrReporter((message) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tif (this.options.interactiveEngine) {\n\t\t\t\tthis.options.interactiveEngine.onDiagnostic({\n\t\t\t\t\tactivity: undefined,\n\t\t\t\t\telapsedMs: 0,\n\t\t\t\t\tlevel: \"blocking\",\n\t\t\t\t\tsource: \"stderr\",\n\t\t\t\t\tmessage,\n\t\t\t\t});\n\t\t\t} else console.log(message);\n\t\t});\n\t\t// Decode continuously per child, including split code points and the final incomplete sequence at EOF.\n\t\tchildProcess.stderr?.setEncoding(\"utf8\");\n\t\tchildProcess.stderr?.on(\"data\", (data: string) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tthis.stderr = appendBoundedStderr(this.stderr, data);\n\t\t\treportStderr(data);\n\t\t});\n\t\tconst readerOptions = createInteractiveJsonlOptions(this.engineMonitor !== undefined);\n\t\tlet markStdoutDrained!: () => void;\n\t\tthis.stdoutDrained = new Promise<void>((resolve) => {\n\t\t\tmarkStdoutDrained = resolve;\n\t\t});\n\t\tthis.stopReadingStdout = attachJsonlLineReader(\n\t\t\tchildProcess.stdout!,\n\t\t\t(line) => {\n\t\t\t\tif (generation === this.generation) this.handleLine(line, generation);\n\t\t\t},\n\t\t\t{ ...readerOptions, onDrained: () => markStdoutDrained() },\n\t\t);\n\t\tif (this.engineMonitor) await this.engineMonitor.waitUntilReady();\n\t\telse await sleep(100);\n\n\t\tif (generation !== this.generation || this.process?.exitCode !== null) {\n\t\t\tthrow rpcTransportError(`Agent process exited immediately. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Tell the engine child the host is quitting on purpose, and wait (bounded) for it to\n\t * record that. Call it before `stop()` for a quit the user asked for: stopping closes\n\t * stdin and sends SIGTERM, which is also how the child is stopped when the host itself\n\t * was signalled, so only this announcement lets the child tell the two apart.\n\t * Resolves true only when the child acknowledged the quit, and false without waiting when\n\t * there is no live engine child, or when the child exits or misses the deadline first.\n\t */\n\tasync announceExplicitQuit(timeoutMs = EXPLICIT_QUIT_ACK_TIMEOUT_MS): Promise<boolean> {\n\t\tconst writer = this.stdinWriter;\n\t\tif (!writer || !this.engineMonitor || this.generation <= this.lastEndedGeneration) return false;\n\t\tconst generation = this.generation;\n\t\tconst done = Promise.withResolvers<boolean>();\n\t\tthis.explicitQuitAck = { generation, acknowledge: () => done.resolve(true) };\n\t\tconst stopListening = this.onGenerationEnded((event) => {\n\t\t\tif (event.generation === generation) done.resolve(false);\n\t\t});\n\t\tconst timer = setTimeout(() => done.resolve(false), timeoutMs);\n\t\ttry {\n\t\t\tthis.bestEffort(\n\t\t\t\twriter.write(serializeInteractiveEngineFrame({ type: \"engine_explicit_quit\" })),\n\t\t\t\t\"explicit quit\",\n\t\t\t);\n\t\t\treturn await done.promise;\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tstopListening();\n\t\t\tif (this.explicitQuitAck?.generation === generation) this.explicitQuitAck = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Explicit stop. Voids any in-flight restart permit, so a replacement caught\n\t * between its own stop and start can never spawn after this returns.\n\t */\n\tstop(): Promise<void> {\n\t\tthis.restartRevision += 1;\n\t\tif (this.stopPromise) return this.stopPromise;\n\t\tif (!this.process) return Promise.resolve();\n\t\tconst stopPromise = this.stopCurrentGeneration().finally(() => {\n\t\t\tif (this.stopPromise === stopPromise) this.stopPromise = undefined;\n\t\t});\n\t\tthis.stopPromise = stopPromise;\n\t\treturn stopPromise;\n\t}\n\n\t/**\n\t * Tear down the current child without touching the restart permit. The reader\n\t * stays attached and the generation stays current until the dead child's\n\t * stdout settles, so an ownership frame it already sent still reaches its\n\t * request; only then is the generation retired (see RpcTerminalDrain).\n\t */\n\tprivate async stopCurrentGeneration(): Promise<void> {\n\t\tconst child = this.process;\n\t\tif (!child) return;\n\t\tconst endedGeneration = this.generation;\n\t\tconst stopError = rpcTransportError(\"Agent process stopped\");\n\t\tthis.invalidateEngineShortcuts();\n\t\tconst terminateTree = this.engineMonitor !== undefined;\n\t\tthis.engineMonitor?.stop();\n\t\tthis.stdinWriter?.close(stopError);\n\t\t// Unblock an in-flight start()/waitUntilBound() for the generation being\n\t\t// replaced. Readiness has no deadline by design, so without this an\n\t\t// explicit stop of a hung replacement child could never be observed.\n\t\tthis.engineMonitor?.fail(stopError);\n\t\tthis.engineMonitor = undefined;\n\t\tthis.stdinWriter = undefined;\n\t\tthis.process = null;\n\t\t// Publish before terminating so host controllers tear down this generation's\n\t\t// UI while the writer is detached: disposal cannot write into a replacement.\n\t\tthis.publishGenerationEnded(endedGeneration, stopError, \"explicit-stop\", true);\n\t\t// Claim before terminating so the exit this provokes does not relabel a\n\t\t// deliberate stop; an exit that already claimed keeps its own error.\n\t\tthis.terminalDrain.claim(endedGeneration, stopError);\n\t\tawait terminateRpcClientProcess(child, terminateTree);\n\t\tawait this.beginTerminalDrain(endedGeneration, stopError);\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.generation += 1;\n\t\tthis.pendingRequests.rejectAll(stopError);\n\t\tthis.eventBuffer?.dispose();\n\t\tthis.eventBuffer = undefined;\n\t\tthis.activeActivityIds.clear();\n\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t}\n\n\t/** Subscribe to agent events. */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\tonExtensionUIRequest(listener: (request: RpcExtensionUIRequest) => void): () => void {\n\t\tthis.extensionUIListeners.push(listener);\n\t\tfor (const request of this.pendingExtensionUIRequests.drain(this.generation)) listener(request);\n\t\treturn () => {\n\t\t\tconst index = this.extensionUIListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.extensionUIListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tasync respondExtensionUI(response: RpcExtensionUIResponse): Promise<void> {\n\t\tawait this.requireWriter().write(serializeJsonLine(response));\n\t}\n\n\tonInteractiveEngineMessage(listener: (message: InteractiveEngineMessage) => void): () => void {\n\t\tthis.engineMessageListeners.push(listener);\n\t\tfor (const message of this.pendingEngineMessages.drain(this.generation)) listener(message);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tonInteractiveEngineKeybindingState(listener: (state: EngineKeybindingState) => void): () => void {\n\t\tconst messageListener = (message: InteractiveEngineMessage): void => {\n\t\t\tif (message.type === \"engine_keybindings_reloaded\") listener(message.state);\n\t\t};\n\t\tthis.engineMessageListeners.push(messageListener);\n\t\tif (this.latestEngineKeybindingState) listener(this.latestEngineKeybindingState);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(messageListener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to the engine's workflow activity. The engine publishes its snapshot as soon as it binds,\n\t * so an observer that attaches later starts from the current snapshot instead of missing it.\n\t */\n\tonInteractiveEngineWorkflowActivity(listener: (frame: WorkflowActivityFrame) => void): () => void {\n\t\tconst messageListener = (message: InteractiveEngineMessage): void => {\n\t\t\tif (message.type === \"engine_workflow_activity\") listener(message.frame);\n\t\t};\n\t\tthis.engineMessageListeners.push(messageListener);\n\t\tconst current = this.workflowActivity.current();\n\t\tif (current) listener(current);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(messageListener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to host-local generation death. Fires at most once per\n\t * generation, synchronously, before any restart work. A death that has\n\t * already happened for the current generation replays immediately, so a\n\t * listener attached after an exit still sees it.\n\t */\n\tonGenerationEnded(listener: InteractiveEngineGenerationEndedListener): () => void {\n\t\tthis.generationEndedListeners.push(listener);\n\t\tconst retained = this.retainedGenerationEnd;\n\t\t// Only while it still describes the live generation: once stop()/start()\n\t\t// has moved on, that death belongs to a replaced child.\n\t\tif (retained && retained.generation === this.generation) listener(retained);\n\t\treturn () => {\n\t\t\tconst index = this.generationEndedListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.generationEndedListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tsendInteractiveEngineCommand(command: InteractiveEngineCommand): void {\n\t\tconst writer = this.stdinWriter;\n\t\tif (command.type === \"engine_project_trust_start\" || command.type === \"engine_project_trust_end\") {\n\t\t\tif (this.generation <= this.lastEndedGeneration) return;\n\t\t\t// The terminal can open and close /trust while the engine is still binding.\n\t\t\t// Retain both frames, without delaying the host-owned decision.\n\t\t\tif (this.engineMonitor && this.boundGeneration !== this.generation) {\n\t\t\t\tthis.pendingProjectTrustFrames.push(this.generation, serializeInteractiveEngineFrame(command));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (!writer) return;\n\t\tconst frame = serializeInteractiveEngineFrame(command);\n\t\tif (\n\t\t\tcommand.type === \"engine_custom_render\" ||\n\t\t\tcommand.type === \"engine_tool_render\" ||\n\t\t\tcommand.type === \"engine_message_render\"\n\t\t) {\n\t\t\twriter.offerLatest(`render:${command.componentId}`, frame);\n\t\t\treturn;\n\t\t}\n\t\tthis.bestEffort(writer.write(frame), `engine command ${command.type}`);\n\t}\n\twaitForInteractiveEngineBound(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilBound() ?? Promise.resolve();\n\t}\n\twaitForInteractiveEngineProjectTrust(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilProjectTrustSettled() ?? Promise.resolve();\n\t}\n\twaitForInteractiveEngineResources(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilResourcesReady() ?? Promise.resolve();\n\t}\n\tgetEnginePid(): number | undefined {\n\t\treturn this.enginePid;\n\t}\n\tgetGeneration(): number {\n\t\treturn this.generation;\n\t}\n\n\t/**\n\t * Replace the engine child, unless an explicit stop supersedes this attempt.\n\t * The permit is checked immediately before spawning, so a `stop()` in that\n\t * window is always observed; cancellation throws rather than returning\n\t * quietly, because callers go on to initialize against the new child.\n\t */\n\tasync restart(sessionId: string | undefined, options?: { sessionDirectory?: string; cwd?: string }): Promise<void> {\n\t\tconst permit = this.restartRevision;\n\t\tawait this.stopCurrentGeneration();\n\t\t// Join an in-flight stop before the permit check: waiting after it would\n\t\t// reopen the window this fence exists to close.\n\t\tif (this.stopPromise) await this.stopPromise;\n\t\tif (permit !== this.restartRevision) throw rpcTransportError(RESTART_CANCELLED_MESSAGE);\n\t\tthis.options = {\n\t\t\t...this.options,\n\t\t\tcwd: options?.cwd ?? this.options.cwd,\n\t\t\targs: restartCliArgs(this.options.args, sessionId, options?.sessionDirectory),\n\t\t};\n\t\tawait this.start();\n\t\tawait this.waitForInteractiveEngineBound();\n\t}\n\n\tasync requestInternal<T>(command: RpcCommandBody): Promise<T> {\n\t\treturn this.data<T>(await this.request(command));\n\t}\n\tuserBashWithUpdates(\n\t\tcommand: string,\n\t\tonUpdate: (delta: string, channel: BashOutputChannel) => void,\n\t\toptions?: { excludeFromContext?: boolean; onRequestId?: (id: string) => void },\n\t): Promise<BashResult> {\n\t\treturn runUserBashWithUpdates(this, command, onUpdate, options, (body, onId) => this.request(body, onId));\n\t}\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn waitForRpcIdle(this, timeout);\n\t}\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn collectRpcEvents(this, timeout);\n\t}\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\tprivate handleLine(line: string, generation: number): void {\n\t\tif (this.terminalDrain.observe(generation, line, (id) => this.pendingRequests.markAccepted(id))) return;\n\t\tif (this.engineMonitor?.handleLine(line)) return;\n\t\ttry {\n\t\t\tconst data = JSON.parse(line) as { type?: string; id?: string };\n\t\t\tif (data.type === \"extension_ui_request\") {\n\t\t\t\tconst request = data as RpcExtensionUIRequest;\n\t\t\t\tif (this.extensionUIListeners.length === 0) this.pendingExtensionUIRequests.push(generation, request);\n\t\t\t\tfor (const listener of this.extensionUIListeners) listener(request);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.resolve(data.id, data as RpcResponse)) return;\n\t\t\tconst event = data as RpcEvent;\n\t\t\tif (this.eventBuffer) this.eventBuffer.enqueue(event);\n\t\t\telse this.emitEvent(event);\n\t\t} catch {\n\t\t\tif (this.engineMonitor) this.failTransport(rpcTransportError(\"Interactive engine emitted malformed JSONL\"));\n\t\t}\n\t}\n\tprivate emitEvent(event: RpcEvent): void {\n\t\t// Iterate a snapshot so listeners that unsubscribe during dispatch do not make later listeners miss this event.\n\t\tfor (const listener of [...this.eventListeners]) listener(event);\n\t}\n\tprivate emitInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\tif (\n\t\t\tthis.engineMessageListeners.length === 0 &&\n\t\t\t(message.type.startsWith(\"engine_custom_\") || message.type.startsWith(\"engine_resources_\"))\n\t\t) {\n\t\t\tthis.pendingEngineMessages.push(generation, message);\n\t\t}\n\t\tfor (const listener of this.engineMessageListeners) listener(message);\n\t}\n\tprivate createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {\n\t\treturn rpcTransportError(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);\n\t}\n\tprivate invalidateEngineShortcuts(): void {\n\t\tif (!this.latestEngineKeybindingState || this.latestEngineKeybindingState.shortcuts.length === 0) return;\n\t\tconst state: EngineKeybindingState = { ...this.latestEngineKeybindingState, shortcuts: [] };\n\t\tthis.latestEngineKeybindingState = state;\n\t\tthis.emitInteractiveEngineMessage({ type: \"engine_keybindings_reloaded\", state }, this.generation);\n\t}\n\tprivate observeInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\t// Ownership is the one thing a dead generation may still report: request\n\t\t// ids never repeat, and the alternative is classifying work it already\n\t\t// started as never sent. Nothing else from it may touch host state — a\n\t\t// stale frame would revive a PID, an activity, or a mount that is gone.\n\t\tif (message.type === \"engine_request_accepted\") {\n\t\t\tif (generation === this.generation) this.pendingRequests.markAccepted(message.requestId);\n\t\t\treturn;\n\t\t}\n\t\tif (message.type === \"engine_explicit_quit_ack\") {\n\t\t\tif (this.explicitQuitAck?.generation === generation) this.explicitQuitAck.acknowledge();\n\t\t\treturn;\n\t\t}\n\t\tif (generation !== this.generation || generation <= this.lastEndedGeneration) return;\n\t\tif (message.type === \"engine_heartbeat\") this.options.interactiveEngine?.onHeartbeat?.();\n\t\tif (message.type === \"engine_ready\") this.enginePid = message.pid;\n\t\tif (message.type === \"engine_bound\") {\n\t\t\tthis.boundGeneration = generation;\n\t\t\tfor (const frame of this.pendingProjectTrustFrames.drain(generation)) {\n\t\t\t\tif (this.stdinWriter) this.bestEffort(this.stdinWriter.write(frame), \"project trust notification\");\n\t\t\t}\n\t\t}\n\t\tif (message.type === \"engine_keybindings_reloaded\") this.latestEngineKeybindingState = message.state;\n\t\tif (message.type === \"engine_workflow_activity\") this.workflowActivity.apply(message.frame);\n\t\tif (message.type === \"engine_activity_started\") this.activeActivityIds.add(message.activity.id);\n\t\telse if (message.type === \"engine_activity_finished\") this.activeActivityIds.delete(message.activityId);\n\t\tthis.options.interactiveEngine?.onActivityChange?.(this.activeActivityIds.size > 0);\n\t\tthis.emitInteractiveEngineMessage(message, generation);\n\t}\n\t/**\n\t * Shared teardown for every unexpected end of `generation`. Death publishes\n\t * at once for the host UI; its requests wait for stdout (RpcTerminalDrain).\n\t */\n\tprivate failGeneration(rawError: Error, generation: number, kind: InteractiveEngineGenerationEndKind): void {\n\t\tif (generation !== this.generation) return;\n\t\tconst error = markRpcTransportFailure(rawError);\n\t\tthis.exitError = error;\n\t\tthis.stdinWriter?.close(error);\n\t\tthis.engineMonitor?.fail(error);\n\t\tif (kind === \"exit\") {\n\t\t\tthis.activeActivityIds.clear();\n\t\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t\t}\n\t\tthis.beginTerminalDrain(generation, error);\n\t\tthis.publishGenerationEnded(generation, error, kind, false);\n\t}\n\t/** Hold this generation's requests until its stdout drains (RpcTerminalDrain). */\n\tprivate beginTerminalDrain(generation: number, error: Error): Promise<void> {\n\t\treturn this.terminalDrain.begin(generation, this.stdoutDrained, error, (settled) => {\n\t\t\tif (generation === this.generation) this.pendingRequests.rejectAll(settled);\n\t\t});\n\t}\n\tprivate publishGenerationEnded(\n\t\tgeneration: number,\n\t\terror: Error,\n\t\tkind: InteractiveEngineGenerationEndKind,\n\t\texpected: boolean,\n\t): void {\n\t\tif (generation <= this.lastEndedGeneration) return;\n\t\tthis.lastEndedGeneration = generation;\n\t\tconst event: InteractiveEngineGenerationEnded = { generation, error, kind, expected };\n\t\tthis.retainedGenerationEnd = event;\n\t\t// Death is a strict boundary: drop this generation's buffered frames\n\t\t// BEFORE teardown runs, so no listener can drain a stale mount frame\n\t\t// while it is closing that very generation's components.\n\t\tthis.pendingEngineMessages.dropGeneration(generation);\n\t\tthis.workflowActivity.reset();\n\t\tthis.pendingExtensionUIRequests.dropGeneration(generation);\n\t\tthis.pendingProjectTrustFrames.dropGeneration(generation);\n\t\tfor (const listener of [...this.generationEndedListeners]) listener(event);\n\t}\n\tprivate failTransport(rawError: Error): void {\n\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\tactivity: undefined,\n\t\t\telapsedMs: 0,\n\t\t\tlevel: \"unresponsive\",\n\t\t\tmessage: rawError.message,\n\t\t});\n\t\tthis.failGeneration(rawError, this.generation, \"transport-error\");\n\t}\n\tprivate requireWriter(): QueuedWriter {\n\t\tif (!this.stdinWriter) throw rpcTransportError(\"Agent process stdin is not writable\");\n\t\treturn this.stdinWriter;\n\t}\n\tprivate bestEffort(operation: Promise<void>, label: string): void {\n\t\tvoid operation.catch((error: Error) => {\n\t\t\tif (!this.process || this.exitError) return;\n\t\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\t\tactivity: undefined,\n\t\t\t\telapsedMs: 0,\n\t\t\t\tlevel: \"unresponsive\",\n\t\t\t\tmessage: `Interactive engine ${label} failed: ${error.message}`,\n\t\t\t});\n\t\t});\n\t}\n\tprotected async request(command: RpcCommandBody, onRequestId?: (id: string) => void): Promise<RpcResponse> {\n\t\tconst childProcess = this.process;\n\t\tif (!childProcess) throw rpcTransportError(\"Client not started\");\n\t\tif (this.exitError) throw this.exitError;\n\t\tif (childProcess.exitCode !== null) {\n\t\t\tconst error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t\tconst id = `req_${++this.requestId}`;\n\t\tonRequestId?.(id);\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\tlet rejectResponse!: (error: Error) => void;\n\t\tconst response = new Promise<RpcResponse>((resolve, reject) => {\n\t\t\trejectResponse = reject;\n\t\t\tthis.pendingRequests.add(id, {\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\t\t});\n\t\ttry {\n\t\t\tawait this.requireWriter().write(serializeJsonLine(fullCommand));\n\t\t} catch (error) {\n\t\t\tthis.pendingRequests.delete(id);\n\t\t\t// Idempotent: the writer already classified this, but a caller-supplied\n\t\t\t// stream can reject with anything, and a send that never left the host\n\t\t\t// is a transport failure whatever it threw.\n\t\t\trejectResponse(markRpcTransportFailure(error));\n\t\t\treturn response;\n\t\t}\n\t\tif (this.pendingRequests.has(id) && !LONG_LIVED_COMMANDS.has(command.type)) {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\trejectResponse(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);\n\t\t}\n\t\treturn response;\n\t}\n\tprivate assertSuccess(response: RpcResponse): void {\n\t\tif (response.success) return;\n\t\tif (response.errorCode === \"credential_synchronization\" && response.errorDetails) {\n\t\t\tthrow new CredentialSynchronizationError(\n\t\t\t\tresponse.errorDetails.providerId,\n\t\t\t\tresponse.errorDetails.operation,\n\t\t\t\tundefined,\n\t\t\t\t{ cause: new Error(response.error) },\n\t\t\t);\n\t\t}\n\t\tthrow new Error(response.error);\n\t}\n\tprotected data<T>(response: RpcResponse): T {\n\t\tthis.assertSuccess(response);\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
1
+ {"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAO7C,OAAO,EAAE,wBAAwB,EAA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AAC,OAAO;YAAE,OAAO;QAC7B,IAAI,QAAQ,CAAC,SAAS,KAAK,4BAA4B,IAAI,QAAQ,CAAC,YAAY,EAAE,CAAC;YAClF,MAAM,IAAI,8BAA8B,CACvC,QAAQ,CAAC,YAAY,CAAC,UAAU,EAChC,QAAQ,CAAC,YAAY,CAAC,SAAS,EAC/B,SAAS,EACT,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CACpC,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IACS,IAAI,CAAI,QAAqB;QACtC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC7B,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAClC,CAAC;CACD","sourcesContent":["import type { ChildProcess } from \"node:child_process\";\nimport type { ImageContent } from \"@bastani/pi-ai/compat\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { WorkflowActivityFrame } from \"../../core/extensions/workflow-events.js\";\nimport { CredentialSynchronizationError } from \"../../core/model-runtime.js\";\nimport type { BashOutputChannel } from \"../../core/tools/bash.js\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport type { ActivityWatchdogDiagnostic } from \"../interactive-engine/activity-watchdog.ts\";\nimport type {\n\tInteractiveEngineGenerationEnded,\n\tInteractiveEngineGenerationEndedListener,\n\tInteractiveEngineGenerationEndKind,\n} from \"../interactive-engine/engine-generation.ts\";\nimport { InteractiveEngineMonitor } from \"../interactive-engine/engine-monitor.ts\";\nimport { WorkflowActivityMirror } from \"../interactive-engine/engine-workflow-activity.ts\";\nimport {\n\ttype EngineKeybindingState,\n\ttype InteractiveEngineCommand,\n\ttype InteractiveEngineMessage,\n\tserializeInteractiveEngineFrame,\n} from \"../interactive-engine/protocol.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport { QueuedWriter } from \"./queued-writer.ts\";\nimport { RpcClientApi, type RpcCommandBody } from \"./rpc-client-api.ts\";\nimport {\n\tappendBoundedStderr,\n\tcreateInteractiveJsonlOptions,\n\tcreateStderrReporter,\n\trestartCliArgs,\n\tspawnRpcClientProcess,\n\tterminateRpcClientProcess,\n} from \"./rpc-client-process.js\";\nimport { collectRpcEvents, runUserBashWithUpdates, waitForRpcIdle } from \"./rpc-client-waits.ts\";\nimport { DEFAULT_REQUEST_TIMEOUT_MS, LONG_LIVED_COMMANDS, RESTART_CANCELLED_MESSAGE } from \"./rpc-command-timeouts.ts\";\nimport { RpcEventBuffer } from \"./rpc-event-buffer.ts\";\nimport { GenerationBuffer } from \"./rpc-generation-buffer.ts\";\nimport { RpcPendingRequests } from \"./rpc-pending-requests.ts\";\nimport { RpcTerminalDrain } from \"./rpc-terminal-drain.ts\";\nimport { markRpcTransportFailure, rpcTransportError } from \"./rpc-transport-error.ts\";\nimport type { RpcCommand, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse } from \"./rpc-types.ts\";\n\nexport type { ModelInfo, RpcCommandBody } from \"./rpc-client-api.ts\";\nexport type { RpcEvent } from \"./rpc-types.ts\";\n\nexport interface RpcClientOptions {\n\tcliPath?: string;\n\tcwd?: string;\n\tenv?: Record<string, string>;\n\tprovider?: string;\n\tmodel?: string;\n\targs?: string[];\n\truntimeExecutable?: string;\n\truntimeArgs?: string[];\n\t/**\n\t * Bounded deadline (ms) applied to short metadata/control requests. Long-lived\n\t * commands (see LONG_LIVED_COMMANDS) never use this timer. Defaults to 30s.\n\t */\n\trequestTimeoutMs?: number;\n\tinteractiveEngine?: {\n\t\tonDiagnostic: (diagnostic: ActivityWatchdogDiagnostic) => void;\n\t\tonActivityChange?: (active: boolean) => void;\n\t\t/**\n\t\t * Heartbeat observer. Deliberately NOT a generic engine-message listener:\n\t\t * subscribing there drains the buffered startup custom-UI messages into the\n\t\t * first subscriber and stops buffering for the real controllers.\n\t\t */\n\t\tonHeartbeat?: () => void;\n\t\t/**\n\t\t * Credential for the engine child. Delivered through the protected\n\t\t * bootstrap file, never through the child's environment or argv.\n\t\t */\n\t\tapiKey?: string;\n\t};\n}\n\nexport type RpcEventListener = (event: RpcEvent) => void;\n\n/** Longest an explicit quit waits for the child to acknowledge it before stopping an unresponsive engine anyway. */\nconst EXPLICIT_QUIT_ACK_TIMEOUT_MS = 1000;\n\nexport class RpcClient extends RpcClientApi {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate extensionUIListeners: Array<(request: RpcExtensionUIRequest) => void> = [];\n\tprivate readonly pendingExtensionUIRequests = new GenerationBuffer<RpcExtensionUIRequest>();\n\tprivate engineMessageListeners: Array<(message: InteractiveEngineMessage) => void> = [];\n\tprivate latestEngineKeybindingState: EngineKeybindingState | undefined;\n\tprivate readonly workflowActivity = new WorkflowActivityMirror();\n\tprivate readonly pendingEngineMessages = new GenerationBuffer<InteractiveEngineMessage>();\n\tprivate readonly pendingProjectTrustFrames = new GenerationBuffer<string>();\n\tprivate boundGeneration = 0;\n\tprivate explicitQuitAck: { generation: number; acknowledge: () => void } | undefined;\n\tprivate readonly pendingRequests = new RpcPendingRequests();\n\t/** Bumped by every explicit stop; a restart holds a permit across its own stop. */\n\tprivate restartRevision = 0;\n\tprivate stopPromise: Promise<void> | undefined;\n\tprivate readonly terminalDrain = new RpcTerminalDrain();\n\tprivate stdoutDrained: Promise<void> = Promise.resolve();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate exitError: Error | null = null;\n\tprivate engineMonitor: InteractiveEngineMonitor | undefined;\n\tprivate eventBuffer: RpcEventBuffer | undefined;\n\tprivate stdinWriter: QueuedWriter | undefined;\n\tprivate generation = 0;\n\tprivate lastEndedGeneration = 0;\n\tprivate generationEndedListeners: InteractiveEngineGenerationEndedListener[] = [];\n\t/**\n\t * The latest generation-end event, retained so a subscriber that attaches\n\t * after the child died still observes it. A child can exit between\n\t * `start()` returning and the runtime constructing its listeners.\n\t */\n\tprivate retainedGenerationEnd: InteractiveEngineGenerationEnded | undefined;\n\tprivate readonly activeActivityIds = new Set<string>();\n\tprivate enginePid: number | undefined;\n\n\tprivate declare options: RpcClientOptions;\n\n\tconstructor(options: RpcClientOptions = {}) {\n\t\tsuper();\n\t\tthis.options = options;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tconst generation = ++this.generation;\n\t\tthis.exitError = null;\n\t\tthis.stderr = \"\";\n\t\tthis.activeActivityIds.clear();\n\t\tthis.enginePid = undefined;\n\t\tthis.engineMonitor = this.options.interactiveEngine\n\t\t\t? new InteractiveEngineMonitor(this.options.interactiveEngine.onDiagnostic, (message) =>\n\t\t\t\t\tthis.observeInteractiveEngineMessage(message, generation),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tthis.eventBuffer = this.engineMonitor ? new RpcEventBuffer((event) => this.emitEvent(event)) : undefined;\n\t\tconst childProcess = spawnRpcClientProcess({\n\t\t\tcliPath,\n\t\t\tcliArgs: args,\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: this.options.env,\n\t\t\truntimeExecutable: this.options.runtimeExecutable,\n\t\t\truntimeArgs: this.options.runtimeArgs,\n\t\t\tinteractiveEngine: this.engineMonitor !== undefined,\n\t\t\t...(this.options.interactiveEngine?.apiKey\n\t\t\t\t? { interactiveEngineApiKey: this.options.interactiveEngine.apiKey }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.process = childProcess;\n\t\tthis.stdinWriter = new QueuedWriter(childProcess.stdin!);\n\n\t\tchildProcess.once(\"exit\", (code, signal) =>\n\t\t\tthis.failGeneration(this.createProcessExitError(code, signal), generation, \"exit\"),\n\t\t);\n\t\tchildProcess.once(\"error\", (rawError) => this.failGeneration(rawError, generation, \"process-error\"));\n\t\tchildProcess.stdin?.on(\"error\", (rawError) => this.failGeneration(rawError, generation, \"stdin-error\"));\n\t\tconst reportStderr = createStderrReporter((message) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tif (this.options.interactiveEngine) {\n\t\t\t\tthis.options.interactiveEngine.onDiagnostic({\n\t\t\t\t\tactivity: undefined,\n\t\t\t\t\telapsedMs: 0,\n\t\t\t\t\tlevel: \"blocking\",\n\t\t\t\t\tsource: \"stderr\",\n\t\t\t\t\tmessage,\n\t\t\t\t});\n\t\t\t} else console.log(message);\n\t\t});\n\t\t// Decode continuously per child, including split code points and the final incomplete sequence at EOF.\n\t\tchildProcess.stderr?.setEncoding(\"utf8\");\n\t\tchildProcess.stderr?.on(\"data\", (data: string) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tthis.stderr = appendBoundedStderr(this.stderr, data);\n\t\t\treportStderr(data);\n\t\t});\n\t\tconst readerOptions = createInteractiveJsonlOptions(this.engineMonitor !== undefined);\n\t\tlet markStdoutDrained!: () => void;\n\t\tthis.stdoutDrained = new Promise<void>((resolve) => {\n\t\t\tmarkStdoutDrained = resolve;\n\t\t});\n\t\tthis.stopReadingStdout = attachJsonlLineReader(\n\t\t\tchildProcess.stdout!,\n\t\t\t(line) => {\n\t\t\t\tif (generation === this.generation) this.handleLine(line, generation);\n\t\t\t},\n\t\t\t{ ...readerOptions, onDrained: () => markStdoutDrained() },\n\t\t);\n\t\tif (this.engineMonitor) await this.engineMonitor.waitUntilReady();\n\t\telse await sleep(100);\n\n\t\tif (generation !== this.generation || this.process?.exitCode !== null) {\n\t\t\tthrow rpcTransportError(`Agent process exited immediately. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Tell the engine child the host is quitting on purpose, and wait (bounded) for it to\n\t * record that. Call it before `stop()` for a quit the user asked for: stopping closes\n\t * stdin and sends SIGTERM, which is also how the child is stopped when the host itself\n\t * was signalled, so only this announcement lets the child tell the two apart.\n\t * Resolves true only when the child acknowledged the quit, and false without waiting when\n\t * there is no live engine child, or when the child exits or misses the deadline first.\n\t */\n\tasync announceExplicitQuit(timeoutMs = EXPLICIT_QUIT_ACK_TIMEOUT_MS): Promise<boolean> {\n\t\tconst writer = this.stdinWriter;\n\t\tif (!writer || !this.engineMonitor || this.generation <= this.lastEndedGeneration) return false;\n\t\tconst generation = this.generation;\n\t\tconst done = Promise.withResolvers<boolean>();\n\t\tthis.explicitQuitAck = { generation, acknowledge: () => done.resolve(true) };\n\t\tconst stopListening = this.onGenerationEnded((event) => {\n\t\t\tif (event.generation === generation) done.resolve(false);\n\t\t});\n\t\tconst timer = setTimeout(() => done.resolve(false), timeoutMs);\n\t\ttry {\n\t\t\tthis.bestEffort(\n\t\t\t\twriter.write(serializeInteractiveEngineFrame({ type: \"engine_explicit_quit\" })),\n\t\t\t\t\"explicit quit\",\n\t\t\t);\n\t\t\treturn await done.promise;\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tstopListening();\n\t\t\tif (this.explicitQuitAck?.generation === generation) this.explicitQuitAck = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Explicit stop. Voids any in-flight restart permit, so a replacement caught\n\t * between its own stop and start can never spawn after this returns.\n\t */\n\tstop(): Promise<void> {\n\t\tthis.restartRevision += 1;\n\t\tif (this.stopPromise) return this.stopPromise;\n\t\tif (!this.process) return Promise.resolve();\n\t\tconst stopPromise = this.stopCurrentGeneration().finally(() => {\n\t\t\tif (this.stopPromise === stopPromise) this.stopPromise = undefined;\n\t\t});\n\t\tthis.stopPromise = stopPromise;\n\t\treturn stopPromise;\n\t}\n\n\t/**\n\t * Tear down the current child without touching the restart permit. The reader\n\t * stays attached and the generation stays current until the dead child's\n\t * stdout settles, so an ownership frame it already sent still reaches its\n\t * request; only then is the generation retired (see RpcTerminalDrain).\n\t */\n\tprivate async stopCurrentGeneration(): Promise<void> {\n\t\tconst child = this.process;\n\t\tif (!child) return;\n\t\tconst endedGeneration = this.generation;\n\t\tconst stopError = rpcTransportError(\"Agent process stopped\");\n\t\tthis.invalidateEngineShortcuts();\n\t\tconst terminateTree = this.engineMonitor !== undefined;\n\t\tthis.engineMonitor?.stop();\n\t\tthis.stdinWriter?.close(stopError);\n\t\t// Unblock an in-flight start()/waitUntilBound() for the generation being\n\t\t// replaced. Readiness has no deadline by design, so without this an\n\t\t// explicit stop of a hung replacement child could never be observed.\n\t\tthis.engineMonitor?.fail(stopError);\n\t\tthis.engineMonitor = undefined;\n\t\tthis.stdinWriter = undefined;\n\t\tthis.process = null;\n\t\t// Publish before terminating so host controllers tear down this generation's\n\t\t// UI while the writer is detached: disposal cannot write into a replacement.\n\t\tthis.publishGenerationEnded(endedGeneration, stopError, \"explicit-stop\", true);\n\t\t// Claim before terminating so the exit this provokes does not relabel a\n\t\t// deliberate stop; an exit that already claimed keeps its own error.\n\t\tthis.terminalDrain.claim(endedGeneration, stopError);\n\t\tawait terminateRpcClientProcess(child, terminateTree);\n\t\tawait this.beginTerminalDrain(endedGeneration, stopError);\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.generation += 1;\n\t\tthis.pendingRequests.rejectAll(stopError);\n\t\tthis.eventBuffer?.dispose();\n\t\tthis.eventBuffer = undefined;\n\t\tthis.activeActivityIds.clear();\n\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t}\n\n\t/** Subscribe to agent events. */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\tonExtensionUIRequest(listener: (request: RpcExtensionUIRequest) => void): () => void {\n\t\tthis.extensionUIListeners.push(listener);\n\t\tfor (const request of this.pendingExtensionUIRequests.drain(this.generation)) listener(request);\n\t\treturn () => {\n\t\t\tconst index = this.extensionUIListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.extensionUIListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tasync respondExtensionUI(response: RpcExtensionUIResponse): Promise<void> {\n\t\tawait this.requireWriter().write(serializeJsonLine(response));\n\t}\n\n\tonInteractiveEngineMessage(listener: (message: InteractiveEngineMessage) => void): () => void {\n\t\tthis.engineMessageListeners.push(listener);\n\t\tfor (const message of this.pendingEngineMessages.drain(this.generation)) listener(message);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tonInteractiveEngineKeybindingState(listener: (state: EngineKeybindingState) => void): () => void {\n\t\tconst messageListener = (message: InteractiveEngineMessage): void => {\n\t\t\tif (message.type === \"engine_keybindings_reloaded\") listener(message.state);\n\t\t};\n\t\tthis.engineMessageListeners.push(messageListener);\n\t\tif (this.latestEngineKeybindingState) listener(this.latestEngineKeybindingState);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(messageListener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to the engine's workflow activity. The engine publishes its snapshot as soon as it binds,\n\t * so an observer that attaches later starts from the current snapshot instead of missing it.\n\t */\n\tonInteractiveEngineWorkflowActivity(listener: (frame: WorkflowActivityFrame) => void): () => void {\n\t\tconst messageListener = (message: InteractiveEngineMessage): void => {\n\t\t\tif (message.type === \"engine_workflow_activity\") listener(message.frame);\n\t\t};\n\t\tthis.engineMessageListeners.push(messageListener);\n\t\tconst current = this.workflowActivity.current();\n\t\tif (current) listener(current);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(messageListener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to host-local generation death. Fires at most once per\n\t * generation, synchronously, before any restart work. A death that has\n\t * already happened for the current generation replays immediately, so a\n\t * listener attached after an exit still sees it.\n\t */\n\tonGenerationEnded(listener: InteractiveEngineGenerationEndedListener): () => void {\n\t\tthis.generationEndedListeners.push(listener);\n\t\tconst retained = this.retainedGenerationEnd;\n\t\t// Only while it still describes the live generation: once stop()/start()\n\t\t// has moved on, that death belongs to a replaced child.\n\t\tif (retained && retained.generation === this.generation) listener(retained);\n\t\treturn () => {\n\t\t\tconst index = this.generationEndedListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.generationEndedListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tsendInteractiveEngineCommand(command: InteractiveEngineCommand): void {\n\t\tconst writer = this.stdinWriter;\n\t\tif (command.type === \"engine_project_trust_start\" || command.type === \"engine_project_trust_end\") {\n\t\t\tif (this.generation <= this.lastEndedGeneration) return;\n\t\t\t// The terminal can open and close /trust while the engine is still binding.\n\t\t\t// Retain both frames, without delaying the host-owned decision.\n\t\t\tif (this.engineMonitor && this.boundGeneration !== this.generation) {\n\t\t\t\tthis.pendingProjectTrustFrames.push(this.generation, serializeInteractiveEngineFrame(command));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (!writer) return;\n\t\tconst frame = serializeInteractiveEngineFrame(command);\n\t\tif (\n\t\t\tcommand.type === \"engine_custom_render\" ||\n\t\t\tcommand.type === \"engine_tool_render\" ||\n\t\t\tcommand.type === \"engine_message_render\"\n\t\t) {\n\t\t\twriter.offerLatest(`render:${command.componentId}`, frame);\n\t\t\treturn;\n\t\t}\n\t\tthis.bestEffort(writer.write(frame), `engine command ${command.type}`);\n\t}\n\twaitForInteractiveEngineBound(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilBound() ?? Promise.resolve();\n\t}\n\twaitForInteractiveEngineProjectTrust(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilProjectTrustSettled() ?? Promise.resolve();\n\t}\n\twaitForInteractiveEngineResources(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilResourcesReady() ?? Promise.resolve();\n\t}\n\tgetEnginePid(): number | undefined {\n\t\treturn this.enginePid;\n\t}\n\tgetGeneration(): number {\n\t\treturn this.generation;\n\t}\n\n\t/**\n\t * Replace the engine child, unless an explicit stop supersedes this attempt.\n\t * The permit is checked immediately before spawning, so a `stop()` in that\n\t * window is always observed; cancellation throws rather than returning\n\t * quietly, because callers go on to initialize against the new child.\n\t */\n\tasync restart(sessionId: string | undefined, options?: { sessionDirectory?: string; cwd?: string }): Promise<void> {\n\t\tconst permit = this.restartRevision;\n\t\tawait this.stopCurrentGeneration();\n\t\t// Join an in-flight stop before the permit check: waiting after it would\n\t\t// reopen the window this fence exists to close.\n\t\tif (this.stopPromise) await this.stopPromise;\n\t\tif (permit !== this.restartRevision) throw rpcTransportError(RESTART_CANCELLED_MESSAGE);\n\t\tthis.options = {\n\t\t\t...this.options,\n\t\t\tcwd: options?.cwd ?? this.options.cwd,\n\t\t\targs: restartCliArgs(this.options.args, sessionId, options?.sessionDirectory),\n\t\t};\n\t\tawait this.start();\n\t\tawait this.waitForInteractiveEngineBound();\n\t}\n\n\tasync requestInternal<T>(command: RpcCommandBody): Promise<T> {\n\t\treturn this.data<T>(await this.request(command));\n\t}\n\tuserBashWithUpdates(\n\t\tcommand: string,\n\t\tonUpdate: (delta: string, channel: BashOutputChannel) => void,\n\t\toptions?: { excludeFromContext?: boolean; onRequestId?: (id: string) => void },\n\t): Promise<BashResult> {\n\t\treturn runUserBashWithUpdates(this, command, onUpdate, options, (body, onId) => this.request(body, onId));\n\t}\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn waitForRpcIdle(this, timeout);\n\t}\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn collectRpcEvents(this, timeout);\n\t}\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tconst accepted = this.prompt(message, images);\n\t\t// A prompt has no request deadline, so `timeout` must also end the wait while\n\t\t// the prompt is still unacknowledged. Whichever settles first decides; both are\n\t\t// observed so the loser's later rejection is never an unhandled rejection.\n\t\teventsPromise.catch(() => {});\n\t\taccepted.catch(() => {});\n\t\tawait Promise.race([accepted, eventsPromise]);\n\t\treturn eventsPromise;\n\t}\n\tprivate handleLine(line: string, generation: number): void {\n\t\tif (this.terminalDrain.observe(generation, line, (id) => this.pendingRequests.markAccepted(id))) return;\n\t\tif (this.engineMonitor?.handleLine(line)) return;\n\t\ttry {\n\t\t\tconst data = JSON.parse(line) as { type?: string; id?: string };\n\t\t\tif (data.type === \"extension_ui_request\") {\n\t\t\t\tconst request = data as RpcExtensionUIRequest;\n\t\t\t\tif (this.extensionUIListeners.length === 0) this.pendingExtensionUIRequests.push(generation, request);\n\t\t\t\tfor (const listener of this.extensionUIListeners) listener(request);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.resolve(data.id, data as RpcResponse)) return;\n\t\t\tconst event = data as RpcEvent;\n\t\t\tif (this.eventBuffer) this.eventBuffer.enqueue(event);\n\t\t\telse this.emitEvent(event);\n\t\t} catch {\n\t\t\tif (this.engineMonitor) this.failTransport(rpcTransportError(\"Interactive engine emitted malformed JSONL\"));\n\t\t}\n\t}\n\tprivate emitEvent(event: RpcEvent): void {\n\t\t// Iterate a snapshot so listeners that unsubscribe during dispatch do not make later listeners miss this event.\n\t\tfor (const listener of [...this.eventListeners]) listener(event);\n\t}\n\tprivate emitInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\tif (\n\t\t\tthis.engineMessageListeners.length === 0 &&\n\t\t\t(message.type.startsWith(\"engine_custom_\") || message.type.startsWith(\"engine_resources_\"))\n\t\t) {\n\t\t\tthis.pendingEngineMessages.push(generation, message);\n\t\t}\n\t\tfor (const listener of this.engineMessageListeners) listener(message);\n\t}\n\tprivate createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {\n\t\treturn rpcTransportError(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);\n\t}\n\tprivate invalidateEngineShortcuts(): void {\n\t\tif (!this.latestEngineKeybindingState || this.latestEngineKeybindingState.shortcuts.length === 0) return;\n\t\tconst state: EngineKeybindingState = { ...this.latestEngineKeybindingState, shortcuts: [] };\n\t\tthis.latestEngineKeybindingState = state;\n\t\tthis.emitInteractiveEngineMessage({ type: \"engine_keybindings_reloaded\", state }, this.generation);\n\t}\n\tprivate observeInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\t// Ownership is the one thing a dead generation may still report: request\n\t\t// ids never repeat, and the alternative is classifying work it already\n\t\t// started as never sent. Nothing else from it may touch host state — a\n\t\t// stale frame would revive a PID, an activity, or a mount that is gone.\n\t\tif (message.type === \"engine_request_accepted\") {\n\t\t\tif (generation === this.generation) this.pendingRequests.markAccepted(message.requestId);\n\t\t\treturn;\n\t\t}\n\t\tif (message.type === \"engine_explicit_quit_ack\") {\n\t\t\tif (this.explicitQuitAck?.generation === generation) this.explicitQuitAck.acknowledge();\n\t\t\treturn;\n\t\t}\n\t\tif (generation !== this.generation || generation <= this.lastEndedGeneration) return;\n\t\tif (message.type === \"engine_heartbeat\") this.options.interactiveEngine?.onHeartbeat?.();\n\t\tif (message.type === \"engine_ready\") this.enginePid = message.pid;\n\t\tif (message.type === \"engine_bound\") {\n\t\t\tthis.boundGeneration = generation;\n\t\t\tfor (const frame of this.pendingProjectTrustFrames.drain(generation)) {\n\t\t\t\tif (this.stdinWriter) this.bestEffort(this.stdinWriter.write(frame), \"project trust notification\");\n\t\t\t}\n\t\t}\n\t\tif (message.type === \"engine_keybindings_reloaded\") this.latestEngineKeybindingState = message.state;\n\t\tif (message.type === \"engine_workflow_activity\") this.workflowActivity.apply(message.frame);\n\t\tif (message.type === \"engine_activity_started\") this.activeActivityIds.add(message.activity.id);\n\t\telse if (message.type === \"engine_activity_finished\") this.activeActivityIds.delete(message.activityId);\n\t\tthis.options.interactiveEngine?.onActivityChange?.(this.activeActivityIds.size > 0);\n\t\tthis.emitInteractiveEngineMessage(message, generation);\n\t}\n\t/**\n\t * Shared teardown for every unexpected end of `generation`. Death publishes\n\t * at once for the host UI; its requests wait for stdout (RpcTerminalDrain).\n\t */\n\tprivate failGeneration(rawError: Error, generation: number, kind: InteractiveEngineGenerationEndKind): void {\n\t\tif (generation !== this.generation) return;\n\t\tconst error = markRpcTransportFailure(rawError);\n\t\tthis.exitError = error;\n\t\tthis.stdinWriter?.close(error);\n\t\tthis.engineMonitor?.fail(error);\n\t\tif (kind === \"exit\") {\n\t\t\tthis.activeActivityIds.clear();\n\t\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t\t}\n\t\tthis.beginTerminalDrain(generation, error);\n\t\tthis.publishGenerationEnded(generation, error, kind, false);\n\t}\n\t/** Hold this generation's requests until its stdout drains (RpcTerminalDrain). */\n\tprivate beginTerminalDrain(generation: number, error: Error): Promise<void> {\n\t\treturn this.terminalDrain.begin(generation, this.stdoutDrained, error, (settled) => {\n\t\t\tif (generation === this.generation) this.pendingRequests.rejectAll(settled);\n\t\t});\n\t}\n\tprivate publishGenerationEnded(\n\t\tgeneration: number,\n\t\terror: Error,\n\t\tkind: InteractiveEngineGenerationEndKind,\n\t\texpected: boolean,\n\t): void {\n\t\tif (generation <= this.lastEndedGeneration) return;\n\t\tthis.lastEndedGeneration = generation;\n\t\tconst event: InteractiveEngineGenerationEnded = { generation, error, kind, expected };\n\t\tthis.retainedGenerationEnd = event;\n\t\t// Death is a strict boundary: drop this generation's buffered frames\n\t\t// BEFORE teardown runs, so no listener can drain a stale mount frame\n\t\t// while it is closing that very generation's components.\n\t\tthis.pendingEngineMessages.dropGeneration(generation);\n\t\tthis.workflowActivity.reset();\n\t\tthis.pendingExtensionUIRequests.dropGeneration(generation);\n\t\tthis.pendingProjectTrustFrames.dropGeneration(generation);\n\t\tfor (const listener of [...this.generationEndedListeners]) listener(event);\n\t}\n\tprivate failTransport(rawError: Error): void {\n\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\tactivity: undefined,\n\t\t\telapsedMs: 0,\n\t\t\tlevel: \"unresponsive\",\n\t\t\tmessage: rawError.message,\n\t\t});\n\t\tthis.failGeneration(rawError, this.generation, \"transport-error\");\n\t}\n\tprivate requireWriter(): QueuedWriter {\n\t\tif (!this.stdinWriter) throw rpcTransportError(\"Agent process stdin is not writable\");\n\t\treturn this.stdinWriter;\n\t}\n\tprivate bestEffort(operation: Promise<void>, label: string): void {\n\t\tvoid operation.catch((error: Error) => {\n\t\t\tif (!this.process || this.exitError) return;\n\t\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\t\tactivity: undefined,\n\t\t\t\telapsedMs: 0,\n\t\t\t\tlevel: \"unresponsive\",\n\t\t\t\tmessage: `Interactive engine ${label} failed: ${error.message}`,\n\t\t\t});\n\t\t});\n\t}\n\tprotected async request(command: RpcCommandBody, onRequestId?: (id: string) => void): Promise<RpcResponse> {\n\t\tconst childProcess = this.process;\n\t\tif (!childProcess) throw rpcTransportError(\"Client not started\");\n\t\tif (this.exitError) throw this.exitError;\n\t\tif (childProcess.exitCode !== null) {\n\t\t\tconst error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t\tconst id = `req_${++this.requestId}`;\n\t\tonRequestId?.(id);\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\tlet rejectResponse!: (error: Error) => void;\n\t\tconst response = new Promise<RpcResponse>((resolve, reject) => {\n\t\t\trejectResponse = reject;\n\t\t\tthis.pendingRequests.add(id, {\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\t\t});\n\t\ttry {\n\t\t\tawait this.requireWriter().write(serializeJsonLine(fullCommand));\n\t\t} catch (error) {\n\t\t\tthis.pendingRequests.delete(id);\n\t\t\t// Idempotent: the writer already classified this, but a caller-supplied\n\t\t\t// stream can reject with anything, and a send that never left the host\n\t\t\t// is a transport failure whatever it threw.\n\t\t\trejectResponse(markRpcTransportFailure(error));\n\t\t\treturn response;\n\t\t}\n\t\tif (this.pendingRequests.has(id) && !LONG_LIVED_COMMANDS.has(command.type)) {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\trejectResponse(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);\n\t\t}\n\t\treturn response;\n\t}\n\tprivate assertSuccess(response: RpcResponse): void {\n\t\tif (response.success) return;\n\t\tif (response.errorCode === \"credential_synchronization\" && response.errorDetails) {\n\t\t\tthrow new CredentialSynchronizationError(\n\t\t\t\tresponse.errorDetails.providerId,\n\t\t\t\tresponse.errorDetails.operation,\n\t\t\t\tundefined,\n\t\t\t\t{ cause: new Error(response.error) },\n\t\t\t);\n\t\t}\n\t\tthrow new Error(response.error);\n\t}\n\tprotected data<T>(response: RpcResponse): T {\n\t\tthis.assertSuccess(response);\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
@@ -7,4 +7,6 @@ export declare function splitIncompleteAnsiSuffix(value: string): {
7
7
  pending: string;
8
8
  };
9
9
  export declare function stripAnsi(value: string): string;
10
+ /** Replace each run of C0 and C1 control characters (ESC, BEL, newlines, ...) with one space. */
11
+ export declare function replaceControlCharacters(value: string): string;
10
12
  //# sourceMappingURL=ansi.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ansi.d.ts","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAkDA;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAW9F;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAc/C"}
1
+ {"version":3,"file":"ansi.d.ts","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAkDA;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAW9F;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAc/C;AAID,iGAAiG;AACjG,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE9D"}
@@ -68,4 +68,9 @@ export function stripAnsi(value) {
68
68
  // and doing it manually has a performance penalty.
69
69
  return value.replace(regex, "");
70
70
  }
71
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/g;
72
+ /** Replace each run of C0 and C1 control characters (ESC, BEL, newlines, ...) with one space. */
73
+ export function replaceControlCharacters(value) {
74
+ return value.replace(CONTROL_CHARACTERS, " ");
75
+ }
71
76
  //# sourceMappingURL=ansi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ansi.js","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,4DAA4D;AAC5D,MAAM,EAAE,GAAG,oCAAoC,CAAC;AA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,EAAE,CAAC;AAC7E,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,KAAa;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,SAAS,CAAC,gCAAgC,OAAO,KAAK,IAAI,CAAC,CAAC;IACvE,CAAC;IAED,sEAAsE;IACtE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAC;IACd,CAAC;IAED,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjC,CAAC","sourcesContent":["/*\n * Portions of this file are derived from:\n * - ansi-regex (https://github.com/chalk/ansi-regex)\n * - strip-ansi (https://github.com/chalk/strip-ansi)\n *\n * MIT License\n *\n * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// Valid string terminator sequences are BEL, ESC\\, and 0x9c\nconst ST = \"(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)\";\n\n// OSC sequences: ESC ] ... ST\nconst OSC_START = \"\\\\u001B\\\\]\";\n\n// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :), then final byte\nconst CSI_START = \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?\";\nconst CSI_FINAL = \"[\\\\dA-PR-TZcf-nq-uy=><~]\";\n\n// Complete sequences. OSC is non-greedy until the first ST.\nconst regex = new RegExp(`(?:${OSC_START}[\\\\s\\\\S]*?${ST})|${CSI_START}${CSI_FINAL}`, \"g\");\n\n// Unfinished sequence at the end of the text: OSC without its ST (a trailing ESC may start ESC\\),\n// or CSI without its final byte.\nconst unfinishedAnsiAtEndRegex = new RegExp(\n\t`(?:${OSC_START}(?:[^\\\\u0007\\\\u009C\\\\u001B]|\\\\u001B(?!\\\\\\\\))*|${CSI_START})$`,\n);\n\n// Longest unfinished sequence held back while streaming. Longer ones are processed as-is.\nconst MAX_PENDING_ANSI_LENGTH = 256;\n\n/**\n * Split streamed text into a part that is safe to pass to stripAnsi now and a trailing\n * unfinished escape sequence that should be prepended to the next chunk.\n */\nexport function splitIncompleteAnsiSuffix(value: string): { complete: string; pending: string } {\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn { complete: value, pending: \"\" };\n\t}\n\tconst windowStart = Math.max(0, value.length - MAX_PENDING_ANSI_LENGTH);\n\tconst match = unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));\n\tif (!match) {\n\t\treturn { complete: value, pending: \"\" };\n\t}\n\tconst splitAt = windowStart + match.index;\n\treturn { complete: value.slice(0, splitAt), pending: value.slice(splitAt) };\n}\n\nexport function stripAnsi(value: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof value}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn value;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn value.replace(regex, \"\");\n}\n"]}
1
+ {"version":3,"file":"ansi.js","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,4DAA4D;AAC5D,MAAM,EAAE,GAAG,oCAAoC,CAAC;AAEhD,8BAA8B;AAC9B,MAAM,SAAS,GAAG,YAAY,CAAC;AAE/B,uGAAuG;AACvG,MAAM,SAAS,GAAG,4DAA4D,CAAC;AAC/E,MAAM,SAAS,GAAG,0BAA0B,CAAC;AAE7C,4DAA4D;AAC5D,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,KAAK,SAAS,GAAG,SAAS,EAAE,EAAE,GAAG,CAAC,CAAC;AAE1F,kGAAkG;AAClG,iCAAiC;AACjC,MAAM,wBAAwB,GAAG,IAAI,MAAM,CAC1C,MAAM,SAAS,iDAAiD,SAAS,IAAI,CAC7E,CAAC;AAEF,0FAA0F;AAC1F,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAAa;IACtD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IACzC,CAAC;IACD,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,uBAAuB,CAAC,CAAC;IACxE,MAAM,KAAK,GAAG,wBAAwB,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;IACtE,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IACzC,CAAC;IACD,MAAM,OAAO,GAAG,WAAW,GAAG,KAAK,CAAC,KAAK,CAAC;IAC1C,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;AAC7E,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,KAAa;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,SAAS,CAAC,gCAAgC,OAAO,KAAK,IAAI,CAAC,CAAC;IACvE,CAAC;IAED,sEAAsE;IACtE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAC;IACd,CAAC;IAED,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,kBAAkB,GAAG,gCAAgC,CAAC;AAE5D,iGAAiG;AACjG,MAAM,UAAU,wBAAwB,CAAC,KAAa;IACrD,OAAO,KAAK,CAAC,OAAO,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["/*\n * Portions of this file are derived from:\n * - ansi-regex (https://github.com/chalk/ansi-regex)\n * - strip-ansi (https://github.com/chalk/strip-ansi)\n *\n * MIT License\n *\n * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// Valid string terminator sequences are BEL, ESC\\, and 0x9c\nconst ST = \"(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)\";\n\n// OSC sequences: ESC ] ... ST\nconst OSC_START = \"\\\\u001B\\\\]\";\n\n// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :), then final byte\nconst CSI_START = \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?\";\nconst CSI_FINAL = \"[\\\\dA-PR-TZcf-nq-uy=><~]\";\n\n// Complete sequences. OSC is non-greedy until the first ST.\nconst regex = new RegExp(`(?:${OSC_START}[\\\\s\\\\S]*?${ST})|${CSI_START}${CSI_FINAL}`, \"g\");\n\n// Unfinished sequence at the end of the text: OSC without its ST (a trailing ESC may start ESC\\),\n// or CSI without its final byte.\nconst unfinishedAnsiAtEndRegex = new RegExp(\n\t`(?:${OSC_START}(?:[^\\\\u0007\\\\u009C\\\\u001B]|\\\\u001B(?!\\\\\\\\))*|${CSI_START})$`,\n);\n\n// Longest unfinished sequence held back while streaming. Longer ones are processed as-is.\nconst MAX_PENDING_ANSI_LENGTH = 256;\n\n/**\n * Split streamed text into a part that is safe to pass to stripAnsi now and a trailing\n * unfinished escape sequence that should be prepended to the next chunk.\n */\nexport function splitIncompleteAnsiSuffix(value: string): { complete: string; pending: string } {\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn { complete: value, pending: \"\" };\n\t}\n\tconst windowStart = Math.max(0, value.length - MAX_PENDING_ANSI_LENGTH);\n\tconst match = unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));\n\tif (!match) {\n\t\treturn { complete: value, pending: \"\" };\n\t}\n\tconst splitAt = windowStart + match.index;\n\treturn { complete: value.slice(0, splitAt), pending: value.slice(splitAt) };\n}\n\nexport function stripAnsi(value: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof value}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn value;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn value.replace(regex, \"\");\n}\n\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f-\\u009f]+/g;\n\n/** Replace each run of C0 and C1 control characters (ESC, BEL, newlines, ...) with one space. */\nexport function replaceControlCharacters(value: string): string {\n\treturn value.replace(CONTROL_CHARACTERS, \" \");\n}\n"]}
package/docs/codemode.md CHANGED
@@ -34,7 +34,7 @@ The result starts with `Script completed` or `Script failed`, the wall time, and
34
34
  | `exit()` | End the script successfully. |
35
35
  | `store(key, value)` / `load(key)` | Keep small JSON values across `codemode` calls. See [Store values](#store-values). |
36
36
  | `ALL_TOOLS` | Every script-callable tool as `{ name, description }`, including tools the description does not list. [Model-only tools](#model-only-tools) are excluded. |
37
- | `searchTools(query, { limit?, namespace? })` | Rank script-callable tools by relevance (BM25, default limit 8). Resolves to `{ name, description }[]`. A query that names an active model-only tool exactly returns it first with a hint to call it directly. |
37
+ | `searchTools(query, { limit?, namespace? })` | Rank script-callable tools by relevance (BM25, default limit 8). Resolves to `{ name, description }[]`. A query that is a tool's name, or the part after a `__` separator such as `thread_read` for `mcp__app__thread_read`, ranks that tool first. A query that names an active model-only tool exactly returns it first with a hint to call it directly. |
38
38
  | `describeTool(name)` | Resolves to a script-callable tool's description and TypeScript declaration, a hint for an active model-only tool, or `undefined`. |
39
39
  | `describeNamespace(name)` | Resolves to `{ name, description?, instructions?, tools }` for a namespace such as an MCP server, or `undefined`. |
40
40
  | `models` | List and run non-LLM models. See [Models](#models). |
@@ -76,7 +76,7 @@ A genuine agent's registered aliases remain valid when its pending-delivery capa
76
76
 
77
77
  If several live agent stages share a workflow-stage name, `ask` remains ambiguous: use an exact stage-ID path from `intercom list`. Name-based `send` retains sticky delivery to matching agents. A prompt or tool with that same name does not turn genuine-agent matches into non-agent refusals.
78
78
 
79
- Before steering a stage from the main chat, enter the workflow invocation context by joining `workflow:<rootRunId>` with `intercom({ action: "join", group: "workflow:<rootRunId>" })`; workflow-owned invocation sessions already start there. A member of that invocation group can list, `send` to, and live-`ask` exact stages in any invocation-owned subgroup (`workflow:<rootRunId>/<name>`), including intentionally isolated reviewer batches. This control is directional: a session registered as a subgroup stage cannot gain parent control by joining the invocation group, subgroup members cannot discover or reach sibling subgroups, and another workflow invocation remains refused. `PENDING` accepts queued `send` only; `RUNNING` accepts immediate `send` and correlated `ask`/`reply`.
79
+ The session that launched a run can list and `send` to its stages without joining. Its own group memberships stay unchanged, so the run's stages gain no route back to it. Any other session steering a stage from the main chat first enters the workflow invocation context by joining `workflow:<rootRunId>` with `intercom({ action: "join", group: "workflow:<rootRunId>" })`; workflow-owned invocation sessions already start there. A send from outside both is refused with an error that names the group to join. A member of that invocation group (or the launching session) can list, `send` to, and live-`ask` exact stages in any invocation-owned subgroup (`workflow:<rootRunId>/<name>`), including intentionally isolated reviewer batches. This control is directional: a session registered as a subgroup stage cannot gain parent control by joining the invocation group, subgroup members cannot discover or reach sibling subgroups, and another workflow invocation remains refused. `PENDING` accepts queued `send` only; `RUNNING` accepts immediate `send` and correlated `ask`/`reply`.
80
80
 
81
81
  ### Deferred delivery to pending stages
82
82
 
@@ -100,9 +100,9 @@ Each row in `intercom list`, and each run in `workflow` status, lists at most 5
100
100
 
101
101
  The workflows extension persists up to **50 queued messages per target** with workflow state. Messages survive resume/replay and broker restart. Reusing a stage's existing session transcript does not duplicate acknowledged messages; a replacement session with a new transcript receives the retained sticky context again. When a matching stage session initializes, it receives the FIFO entries through the ordinary Intercom inbound path before its first model turn, under the heading **Messages received before you started**, with sender identity and `Sent:` timestamps visible separately from the task prompt.
102
102
 
103
- Only a workflow invocation member with eligible invocation-control authority can queue to its invocation-owned stages; this includes a main-chat session that explicitly joined `workflow:<rootRunId>`. Subgroup peers and another root run remain refused even if they add that membership. An explicit stage `group: "default"` is a shared-group escape, is not workflow-owned, and does not receive pending invocation delivery. An ineligible attempt is refused with `Target workflow run is in a different intercom group`. The 51st queued message is refused with `Pending stage message queue is full (limit 50)` rather than evicting an earlier entry.
103
+ Only a workflow invocation member with eligible invocation-control authority can queue to its invocation-owned stages; this includes a main-chat session that explicitly joined `workflow:<rootRunId>`. Subgroup peers and another root run remain refused even if they add that membership. An explicit stage `group: "default"` is a shared-group escape, is not workflow-owned, and does not receive pending invocation delivery. An ineligible session is refused with `Target workflow run is in a different intercom group; join workflow:<rootRunId> to send to its stages`. A workflow stage registered outside the invocation (a subgroup peer or another run's stage) is refused with `A workflow stage in <its group> cannot send to stages of workflow:<rootRunId>; joining that group does not grant it control`, because joining never authorizes it. The 51st queued message is refused with `Pending stage message queue is full (limit 50)` rather than evicting an earlier entry.
104
104
 
105
- If the destination stage is skipped, the run terminates, or the stage becomes terminal before its session initializes, Atomic marks the queued message undeliverable and sends the correlated failure notification when acknowledgment was requested. Use `ask` only on a live, reply-capable exact target. Pending, future, and pattern asks return `pending_stage_ask_unsupported`; use ordinary `send`, because a stage may start much later or never start.
105
+ If the destination stage is skipped, the run terminates, or the stage becomes terminal before its session initializes, Atomic marks the queued message undeliverable and sends the correlated failure notification when acknowledgment was requested. The notification goes back to the session that sent the message, including the launching session and a session that joined `workflow:<rootRunId>` from another group, and to no one else. Use `ask` only on a live, reply-capable exact target. Pending, future, and pattern asks return `pending_stage_ask_unsupported`; use ordinary `send`, because a stage may start much later or never start.
106
106
 
107
107
  A workflow run that was interrupted and can continue with `/workflow resume` stays addressable after the Atomic session that launched it restarts. Once the crashed session's lease expires (about 120 seconds), its stages show as pending in `intercom list`, and sends to `workflow:<rootRunId>/<stage>` or `workflow:<rootRunId>/**` are queued and delivered once after `/workflow resume`. Asks are refused while the run is dormant, and only the launching session answers for it.
108
108