@bastani/atomic 0.9.19-alpha.4 → 0.9.19-alpha.6

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 (119) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/broker/client.ts +19 -1
  4. package/dist/builtin/intercom/index.bundle.mjs +8 -1
  5. package/dist/builtin/intercom/package.json +1 -1
  6. package/dist/builtin/mcp/package.json +1 -1
  7. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  8. package/dist/builtin/subagents/README.md +6 -4
  9. package/dist/builtin/subagents/agents/codebase-online-researcher.md +7 -7
  10. package/dist/builtin/subagents/agents/debugger.md +2 -2
  11. package/dist/builtin/subagents/package.json +1 -1
  12. package/dist/builtin/subagents/skills/subagent/SKILL.md +16 -14
  13. package/dist/builtin/subagents/src/extension/index.bundle.mjs +2 -1
  14. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  15. package/dist/builtin/web-access/README.md +31 -24
  16. package/dist/builtin/web-access/index.bundle.mjs +16099 -77
  17. package/dist/builtin/web-access/package.json +2 -1
  18. package/dist/builtin/workflows/CHANGELOG.md +13 -0
  19. package/dist/builtin/workflows/builtin/{chunk-9k3ywfgd.js → chunk-1nbq96fh.js} +18 -18
  20. package/dist/builtin/workflows/builtin/{chunk-ahbntmx2.js → chunk-vhmnzdj9.js} +36 -36
  21. package/dist/builtin/workflows/builtin/{chunk-62v3gg9f.js → chunk-yeee2jrc.js} +11 -11
  22. package/dist/builtin/workflows/builtin/goal.js +1 -1
  23. package/dist/builtin/workflows/builtin/index.js +3 -3
  24. package/dist/builtin/workflows/builtin/open-claude-design.js +1 -1
  25. package/dist/builtin/workflows/builtin/ralph.js +1 -1
  26. package/dist/builtin/workflows/package.json +1 -1
  27. package/dist/builtin/workflows/src/extension/index.bundle.mjs +96 -67
  28. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  29. package/dist/core/agent-session-tool-registry.js +10 -0
  30. package/dist/core/agent-session-tool-registry.js.map +1 -1
  31. package/dist/core/bash-executor.js.map +1 -1
  32. package/dist/core/tools/bash.d.ts +1 -1
  33. package/dist/core/tools/bash.d.ts.map +1 -1
  34. package/dist/core/tools/bash.js +3 -2
  35. package/dist/core/tools/bash.js.map +1 -1
  36. package/dist/core/tools/edit.d.ts +3 -0
  37. package/dist/core/tools/edit.d.ts.map +1 -1
  38. package/dist/core/tools/edit.js +91 -12
  39. package/dist/core/tools/edit.js.map +1 -1
  40. package/dist/core/tools/file-mutation-coordinator.d.ts +255 -0
  41. package/dist/core/tools/file-mutation-coordinator.d.ts.map +1 -0
  42. package/dist/core/tools/file-mutation-coordinator.js +300 -0
  43. package/dist/core/tools/file-mutation-coordinator.js.map +1 -0
  44. package/dist/core/tools/file-mutation-queue.d.ts +14 -1
  45. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  46. package/dist/core/tools/file-mutation-queue.js +15 -3
  47. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  48. package/dist/core/tools/hashline.d.ts +9 -0
  49. package/dist/core/tools/hashline.d.ts.map +1 -1
  50. package/dist/core/tools/hashline.js +12 -1
  51. package/dist/core/tools/hashline.js.map +1 -1
  52. package/dist/core/tools/index.d.ts +9 -1
  53. package/dist/core/tools/index.d.ts.map +1 -1
  54. package/dist/core/tools/index.js +67 -12
  55. package/dist/core/tools/index.js.map +1 -1
  56. package/dist/core/tools/non-minting-snapshot-store.d.ts +49 -0
  57. package/dist/core/tools/non-minting-snapshot-store.d.ts.map +1 -0
  58. package/dist/core/tools/non-minting-snapshot-store.js +64 -0
  59. package/dist/core/tools/non-minting-snapshot-store.js.map +1 -0
  60. package/dist/core/tools/powershell.d.ts +2 -2
  61. package/dist/core/tools/powershell.d.ts.map +1 -1
  62. package/dist/core/tools/powershell.js +2 -5
  63. package/dist/core/tools/powershell.js.map +1 -1
  64. package/dist/core/tools/read-document-extract.js.map +1 -1
  65. package/dist/core/tools/render-utils.js.map +1 -1
  66. package/dist/core/tools/write.d.ts +30 -1
  67. package/dist/core/tools/write.d.ts.map +1 -1
  68. package/dist/core/tools/write.js +97 -8
  69. package/dist/core/tools/write.js.map +1 -1
  70. package/dist/index.d.ts +1 -1
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js.map +1 -1
  73. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  74. package/dist/modes/interactive/interactive-mode-base.d.ts +1 -0
  75. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  76. package/dist/modes/interactive/interactive-mode-base.js +3 -1
  77. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  78. package/dist/modes/interactive/interactive-mode-surface.d.ts +1 -1
  79. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  80. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  81. package/dist/modes/interactive/interactive-render-chat.js +28 -4
  82. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  83. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  84. package/dist/modes/interactive/interactive-startup.js +3 -0
  85. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  86. package/dist/modes/interactive-engine/activity-watchdog.d.ts +2 -2
  87. package/dist/modes/interactive-engine/activity-watchdog.d.ts.map +1 -1
  88. package/dist/modes/interactive-engine/activity-watchdog.js.map +1 -1
  89. package/dist/modes/interactive-engine/engine-diagnostic-view.d.ts +3 -1
  90. package/dist/modes/interactive-engine/engine-diagnostic-view.d.ts.map +1 -1
  91. package/dist/modes/interactive-engine/engine-diagnostic-view.js +11 -0
  92. package/dist/modes/interactive-engine/engine-diagnostic-view.js.map +1 -1
  93. package/dist/modes/interactive-engine/isolated-runtime.js +2 -1
  94. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  95. package/dist/modes/rpc/rpc-client-process.d.ts +2 -0
  96. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  97. package/dist/modes/rpc/rpc-client-process.js +23 -1
  98. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  99. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  100. package/dist/modes/rpc/rpc-client.js +20 -3
  101. package/dist/modes/rpc/rpc-client.js.map +1 -1
  102. package/dist/utils/markit.d.ts +2 -0
  103. package/dist/utils/markit.d.ts.map +1 -1
  104. package/dist/utils/markit.js +65 -5
  105. package/dist/utils/markit.js.map +1 -1
  106. package/docs/background-tasks.md +14 -10
  107. package/docs/containerization.md +7 -5
  108. package/docs/development.md +11 -0
  109. package/docs/docs.json +1 -0
  110. package/docs/providers.md +1 -1
  111. package/docs/subagents.md +4 -2
  112. package/docs/tools.md +26 -0
  113. package/docs/web-access.md +38 -0
  114. package/docs/workflows/builtins.md +9 -6
  115. package/examples/extensions/gondolin/index.ts +116 -148
  116. package/examples/extensions/gondolin/package.json +1 -1
  117. package/examples/extensions/ssh.ts +56 -34
  118. package/npm-shrinkwrap.json +33 -33
  119. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAGA,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,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,cAAc,EACd,qBAAqB,EACrB,yBAAyB,GACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,g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,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 { 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 {\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\trestartCliArgs,\n\tspawnRpcClientProcess,\n\tterminateRpcClientProcess,\n} from \"./rpc-client-process.ts\";\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\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 pendingEngineMessages = new GenerationBuffer<InteractiveEngineMessage>();\n\tprivate readonly pendingProjectTrustFrames = new GenerationBuffer<string>();\n\tprivate boundGeneration = 0;\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\tchildProcess.stderr?.on(\"data\", (data) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tthis.stderr = appendBoundedStderr(this.stderr, data.toString());\n\t\t\tprocess.stderr.write(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 * 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 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\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(sessionFile: string | undefined): 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 = { ...this.options, args: restartCliArgs(this.options.args, sessionFile) };\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\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 (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_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.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":"AAGA,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,EAIN,+BAA+B,GAC/B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAA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C,eAAe,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5E,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE;gBACzB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAChC,cAAc,CAAC,IAAI,KAAK,CAAC,mCAAmC,OAAO,CAAC,IAAI,aAAa,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YACtG,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,0BAA0B,CAAC,CAAC;QACjE,CAAC;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 { 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 {\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\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 pendingEngineMessages = new GenerationBuffer<InteractiveEngineMessage>();\n\tprivate readonly pendingProjectTrustFrames = new GenerationBuffer<string>();\n\tprivate boundGeneration = 0;\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 * 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 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\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(sessionFile: string | undefined): 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 = { ...this.options, args: restartCliArgs(this.options.args, sessionFile) };\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\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 (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_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.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"]}
@@ -3,6 +3,8 @@ export interface MarkitConversionResult {
3
3
  ok: boolean;
4
4
  error?: string;
5
5
  }
6
+ /** Bind the in-process interactive renderer for its lifetime. */
7
+ export declare function setMarkitDiagnosticSink(sink: (message: string) => void): () => void;
6
8
  export declare function convertFileWithMarkit(filePath: string, signal?: AbortSignal): Promise<MarkitConversionResult>;
7
9
  export declare function convertBufferWithMarkit(buffer: Uint8Array, extension: string, signal?: AbortSignal): Promise<MarkitConversionResult>;
8
10
  //# sourceMappingURL=markit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"markit.d.ts","sourceRoot":"","sources":["../../src/utils/markit.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,sBAAsB;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AA8CD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,sBAAsB,CAAC,CASnH;AAED,wBAAsB,uBAAuB,CAC5C,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,sBAAsB,CAAC,CAWjC"}
1
+ {"version":3,"file":"markit.d.ts","sourceRoot":"","sources":["../../src/utils/markit.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,sBAAsB;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAiBD,iEAAiE;AACjE,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,CAMnF;AAmFD,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,sBAAsB,CAAC,CASnH;AAED,wBAAsB,uBAAuB,CAC5C,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,sBAAsB,CAAC,CAWjC"}
@@ -1,4 +1,60 @@
1
+ /**
2
+ * MuPDF ships as an Emscripten module whose fd 1 and fd 2 sinks default to
3
+ * `console.log` / `console.error` (`mupdf/dist/mupdf-wasm.js`:
4
+ * `t.print&&(T=t.print),t.printErr&&(j=t.printErr)`), and
5
+ * `mupdf/dist/mupdf.js` builds that module at import time from
6
+ * `globalThis["$libmupdf_wasm_Module"]`. A PDF with a damaged `/FlateDecode`
7
+ * stream therefore writes diagnostics straight to the terminal. Capture a
8
+ * bounded batch and deliver it through the active TUI sink or console.log.
9
+ * RPC mode's stdout guard forwards console.log to the host through stderr.
10
+ */
11
+ const MUPDF_MODULE_GLOBAL = "$libmupdf_wasm_Module";
12
+ const MAX_MUPDF_DIAGNOSTIC_LINES = 32;
13
+ const MAX_MUPDF_DIAGNOSTIC_LENGTH = 4096;
14
+ let diagnosticSink;
15
+ /** Bind the in-process interactive renderer for its lifetime. */
16
+ export function setMarkitDiagnosticSink(sink) {
17
+ const previous = diagnosticSink;
18
+ diagnosticSink = sink;
19
+ return () => {
20
+ if (diagnosticSink === sink)
21
+ diagnosticSink = previous;
22
+ };
23
+ }
24
+ function logMupdfDiagnostics() {
25
+ if (mupdfDiagnostics.length === 0)
26
+ return;
27
+ const message = mupdfDiagnostics.join("\n");
28
+ if (diagnosticSink)
29
+ diagnosticSink(message);
30
+ else
31
+ console.log(message);
32
+ }
33
+ // Process-global because the MuPDF module is: concurrent conversions may
34
+ // cross-attribute a line. The text is advisory suffix on an error message,
35
+ // never a decision input, so that imprecision is acceptable.
36
+ let mupdfDiagnostics = [];
37
+ function recordMupdfDiagnostic(line) {
38
+ if (mupdfDiagnostics.length >= MAX_MUPDF_DIAGNOSTIC_LINES)
39
+ mupdfDiagnostics.shift();
40
+ mupdfDiagnostics.push(line.slice(0, MAX_MUPDF_DIAGNOSTIC_LENGTH));
41
+ }
42
+ /** Must run before the first `import("markit-ai")`; mupdf reads the global at module evaluation. */
43
+ function captureMupdfDiagnostics() {
44
+ const globals = globalThis;
45
+ const existing = (globals[MUPDF_MODULE_GLOBAL] ?? {});
46
+ globals[MUPDF_MODULE_GLOBAL] = { ...existing, print: recordMupdfDiagnostic, printErr: recordMupdfDiagnostic };
47
+ }
48
+ function withMupdfDiagnostics(message) {
49
+ if (mupdfDiagnostics.length === 0)
50
+ return message;
51
+ logMupdfDiagnostics();
52
+ const detail = mupdfDiagnostics.join("; ");
53
+ mupdfDiagnostics = [];
54
+ return `${message} (mupdf: ${detail})`;
55
+ }
1
56
  let markit = async () => {
57
+ captureMupdfDiagnostics();
2
58
  const promise = import("markit-ai").then(({ Markit }) => {
3
59
  const instance = new Markit();
4
60
  markit = () => instance;
@@ -23,6 +79,7 @@ async function runMarkitConversion(task, signal) {
23
79
  if (signal?.aborted)
24
80
  throw abortError();
25
81
  const instance = await markit();
82
+ mupdfDiagnostics = [];
26
83
  if (!signal)
27
84
  return task(instance);
28
85
  return await new Promise((resolve, reject) => {
@@ -34,9 +91,12 @@ async function runMarkitConversion(task, signal) {
34
91
  });
35
92
  }
36
93
  function finalizeConversion(markdown) {
37
- return typeof markdown === "string" && markdown.length > 0
38
- ? { content: markdown, ok: true }
39
- : { content: "", ok: false, error: "Conversion produced no output" };
94
+ if (typeof markdown === "string" && markdown.length > 0) {
95
+ logMupdfDiagnostics();
96
+ mupdfDiagnostics = [];
97
+ return { content: markdown, ok: true };
98
+ }
99
+ return { content: "", ok: false, error: withMupdfDiagnostics("Conversion produced no output") };
40
100
  }
41
101
  export async function convertFileWithMarkit(filePath, signal) {
42
102
  try {
@@ -45,7 +105,7 @@ export async function convertFileWithMarkit(filePath, signal) {
45
105
  catch (error) {
46
106
  if (error instanceof Error && error.name === "AbortError")
47
107
  throw error;
48
- return { content: "", ok: false, error: normalizeError(error) };
108
+ return { content: "", ok: false, error: withMupdfDiagnostics(normalizeError(error)) };
49
109
  }
50
110
  }
51
111
  export async function convertBufferWithMarkit(buffer, extension, signal) {
@@ -57,7 +117,7 @@ export async function convertBufferWithMarkit(buffer, extension, signal) {
57
117
  catch (error) {
58
118
  if (error instanceof Error && error.name === "AbortError")
59
119
  throw error;
60
- return { content: "", ok: false, error: normalizeError(error) };
120
+ return { content: "", ok: false, error: withMupdfDiagnostics(normalizeError(error)) };
61
121
  }
62
122
  }
63
123
  //# sourceMappingURL=markit.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"markit.js","sourceRoot":"","sources":["../../src/utils/markit.ts"],"names":[],"mappings":"AAQA,IAAI,MAAM,GAAmC,KAAK,IAAI,EAAE;IACvD,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE;QAC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uB,CAC5C,MAAkB,EAClB,SAAiB,EACjB,MAAoB;IAEpB,MAAM,mBAAmB,GAAG,kBAAkB,CAAC,SAAS,CAAC,CAAC;IAC1D,MAAM,UAAU,GAAe,EAAE,SAAS,EAAE,mBAAmB,EAAE,QAAQ,EAAE,QAAQ,mBAAmB,EAAE,EAAE,CAAC;IAC3G,IAAI,CAAC;QACJ,OAAO,kBAAkB,CACxB,CAAC,MAAM,mBAAmB,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,QAAQ,CAC7G,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY;YAAE,MAAM,KAAK,CAAC;QACvE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;IACjE,CAAC;AACF,CAAC","sourcesContent":["import type { Markit, StreamInfo } from \"markit-ai\";\n\nexport interface MarkitConversionResult {\n\tcontent: string;\n\tok: boolean;\n\terror?: string;\n}\n\nlet markit: () => Markit | Promise<Markit> = async () => {\n\tconst promise = import(\"markit-ai\").then(({ Markit }) => {\n\t\tconst instance = new Markit();\n\t\tmarkit = () => instance;\n\t\treturn instance;\n\t});\n\tmarkit = () => promise;\n\treturn promise;\n};\n\nfunction normalizeExtension(extension: string): string {\n\tconst trimmed = extension.trim().toLowerCase();\n\treturn trimmed ? (trimmed.startsWith(\".\") ? trimmed : `.${trimmed}`) : \".bin\";\n}\n\nfunction normalizeError(error: unknown): string {\n\treturn error instanceof Error && error.message.trim().length > 0 ? error.message.trim() : \"Conversion failed\";\n}\n\nfunction abortError(): Error {\n\tconst error = new Error(\"Aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n\nasync function runMarkitConversion<T>(task: (markit: Markit) => Promise<T>, signal?: AbortSignal): Promise<T> {\n\tif (signal?.aborted) throw abortError();\n\tconst instance = await markit();\n\tif (!signal) return task(instance);\n\treturn await new Promise<T>((resolve, reject) => {\n\t\tconst abort = () => reject(abortError());\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tvoid task(instance)\n\t\t\t.then(resolve, reject)\n\t\t\t.finally(() => signal.removeEventListener(\"abort\", abort));\n\t});\n}\n\nfunction finalizeConversion(markdown?: string): MarkitConversionResult {\n\treturn typeof markdown === \"string\" && markdown.length > 0\n\t\t? { content: markdown, ok: true }\n\t\t: { content: \"\", ok: false, error: \"Conversion produced no output\" };\n}\n\nexport async function convertFileWithMarkit(filePath: string, signal?: AbortSignal): Promise<MarkitConversionResult> {\n\ttry {\n\t\treturn finalizeConversion(\n\t\t\t(await runMarkitConversion((instance) => instance.convertFile(filePath), signal)).markdown,\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.name === \"AbortError\") throw error;\n\t\treturn { content: \"\", ok: false, error: normalizeError(error) };\n\t}\n}\n\nexport async function convertBufferWithMarkit(\n\tbuffer: Uint8Array,\n\textension: string,\n\tsignal?: AbortSignal,\n): Promise<MarkitConversionResult> {\n\tconst normalizedExtension = normalizeExtension(extension);\n\tconst streamInfo: StreamInfo = { extension: normalizedExtension, filename: `input${normalizedExtension}` };\n\ttry {\n\t\treturn finalizeConversion(\n\t\t\t(await runMarkitConversion((instance) => instance.convert(Buffer.from(buffer), streamInfo), signal)).markdown,\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.name === \"AbortError\") throw error;\n\t\treturn { content: \"\", ok: false, error: normalizeError(error) };\n\t}\n}\n"]}
1
+ {"version":3,"file":"markit.js","sourceRoot":"","sources":["../../src/utils/markit.ts"],"names":[],"mappings":"AAQA;;;;;;;;;GASG;AACH,MAAM,mBAAmB,GAAG,uBAAuB,CAAC;AACpD,MAAM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AoB,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;IACvF,CAAC;AACF,CAAC","sourcesContent":["import type { Markit, StreamInfo } from \"markit-ai\";\n\nexport interface MarkitConversionResult {\n\tcontent: string;\n\tok: boolean;\n\terror?: string;\n}\n\n/**\n * MuPDF ships as an Emscripten module whose fd 1 and fd 2 sinks default to\n * `console.log` / `console.error` (`mupdf/dist/mupdf-wasm.js`:\n * `t.print&&(T=t.print),t.printErr&&(j=t.printErr)`), and\n * `mupdf/dist/mupdf.js` builds that module at import time from\n * `globalThis[\"$libmupdf_wasm_Module\"]`. A PDF with a damaged `/FlateDecode`\n * stream therefore writes diagnostics straight to the terminal. Capture a\n * bounded batch and deliver it through the active TUI sink or console.log.\n * RPC mode's stdout guard forwards console.log to the host through stderr.\n */\nconst MUPDF_MODULE_GLOBAL = \"$libmupdf_wasm_Module\";\nconst MAX_MUPDF_DIAGNOSTIC_LINES = 32;\nconst MAX_MUPDF_DIAGNOSTIC_LENGTH = 4096;\nlet diagnosticSink: ((message: string) => void) | undefined;\n\n/** Bind the in-process interactive renderer for its lifetime. */\nexport function setMarkitDiagnosticSink(sink: (message: string) => void): () => void {\n\tconst previous = diagnosticSink;\n\tdiagnosticSink = sink;\n\treturn () => {\n\t\tif (diagnosticSink === sink) diagnosticSink = previous;\n\t};\n}\n\nfunction logMupdfDiagnostics(): void {\n\tif (mupdfDiagnostics.length === 0) return;\n\tconst message = mupdfDiagnostics.join(\"\\n\");\n\tif (diagnosticSink) diagnosticSink(message);\n\telse console.log(message);\n}\n\n// Process-global because the MuPDF module is: concurrent conversions may\n// cross-attribute a line. The text is advisory suffix on an error message,\n// never a decision input, so that imprecision is acceptable.\nlet mupdfDiagnostics: string[] = [];\n\nfunction recordMupdfDiagnostic(line: string): void {\n\tif (mupdfDiagnostics.length >= MAX_MUPDF_DIAGNOSTIC_LINES) mupdfDiagnostics.shift();\n\tmupdfDiagnostics.push(line.slice(0, MAX_MUPDF_DIAGNOSTIC_LENGTH));\n}\n\n/** Must run before the first `import(\"markit-ai\")`; mupdf reads the global at module evaluation. */\nfunction captureMupdfDiagnostics(): void {\n\tconst globals = globalThis as Record<string, unknown>;\n\tconst existing = (globals[MUPDF_MODULE_GLOBAL] ?? {}) as Record<string, unknown>;\n\tglobals[MUPDF_MODULE_GLOBAL] = { ...existing, print: recordMupdfDiagnostic, printErr: recordMupdfDiagnostic };\n}\n\nfunction withMupdfDiagnostics(message: string): string {\n\tif (mupdfDiagnostics.length === 0) return message;\n\tlogMupdfDiagnostics();\n\tconst detail = mupdfDiagnostics.join(\"; \");\n\tmupdfDiagnostics = [];\n\treturn `${message} (mupdf: ${detail})`;\n}\n\nlet markit: () => Markit | Promise<Markit> = async () => {\n\tcaptureMupdfDiagnostics();\n\tconst promise = import(\"markit-ai\").then(({ Markit }) => {\n\t\tconst instance = new Markit();\n\t\tmarkit = () => instance;\n\t\treturn instance;\n\t});\n\tmarkit = () => promise;\n\treturn promise;\n};\n\nfunction normalizeExtension(extension: string): string {\n\tconst trimmed = extension.trim().toLowerCase();\n\treturn trimmed ? (trimmed.startsWith(\".\") ? trimmed : `.${trimmed}`) : \".bin\";\n}\n\nfunction normalizeError(error: unknown): string {\n\treturn error instanceof Error && error.message.trim().length > 0 ? error.message.trim() : \"Conversion failed\";\n}\n\nfunction abortError(): Error {\n\tconst error = new Error(\"Aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\n\nasync function runMarkitConversion<T>(task: (markit: Markit) => Promise<T>, signal?: AbortSignal): Promise<T> {\n\tif (signal?.aborted) throw abortError();\n\tconst instance = await markit();\n\tmupdfDiagnostics = [];\n\tif (!signal) return task(instance);\n\treturn await new Promise<T>((resolve, reject) => {\n\t\tconst abort = () => reject(abortError());\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tvoid task(instance)\n\t\t\t.then(resolve, reject)\n\t\t\t.finally(() => signal.removeEventListener(\"abort\", abort));\n\t});\n}\n\nfunction finalizeConversion(markdown?: string): MarkitConversionResult {\n\tif (typeof markdown === \"string\" && markdown.length > 0) {\n\t\tlogMupdfDiagnostics();\n\t\tmupdfDiagnostics = [];\n\t\treturn { content: markdown, ok: true };\n\t}\n\treturn { content: \"\", ok: false, error: withMupdfDiagnostics(\"Conversion produced no output\") };\n}\n\nexport async function convertFileWithMarkit(filePath: string, signal?: AbortSignal): Promise<MarkitConversionResult> {\n\ttry {\n\t\treturn finalizeConversion(\n\t\t\t(await runMarkitConversion((instance) => instance.convertFile(filePath), signal)).markdown,\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.name === \"AbortError\") throw error;\n\t\treturn { content: \"\", ok: false, error: withMupdfDiagnostics(normalizeError(error)) };\n\t}\n}\n\nexport async function convertBufferWithMarkit(\n\tbuffer: Uint8Array,\n\textension: string,\n\tsignal?: AbortSignal,\n): Promise<MarkitConversionResult> {\n\tconst normalizedExtension = normalizeExtension(extension);\n\tconst streamInfo: StreamInfo = { extension: normalizedExtension, filename: `input${normalizedExtension}` };\n\ttry {\n\t\treturn finalizeConversion(\n\t\t\t(await runMarkitConversion((instance) => instance.convert(Buffer.from(buffer), streamInfo), signal)).markdown,\n\t\t);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.name === \"AbortError\") throw error;\n\t\treturn { content: \"\", ok: false, error: withMupdfDiagnostics(normalizeError(error)) };\n\t}\n}\n"]}
@@ -25,6 +25,10 @@ Opening `/tasks` is navigation, not an approval request. It does not mark the ag
25
25
 
26
26
  The agent can choose foreground-first or background observation for each authorized shell or subagent call. Choosing a mode does not require a separate user confirmation and does not relax tool permissions or task ownership.
27
27
 
28
+ For ordinary shell commands, leave `wait` out rather than routinely requesting one-second waits. Short waits can background otherwise brief commands and add follow-up calls without speeding up execution. Use explicit background observation when you have independent work to do, and a short budget only when you need control back sooner. Explicit budgets remain supported on every platform.
29
+
30
+ Keep immediately blocking work local unless a specialist, isolated context, or your explicit delegation request makes a subagent worthwhile. After spawning, continue independent work without duplicating the child's task. Wait when its result becomes a dependency; otherwise rely on completion notices rather than repeated short waits or status polls.
31
+
28
32
  | Call | Observation behavior |
29
33
  | --- | --- |
30
34
  | `bash` or `powershell` without `wait` | Waits for the owner's command observation budget, normally 10 seconds, then automatically returns if still running. |
@@ -75,7 +79,7 @@ A launch result says **Launched in background**. This records what happened at l
75
79
 
76
80
  ### Waiting is not restarting
77
81
 
78
- To wait briefly before continuing:
82
+ When specialist delegation is useful and its result is needed next, use foreground observation:
79
83
 
80
84
  ```ts
81
85
  subagent({
@@ -88,7 +92,7 @@ subagent({
88
92
  If that observation budget expires, the same child continues in the background. It is not an execution timeout. Observe the task ID returned by the original call:
89
93
 
90
94
  ```ts
91
- subagent({ action: "wait", id: taskId, budgetMs: 1000 })
95
+ subagent({ action: "wait", id: taskId })
92
96
  subagent({ action: "status", id: taskId })
93
97
  ```
94
98
 
@@ -156,14 +160,14 @@ Completed, failed, and stopped tasks retain inspection but do not offer executio
156
160
  Top-level model `bash` calls on POSIX and native Windows, and `powershell` calls on native Windows, use the session's task owner. A long command can outlive its foreground observation budget and return a task ID while continuing to run. Its status then appears below the prompt and under **Shells** in `/tasks`. An explicit execution timeout still ends the command; it is separate from observation yielding.
157
161
 
158
162
  ```ts
159
- // Background immediately, keeping the command owned and its output retained.
160
- bash({ command: "npm run build", wait: { kind: "background" }, timeout: 600 })
163
+ // Ordinary commands use the owner's observation budget, normally 10 seconds.
164
+ bash({ command: "npm run check" })
161
165
 
162
- // Foreground-first, automatically yielding after one second if still running.
163
- bash({ command: "npm test", wait: { kind: "foreground", budgetMs: 1000 }, timeout: 600 })
166
+ // Background a build when you can do independent work while it runs.
167
+ bash({ command: "npm run build", wait: { kind: "background" }, timeout: 600 })
164
168
 
165
- // Keep the default automatic observation budget.
166
- bash({ command: "npm run check" })
169
+ // Wait longer when the test result is needed next; execution timeout is separate.
170
+ bash({ command: "npm test", wait: { kind: "foreground", budgetMs: 30000 }, timeout: 600 })
167
171
  ```
168
172
 
169
173
  The shell execution timeout is separate: `timeout` is seconds and defaults to 300, with a maximum of 3600. It continues counting after backgrounding. Choose a timeout appropriate for the command; reducing `budgetMs` does not shorten or extend it. Use the returned task ID to inspect or stop the existing task through `/tasks`. Background completion notifies the parent automatically, so there is no need to launch the command again to collect its result.
@@ -171,8 +175,8 @@ The shell execution timeout is separate: `timeout` is seconds and defaults to 30
171
175
  Observe an existing task without running its command again:
172
176
 
173
177
  ```ts
174
- bash({ action: "wait", id: taskId, budgetMs: 1000 })
175
- powershell({ action: "wait", id: taskId, budgetMs: 1000 })
178
+ bash({ action: "wait", id: taskId })
179
+ powershell({ action: "wait", id: taskId })
176
180
  ```
177
181
 
178
182
  Use the original task ID from the same owning session or workflow stage. Omit `budgetMs` to use the owner's command observation policy, or pass `0` to poll. A wait returns retained output and a yielded or settled observation; settled results include available exit and failure details. While running, successive yielded waits advance through retained output in bounded pages, including after a session reload. A caught-up wait returns no output until more arrives. Settled waits return all retained output again, subject to labelled gaps and truncation, so they may repeat output you have already seen.
@@ -10,7 +10,7 @@ There are two general options. You can either
10
10
 
11
11
  | Pattern | What is isolated | Best for | Notes |
12
12
  | --- | --- | --- | --- |
13
- | Gondolin extension | Built-in tools and `!` commands | Local micro-VM isolation while keeping auth on host | See [`examples/extensions/gondolin/`](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/extensions/gondolin). |
13
+ | Gondolin extension | Selected file tools, shell execution, and `!` commands | Local micro-VM tool routing while keeping auth on host | Other tools, including `search`, remain on the host. See [`examples/extensions/gondolin/`](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/extensions/gondolin). |
14
14
  | Plain Docker | Whole `atomic` process in a local container | Simple local isolation | Provider API keys enter the container. |
15
15
  | OpenShell | Whole `atomic` process in a policy-controlled sandbox | Local or remote managed sandbox | Requires an OpenShell gateway. |
16
16
 
@@ -19,14 +19,14 @@ Extensions run wherever the `atomic` process runs. If you run host `atomic` with
19
19
  ## Gondolin
20
20
 
21
21
  [Gondolin](https://github.com/earendil-works/gondolin) is a local Linux micro-VM.
22
- Use the [example extension](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/extensions/gondolin) when you want `atomic` on the host but all built-in tools routed into the VM.
22
+ Use the [example extension](https://github.com/bastani-inc/atomic/tree/main/packages/coding-agent/examples/extensions/gondolin) when you want `atomic` on the host with selected file tools and shell execution routed into the VM. This is not isolation for the entire session.
23
23
 
24
24
  Setup:
25
25
 
26
26
  ```bash
27
27
  cp -R packages/coding-agent/examples/extensions/gondolin ~/.atomic/agent/extensions/gondolin
28
28
  cd ~/.atomic/agent/extensions/gondolin
29
- bun install --ignore-scripts
29
+ npm ci --ignore-scripts
30
30
  ```
31
31
 
32
32
  Run from the project you want mounted:
@@ -36,11 +36,13 @@ cd /path/to/project
36
36
  atomic -e ~/.atomic/agent/extensions/gondolin
37
37
  ```
38
38
 
39
- The extension mounts the host cwd at `/workspace` in the VM and overrides `read`, `write`, `edit`, `bash`, `find`, and `search` so the default coding tools operate inside the VM.
39
+ The extension mounts the host cwd at `/workspace` in the VM and overrides `read`, `write`, `edit`, `bash`, `find`, and `ls`.
40
40
  User `!` commands are routed into the VM, as well.
41
41
  File changes under `/workspace` write through to the host.
42
42
 
43
- Requirements: Bun for dependency installation, Node.js >= 23.6.0 for `@earendil-works/gondolin`, plus QEMU (requires installation through your package manager).
43
+ `search` remains a host tool; it is not redirected into the VM. The removed `grep` tool is not registered. For guest-only content searches, use a shell command through the routed `bash` tool or `!` command. To expose only these routed tools, start with `atomic --tools read,write,edit,bash,find,ls -e ~/.atomic/agent/extensions/gondolin`; other loaded extensions can still supply host-side tools. Use whole-process isolation instead when host filesystem access must be prevented.
44
+
45
+ Requirements: npm for dependency installation, Node.js >= 23.6.0 for `@earendil-works/gondolin`, plus QEMU (requires installation through your package manager).
44
46
 
45
47
  ## Plain Docker
46
48
 
@@ -50,6 +50,17 @@ Never use `__dirname` directly for package assets.
50
50
 
51
51
  For startup measurements, see the [Windows startup benchmark](https://github.com/bastani-inc/atomic/blob/main/scripts/perf/windows-startup/README.md). Internal timing marks do not prove terminal first paint.
52
52
 
53
+ ## PDF and engine diagnostics
54
+
55
+ PDF conversion and engine diagnostics appear as status messages in interactive sessions
56
+ and console output otherwise. Conversion failures also include diagnostic details in
57
+ their error result. Long or noisy diagnostics may be truncated. Interactive sessions keep
58
+ only recent diagnostics; older diagnostics are discarded without removing normal chat.
59
+
60
+ Diagnostics are displayed as text, not terminal commands. RPC clients receive diagnostics
61
+ separately from JSON responses. No `atomic-engine-stderr.log` file is written; include the
62
+ displayed diagnostic and conversion error when reporting a PDF problem.
63
+
53
64
  ## Testing
54
65
 
55
66
  ```bash
package/docs/docs.json CHANGED
@@ -70,6 +70,7 @@
70
70
  "pages": [
71
71
  "tools",
72
72
  "tools/edit",
73
+ "web-access",
73
74
  "session-format"
74
75
  ]
75
76
  },
package/docs/providers.md CHANGED
@@ -118,7 +118,7 @@ Run `/login xai`, then select **Use a subscription**. `XAI_API_KEY` remains avai
118
118
 
119
119
  Atomic defaults xAI sessions to `grok-4.6`. Built-in workflow and subagent fallback chains use `xai/grok-4.6:xhigh`, `github-copilot/grok-4.6:xhigh`, and `openrouter/x-ai/grok-4.6:xhigh`; GitHub Copilot also exposes Grok 4.6 when the account's model policy enables it. Network-backed catalogs refresh and cache these newer entries independently of the bundled catalog snapshot.
120
120
 
121
- The `codebase-locator`, `codebase-pattern-finder`, and `codebase-research-locator` agents use GPT-5.6 Luna at `xhigh` and Grok fallbacks at `medium` instead. Goal and Ralph orchestration, Ralph research, and Open Claude Design use GPT-6 Astra at `medium`; Ralph prompt refinement remains at `high`.
121
+ The `codebase-locator`, `codebase-pattern-finder`, and `codebase-research-locator` agents use GPT-5.6 Luna at `xhigh` and Grok fallbacks at `medium` instead. Goal and Ralph orchestration, Ralph research, and the debugger use GPT-6 Astra at `medium`; Ralph prompt refinement remains at `high`. Open Claude Design starts with Anthropic Fable 5.1 at `medium`, then GitHub Copilot Fable 5.1 and Codex, Copilot, and OpenAI Astra at `medium`.
122
122
 
123
123
  ### Radius
124
124
 
package/docs/subagents.md CHANGED
@@ -7,6 +7,8 @@ description: "Run focused Atomic child agents"
7
7
 
8
8
  Atomic bundles `@bastani/subagents`, an extension for bounded specialist delegation with separate context while the parent remains in control. Use a single agent or parallel fan-out when isolation or a specialist pass materially helps with locating code, analyzing behavior, researching references, reproducing actual failures, or simplifying code. Keep interactive, exploratory, conceptual, and conversation-led work inline when direct user steering is more useful.
9
9
 
10
+ Keep immediately blocking work local unless specialist expertise, context isolation, or an explicit delegation request makes a child worthwhile. Delegate independent work you can overlap with your own next steps, then continue without duplicating the child's task. If a specialist's result is needed next, foreground observation is still available. Wait when the result becomes a dependency; otherwise rely on completion notices rather than repeated short waits or status polls.
11
+
10
12
  You do not need to install anything separately when you use `@bastani/atomic`.
11
13
 
12
14
  Background subagents are supported. See [Background tasks](/background-tasks) for launch examples, the below-prompt status indicator, `/tasks`, shell output, cancellation, and completion notices.
@@ -67,7 +69,7 @@ Subagents now run and return their results directly. Atomic does not infer accep
67
69
 
68
70
  ## Owner-bound task observation
69
71
 
70
- Runtime-created session contexts bind single launches to their actual session or workflow-stage owner. Omitted `wait` returns an admitted observation with reason `default-background`; `wait: {kind: "background"}` uses reason `explicit`. `wait: {kind: "foreground", budgetMs: 30000}` opts into foreground-first observation. The omitted foreground budget is 30000 ms. `subagent({action: "wait", id: taskId, budgetMs: 1000})` observes an existing task in the same owner without restarting it.
72
+ Runtime-created session contexts bind single launches to their actual session or workflow-stage owner. Omitted `wait` returns an admitted observation with reason `default-background`; `wait: {kind: "background"}` uses reason `explicit`. `wait: {kind: "foreground", budgetMs: 30000}` opts into foreground-first observation. The omitted foreground budget is 30000 ms. `subagent({action: "wait", id: taskId})` observes an existing task in the same owner without restarting it, using the owner's observation budget unless explicitly overridden.
71
73
 
72
74
  The agent may choose foreground-first or background observation for each authorized call without asking the user merely to select a mode. When a foreground observation expires, the returned task is still running. Wait for terminal completion before using its result in dependent work. See [Choosing how long to wait](/background-tasks#choose-how-long-to-wait) for shell and subagent defaults and the separate execution-timeout behavior.
73
75
 
@@ -119,7 +121,7 @@ Atomic currently bundles these agents from `@bastani/subagents`:
119
121
  | `code-simplifier` | Simplify recently changed code under its behavior-preservation “doors” rubric. | Yes |
120
122
  | `worker` | Implement an approved task or handoff, validate the narrow change, and escalate product, architecture, or scope decisions to its supervisor. | Yes |
121
123
 
122
- All bundled agents except `debugger` default to `openai-codex/gpt-6-astra:low`; `debugger` uses `openai-codex/gpt-6-astra:xhigh`. Their fallback chains start with GitHub Copilot Astra, OpenAI Astra, Anthropic Fable 5.1, then GitHub Copilot Fable 5.1. Ordinary agents use Astra/Fable 5.1 at `low`, with Sol and GPT-5.5 fallbacks at `medium`, including the locator roles. Debugger keeps Astra and Sol at `xhigh` and Anthropic fallbacks at `high`. Later candidates retain provider-specific reasoning levels and identifiers; OpenRouter mirrors follow the direct-provider candidates. Each agent definition contains its complete ordered chain.
124
+ The bundled `debugger` defaults to `openai-codex/gpt-6-astra:medium`. Its Astra, Fable 5.1, and Fable 5 candidates use `medium`; Sol and Opus candidates use `high`. Other defaults are unchanged: the three locator roles use `openai-codex/gpt-5.6-luna:xhigh`, while the remaining agents use `openai-codex/gpt-6-astra:low`. Ordinary agents use Astra/Fable 5.1 at `low`, with Sol and GPT-5.5 fallbacks at `medium`, including the locator roles. Debugger's fallback chain starts with GitHub Copilot Astra, OpenAI Astra, Anthropic Fable 5.1, then GitHub Copilot Fable 5.1. Later candidates retain provider-specific reasoning levels and identifiers; OpenRouter mirrors follow the direct-provider candidates. Each agent definition contains its complete ordered chain.
123
125
 
124
126
  The bundled definitions keep their routing and model frontmatter but use compact, outcome-first bodies: role and goal, success criteria, constraints and tool routes, output contract, and stop rules where applicable. Report-producing agents ground progress claims in tool results and return concise evidence rather than narrating internal reasoning. Read-oriented agents inspect and report. `debugger`, `code-simplifier`, and `worker` can edit files, so give them an explicit scope and validation target. The debugger should finish an in-scope diagnosis by applying and validating the fix, not stop at a proposed patch.
125
127
 
package/docs/tools.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  Atomic enables these coding tools in normal sessions by default: `read`, `write`, `edit`, `bash`, `kill`, `find`, and `search`.
4
4
 
5
+ ## `code_search`
6
+
7
+ The bundled web-access extension provides `code_search` for questions about code, architecture, and APIs in a public GitHub repository. It uses DeepWiki MCP at `https://mcp.deepwiki.com/mcp` without an API key or local MCP configuration.
8
+
9
+ ```typescript
10
+ code_search({ repoName: "facebook/react", query: "How does useEffect cleanup work?" })
11
+ ```
12
+
13
+ Both `repoName` and `query` are required. Supply one repository in `owner/repo` format, not a GitHub URL or list, and a nonempty question. Existing query-only calls must add `repoName`. Questions are sent verbatim to DeepWiki's `ask_question` tool.
14
+
15
+ Optional `maxTokens` defaults to 5000 and accepts integers from 1000 to 50000. It is a best-effort output bound of roughly four characters per token, plus a truncation notice, not a limit on DeepWiki's generation. Requests have a 60-second deadline and honor cancellation.
16
+
17
+ Answers depend on DeepWiki's repository indexing and availability. Check the repository name when a question fails. Errors and empty responses do not fall back to Exa; use `web_search` for broader discovery or unavailable repositories. `web_search` retains its existing Exa and other provider support.
18
+
5
19
  ## Hashline editing anchors
6
20
 
7
21
  `read`, `search`, `write`, and successful `edit` results for local text files emit an editable, session-scoped hashline header:
@@ -24,6 +38,18 @@ insert tail:
24
38
 
25
39
  Block operations resolve through Atomic's native Rust tree-sitter primitive, with the brace/indent heuristic only as a fallback when the native binding is unavailable. See the [`edit` hashline specification](/tools/edit) for every operation, verified tolerated input shape, output and recovery behavior, limits, worked examples, literal error messages, and warnings.
26
40
 
41
+ If a file or its parent directory becomes inaccessible after `edit` prepares a patch, the edit is refused with `FILE_MUTATION_CONFLICT:target_unreadable` and the filesystem error code, such as `EACCES`. No changes are written. Restore access, then read the file again before retrying.
42
+
43
+ ## `write`
44
+
45
+ `write` overwriting an existing file requires this session to have already observed exactly the content it is replacing, checked under the same per-file mutation queue that serializes the write itself. Creating a new file is unaffected, and so is overwriting a file this session read, wrote, or edited earlier. Where a session has no version of its own, the refusal is `no_prior_observation`; where it has one that no longer matches what is on disk, it is `changed_since_observation` and names the first diverging line, what the session assumed was there, and what the file holds instead. Both carry the same `FILE_MUTATION_CONFLICT` code and requester identity as an `edit` conflict, so a `write` that would have silently discarded another agent's file is reported rather than performed. Snapshots are per session, so a file read by a different session or a previous run does not authorize an overwrite here either. A write whose result is aborted after the bytes have already reached disk still records its snapshot, so retrying it is not mistaken for overwriting a stranger's file.
46
+
47
+ Standalone `createWriteToolDefinition(cwd)` and `createWriteTool(cwd)` instances retain their own observations across `local://` writes, just as they do for plain paths, even when no `hashlineStore` is supplied. Separate instances still need an explicitly shared store to share observations.
48
+
49
+ Creating a file claims the path exclusively. `write` asks the filesystem for create-or-fail semantics (`O_EXCL`) whenever it has just observed the path as absent, so a file that appears in the window between that check and the write is reported as `target_exists` with a description of what is there now, rather than being silently truncated. Overwrites do not request exclusivity, since they are replacing a file the session has already accounted for.
50
+
51
+ `WriteOperations` carries the read `write` performs before every write. Custom implementations must supply it, and it must report absence as `undefined` while rejecting for anything else: a path that exists but cannot be read is not a free path, and reporting it as absent would present it as a fresh create and truncate it. Such a rejection surfaces as `target_unreadable`, including the filesystem error code when the backend supplies one. Routing the read through `WriteOperations` is what lets a remote or sandboxed implementation have these checks run against the filesystem its writes actually land on, instead of against local disk. An implementation that cannot express exclusive create may ignore that request and overwrite; it then loses only the race against writers outside Atomic, since the mutation queue already excludes writers inside it.
52
+
27
53
  ## `bash` and `bashInterceptor`
28
54
 
29
55
  The `bash` tool executes shell commands in the session workspace, with optional PTY handling. When `pty: true` is requested, local execution uses the bundled Rust-backed PTY session; if the native PTY package is unavailable, Atomic degrades to normal pipe execution. Set `PI_NO_PTY=1` or `ATOMIC_NO_PTY=1` to force normal pipe execution. Foreground results include oh-my-pi-style `timeoutSeconds`, `requestedTimeoutSeconds`, `wallTimeMs`, and non-zero `exitCode` metadata, and preserve overflow output in a temporary `fullOutputPath` when output is truncated.