@code-yeongyu/senpi 2026.8.27 → 2026.8.28-2

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 (181) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/dist/cli/args.d.ts +2 -0
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +4 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/core/agent-session-services.d.ts.map +1 -1
  7. package/dist/core/agent-session-services.js +2 -0
  8. package/dist/core/agent-session-services.js.map +1 -1
  9. package/dist/core/agent-session.d.ts +5 -0
  10. package/dist/core/agent-session.d.ts.map +1 -1
  11. package/dist/core/agent-session.js +1 -0
  12. package/dist/core/agent-session.js.map +1 -1
  13. package/dist/core/auth-storage.d.ts +1 -0
  14. package/dist/core/auth-storage.d.ts.map +1 -1
  15. package/dist/core/auth-storage.js +3 -0
  16. package/dist/core/auth-storage.js.map +1 -1
  17. package/dist/core/credential-accounts.d.ts +31 -0
  18. package/dist/core/credential-accounts.d.ts.map +1 -0
  19. package/dist/core/credential-accounts.js +135 -0
  20. package/dist/core/credential-accounts.js.map +1 -0
  21. package/dist/core/credential-pool/classify.d.ts +6 -1
  22. package/dist/core/credential-pool/classify.d.ts.map +1 -1
  23. package/dist/core/credential-pool/classify.js +22 -5
  24. package/dist/core/credential-pool/classify.js.map +1 -1
  25. package/dist/core/credential-pool/failover.d.ts +8 -0
  26. package/dist/core/credential-pool/failover.d.ts.map +1 -1
  27. package/dist/core/credential-pool/failover.js +24 -6
  28. package/dist/core/credential-pool/failover.js.map +1 -1
  29. package/dist/core/credential-pool/rotation-stream.d.ts +13 -2
  30. package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -1
  31. package/dist/core/credential-pool/rotation-stream.js +97 -10
  32. package/dist/core/credential-pool/rotation-stream.js.map +1 -1
  33. package/dist/core/extensions/builtin/account/index.d.ts +9 -0
  34. package/dist/core/extensions/builtin/account/index.d.ts.map +1 -0
  35. package/dist/core/extensions/builtin/account/index.js +69 -0
  36. package/dist/core/extensions/builtin/account/index.js.map +1 -0
  37. package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
  38. package/dist/core/extensions/builtin/goal/index.js +7 -0
  39. package/dist/core/extensions/builtin/goal/index.js.map +1 -1
  40. package/dist/core/extensions/builtin/imagegen/index.d.ts.map +1 -1
  41. package/dist/core/extensions/builtin/imagegen/index.js +10 -3
  42. package/dist/core/extensions/builtin/imagegen/index.js.map +1 -1
  43. package/dist/core/extensions/builtin/index.d.ts.map +1 -1
  44. package/dist/core/extensions/builtin/index.js +4 -0
  45. package/dist/core/extensions/builtin/index.js.map +1 -1
  46. package/dist/core/extensions/builtin/service-tier.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/service-tier.js +13 -0
  48. package/dist/core/extensions/builtin/service-tier.js.map +1 -1
  49. package/dist/core/extensions/builtin/terminal/extension.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/terminal/extension.js +4 -2
  51. package/dist/core/extensions/builtin/terminal/extension.js.map +1 -1
  52. package/dist/core/model-config-schema.d.ts +4 -4
  53. package/dist/core/model-runtime.d.ts +2 -0
  54. package/dist/core/model-runtime.d.ts.map +1 -1
  55. package/dist/core/model-runtime.js +74 -37
  56. package/dist/core/model-runtime.js.map +1 -1
  57. package/dist/core/retry-fallback/chains.d.ts +23 -1
  58. package/dist/core/retry-fallback/chains.d.ts.map +1 -1
  59. package/dist/core/retry-fallback/chains.js +59 -3
  60. package/dist/core/retry-fallback/chains.js.map +1 -1
  61. package/dist/core/retry-fallback/controller.d.ts.map +1 -1
  62. package/dist/core/retry-fallback/controller.js +9 -2
  63. package/dist/core/retry-fallback/controller.js.map +1 -1
  64. package/dist/core/retry-fallback/settings.d.ts.map +1 -1
  65. package/dist/core/retry-fallback/settings.js +9 -0
  66. package/dist/core/retry-fallback/settings.js.map +1 -1
  67. package/dist/core/retry-fallback/validate.js +1 -1
  68. package/dist/core/retry-fallback/validate.js.map +1 -1
  69. package/dist/core/sdk.js +1 -1
  70. package/dist/core/sdk.js.map +1 -1
  71. package/dist/core/session-manager.d.ts +9 -0
  72. package/dist/core/session-manager.d.ts.map +1 -1
  73. package/dist/core/session-manager.js +31 -0
  74. package/dist/core/session-manager.js.map +1 -1
  75. package/dist/main.d.ts +7 -0
  76. package/dist/main.d.ts.map +1 -1
  77. package/dist/main.js +22 -2
  78. package/dist/main.js.map +1 -1
  79. package/dist/modes/app-server/server/account.d.ts.map +1 -1
  80. package/dist/modes/app-server/server/account.js +5 -5
  81. package/dist/modes/app-server/server/account.js.map +1 -1
  82. package/dist/modes/interactive/components/footer.d.ts +11 -3
  83. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  84. package/dist/modes/interactive/components/footer.js +31 -1
  85. package/dist/modes/interactive/components/footer.js.map +1 -1
  86. package/dist/modes/interactive/grok/chrome.d.ts +4 -4
  87. package/dist/modes/interactive/grok/chrome.d.ts.map +1 -1
  88. package/dist/modes/interactive/grok/chrome.js.map +1 -1
  89. package/dist/modes/interactive/grok/footer.d.ts +3 -3
  90. package/dist/modes/interactive/grok/footer.d.ts.map +1 -1
  91. package/dist/modes/interactive/grok/footer.js.map +1 -1
  92. package/dist/modes/interactive/interactive-host-runtime.d.ts +16 -1
  93. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -1
  94. package/dist/modes/interactive/interactive-host-runtime.js +321 -36
  95. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -1
  96. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  97. package/dist/modes/interactive/interactive-mode.js +295 -250
  98. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  99. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  100. package/dist/modes/rpc/connection-handler.js +144 -29
  101. package/dist/modes/rpc/connection-handler.js.map +1 -1
  102. package/dist/modes/rpc/multi-session-host.js +14 -4
  103. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  104. package/dist/modes/rpc/rpc-client.d.ts +90 -8
  105. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  106. package/dist/modes/rpc/rpc-client.js +118 -23
  107. package/dist/modes/rpc/rpc-client.js.map +1 -1
  108. package/dist/modes/rpc/rpc-mode.d.ts +3 -1
  109. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  110. package/dist/modes/rpc/rpc-mode.js +3 -1
  111. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  112. package/dist/modes/rpc/rpc-types.d.ts +164 -2
  113. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  114. package/dist/modes/rpc/rpc-types.js.map +1 -1
  115. package/dist/modes/rpc/session-command-router.d.ts +22 -0
  116. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  117. package/dist/modes/rpc/session-command-router.js +153 -14
  118. package/dist/modes/rpc/session-command-router.js.map +1 -1
  119. package/dist/modes/rpc/session-event-writer.d.ts +2 -0
  120. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  121. package/dist/modes/rpc/session-event-writer.js +4 -0
  122. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  123. package/dist/modes/rpc/session-registry.d.ts +16 -0
  124. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  125. package/dist/modes/rpc/session-registry.js +40 -3
  126. package/dist/modes/rpc/session-registry.js.map +1 -1
  127. package/docs/providers.md +48 -0
  128. package/docs/rpc.md +43 -4
  129. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +26 -0
  130. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  131. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +13 -1
  132. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +15 -1
  133. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +14 -1
  134. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.d.ts.map +1 -1
  135. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +20 -4
  136. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js.map +1 -1
  137. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts +1 -1
  138. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts.map +1 -1
  139. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js.map +1 -1
  140. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts +21 -0
  141. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts.map +1 -0
  142. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js +27 -0
  143. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js.map +1 -0
  144. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts +24 -0
  145. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts.map +1 -1
  146. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js.map +1 -1
  147. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.d.ts.map +1 -1
  148. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +7 -2
  149. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js.map +1 -1
  150. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  151. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts +2 -1
  152. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts.map +1 -1
  153. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js +2 -1
  154. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js.map +1 -1
  155. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts +3 -2
  156. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts.map +1 -1
  157. package/node_modules/@earendil-works/pi-ai/dist/auth/types.js.map +1 -1
  158. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  159. package/node_modules/@earendil-works/pi-ai/dist/providers/data/alibaba-token-plan.json +1 -1
  160. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  161. package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  162. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  163. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  164. package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  165. package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  166. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  167. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  168. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  169. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  170. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  171. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  172. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  173. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  174. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  175. package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  176. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  177. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  178. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  179. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  180. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  181. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"session-registry.js","sour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CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;YACrD,SAAS;YACT,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG;YACtB,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,cAAc,EAAE;YAC5D,MAAM,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,eAAe,CAAC,OAAgC;QACvD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC;YACzG,MAAM,IAAI,uBAAuB,CAAC,cAAc,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;CACD","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport { ProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport {\n\ttype AgentSessionLaunchProfile,\n\ttype AgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\tcreateAgentSessionRuntime,\n} from \"../../core/agent-session-runtime.ts\";\nimport { SessionManager } from \"../../core/session-manager.ts\";\n\n/** The immutable flags selected when a routing session is opened. */\nexport interface RpcSessionLaunchProfile extends AgentSessionLaunchProfile {\n\tsessionPath?: string;\n}\n\nexport type SessionRuntime = Pick<AgentSessionRuntime, \"session\" | \"dispose\">;\nexport type RpcSessionState = \"opening\" | \"open\" | \"closing\" | \"closed\";\n\nexport interface RpcSessionEntry {\n\tstate: RpcSessionState;\n\truntime?: SessionRuntime;\n\tscope: ProviderScope;\n\tprofile: Readonly<RpcSessionLaunchProfile>;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\tlifecycleMutex: Promise<void>;\n}\n\nexport class RpcSessionRegistryError extends Error {\n\treadonly code: \"unknown_session\" | \"session_closing\" | \"session_path_in_use\" | \"invalid_path\" | \"open_failed\";\n\n\tconstructor(code: RpcSessionRegistryError[\"code\"], reason?: string) {\n\t\tsuper(code === \"open_failed\" && reason ? `${code}: ${reason}` : code);\n\t\tthis.code = code;\n\t\tthis.name = \"RpcSessionRegistryError\";\n\t}\n}\n\nexport interface RpcSessionRegistryOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n}\n\nexport interface OpenRpcSession {\n\tsessionId: string;\n\tdurableSessionId: string;\n\tsessionPath?: string;\n}\n\nfunction canonicalPath(path: string): string {\n\tconst absolutePath = resolve(path);\n\tif (existsSync(absolutePath)) return realpathSync(absolutePath);\n\treturn `${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`;\n}\n\nfunction frozenProfile(profile: RpcSessionLaunchProfile): Readonly<RpcSessionLaunchProfile> {\n\treturn Object.freeze({\n\t\t...profile,\n\t\t...(profile.creationModel ? { creationModel: Object.freeze({ ...profile.creationModel }) } : {}),\n\t});\n}\n\n/** Process-local lifecycle owner for multi-session RPC runtimes. */\nexport class RpcSessionRegistry {\n\tprivate readonly entries = new Map<string, RpcSessionEntry>();\n\tprivate readonly reservations = new Set<string>();\n\tprivate nextHandle = 0;\n\tprivate readonly options: RpcSessionRegistryOptions;\n\n\tconstructor(options: RpcSessionRegistryOptions) {\n\t\tthis.options = options;\n\t}\n\n\tasync openSession(profile: RpcSessionLaunchProfile): Promise<OpenRpcSession> {\n\t\tthis.validateProfile(profile);\n\t\tconst sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;\n\t\tif (sessionPath && this.reservations.has(sessionPath)) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\tif (sessionPath) this.reservations.add(sessionPath);\n\n\t\t// Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):\n\t\t// Create-only launch semantics mirror classic startup flags. A resumed\n\t\t// session restores its persisted model and thinking level instead of being\n\t\t// overridden by the new open_session request.\n\t\tconst isResume = sessionPath !== undefined && existsSync(sessionPath);\n\t\tconst storedProfile = frozenProfile({ ...profile, ...(sessionPath ? { sessionPath } : {}) });\n\t\tconst runtimeProfile = isResume\n\t\t\t? frozenProfile({ ...storedProfile, creationModel: undefined, initialThinkingLevel: undefined })\n\t\t\t: storedProfile;\n\n\t\tconst handle = `rpc-${++this.nextHandle}`;\n\t\tconst entry: RpcSessionEntry = {\n\t\t\tstate: \"opening\",\n\t\t\tscope: new ProviderScope(),\n\t\t\tprofile: storedProfile,\n\t\t\tsessionPath,\n\t\t\tlifecycleMutex: Promise.resolve(),\n\t\t};\n\t\tthis.entries.set(handle, entry);\n\t\ttry {\n\t\t\tconst manager = sessionPath\n\t\t\t\t? SessionManager.open(sessionPath, undefined, storedProfile.cwd)\n\t\t\t\t: SessionManager.create(storedProfile.cwd);\n\t\t\tentry.runtime = await runWithProviderScope(entry.scope, () =>\n\t\t\t\tcreateAgentSessionRuntime(this.options.createRuntime, {\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tagentDir: this.options.agentDir,\n\t\t\t\t\tsessionManager: manager,\n\t\t\t\t\tlaunchProfile: runtimeProfile,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.sessionPath ??= manager.getSessionFile();\n\t\t\tentry.state = \"open\";\n\t\t\treturn { sessionId: handle, durableSessionId: entry.durableSessionId, sessionPath: entry.sessionPath };\n\t\t} catch (error) {\n\t\t\t// Runtime construction may have started extensions, watchers, and provider\n\t\t\t// registrations before it rejects. Keep the reservation and entry private\n\t\t\t// until all of those resources have been torn down, then release them as\n\t\t\t// one rollback so the path can immediately be opened again.\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t} catch {\n\t\t\t\t// The original construction error remains the externally visible cause.\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait entry.scope.close?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.entries.delete(handle);\n\t\t\t\t\tif (sessionPath) this.reservations.delete(sessionPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error instanceof RpcSessionRegistryError) throw error;\n\t\t\tthrow new RpcSessionRegistryError(\"open_failed\", error instanceof Error ? error.message : undefined);\n\t\t}\n\t}\n\n\tgetForCommand(handle: string, command: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (!entry) throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tif (entry.state === \"closing\" && ![\"abort\", \"abort_bash\", \"extension_ui_response\"].includes(command)) {\n\t\t\tthrow new RpcSessionRegistryError(\"session_closing\");\n\t\t}\n\t\tif (entry.state !== \"open\" && entry.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Starts a close synchronously. Call this before disposing any session-owned\n\t * binding so a concurrent command cannot reach a half-disposed handler.\n\t */\n\tbeginClose(handle: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"open\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.state = \"closing\";\n\t\treturn entry;\n\t}\n\n\tasync close(handle: string): Promise<void> {\n\t\tthis.beginClose(handle);\n\t\treturn this.closeMarked(handle);\n\t}\n\n\t/** Completes a close previously made visible by beginClose(). */\n\tasync closeMarked(handle: string): Promise<void> {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.lifecycleMutex = (async () => {\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.session.abort();\n\t\t\t\tawait entry.runtime?.session.waitForIdle();\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t\tawait entry.scope.close?.();\n\t\t\t} finally {\n\t\t\t\tentry.state = \"closed\";\n\t\t\t\tthis.entries.delete(handle);\n\t\t\t\tif (entry.sessionPath) this.reservations.delete(entry.sessionPath);\n\t\t\t}\n\t\t})();\n\t\treturn entry.lifecycleMutex;\n\t}\n\n\tlist(): Array<{\n\t\tsessionId: string;\n\t\tdurableSessionId?: string;\n\t\tsessionPath?: string;\n\t\tcwd: string;\n\t\tname?: string;\n\t\tstatus: RpcSessionState;\n\t}> {\n\t\treturn [...this.entries].map(([sessionId, entry]) => ({\n\t\t\tsessionId,\n\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\tsessionPath: entry.sessionPath,\n\t\t\tcwd: entry.profile.cwd,\n\t\t\tname: entry.runtime?.session.sessionManager.getSessionName(),\n\t\t\tstatus: entry.state,\n\t\t}));\n\t}\n\n\tprivate validateProfile(profile: RpcSessionLaunchProfile): void {\n\t\tif (!isAbsolute(profile.cwd) || (profile.sessionPath !== undefined && !isAbsolute(profile.sessionPath))) {\n\t\t\tthrow new RpcSessionRegistryError(\"invalid_path\");\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-registry.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EAIN,yBAAyB,GACzB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAwB/D,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAGjD,YAAY,IAAqC,EAAE,MAAe;QACjE,KAAK,CAAC,IAAI,KAAK,aAAa,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,MAAM,EAAE,CAAC,CA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C3C,MAAM,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC;gBAC/B,MAAM,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;YAC7B,CAAC;oBAAS,CAAC;gBACV,KAAK,CAAC,KAAK,GAAG,QAAQ,CAAC;gBACvB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBAC5B,IAAI,KAAK,CAAC,WAAW;oBAAE,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;YACpE,CAAC;QACF,CAAC,CAAC,EAAE,CAAC;QACL,OAAO,KAAK,CAAC,cAAc,CAAC;IAC7B,CAAC;IAED,IAAI;QAQH,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;YACrD,SAAS;YACT,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,GAAG,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG;YACtB,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,cAAc,EAAE;YAC5D,MAAM,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,eAAe,CAAC,OAAgC;QACvD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC;YACzG,MAAM,IAAI,uBAAuB,CAAC,cAAc,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;CACD","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport { ProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport {\n\ttype AgentSessionLaunchProfile,\n\ttype AgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\tcreateAgentSessionRuntime,\n} from \"../../core/agent-session-runtime.ts\";\nimport { SessionManager } from \"../../core/session-manager.ts\";\n\n/** The immutable flags selected when a routing session is opened. */\nexport interface RpcSessionLaunchProfile extends AgentSessionLaunchProfile {\n\tsessionPath?: string;\n}\n\nexport type SessionRuntime = Pick<AgentSessionRuntime, \"session\" | \"dispose\">;\nexport type RpcSessionState = \"opening\" | \"open\" | \"closing\" | \"closed\";\n\nexport interface RpcSessionEntry {\n\tstate: RpcSessionState;\n\truntime?: SessionRuntime;\n\tscope: ProviderScope;\n\tprofile: Readonly<RpcSessionLaunchProfile>;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\t/** Canonical reservation key for path-opened sessions; matches the reservations set. */\n\treservationKey?: string;\n\t/** Live attachments (open + later attaches). The runtime is disposed only when the last one closes. */\n\tattachments: number;\n\tlifecycleMutex: Promise<void>;\n}\n\nexport class RpcSessionRegistryError extends Error {\n\treadonly code: \"unknown_session\" | \"session_closing\" | \"session_path_in_use\" | \"invalid_path\" | \"open_failed\";\n\n\tconstructor(code: RpcSessionRegistryError[\"code\"], reason?: string) {\n\t\tsuper(code === \"open_failed\" && reason ? `${code}: ${reason}` : code);\n\t\tthis.code = code;\n\t\tthis.name = \"RpcSessionRegistryError\";\n\t}\n}\n\nexport interface RpcSessionRegistryOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n}\n\nexport interface OpenRpcSession {\n\tsessionId: string;\n\tdurableSessionId: string;\n\tsessionPath?: string;\n\t/** True when this open attached to an already-open session instead of creating one. */\n\tattached?: boolean;\n}\n\nfunction canonicalPath(path: string): string {\n\tconst absolutePath = resolve(path);\n\tif (existsSync(absolutePath)) return realpathSync(absolutePath);\n\treturn `${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`;\n}\n\nfunction frozenProfile(profile: RpcSessionLaunchProfile): Readonly<RpcSessionLaunchProfile> {\n\treturn Object.freeze({\n\t\t...profile,\n\t\t...(profile.creationModel ? { creationModel: Object.freeze({ ...profile.creationModel }) } : {}),\n\t});\n}\n\n/** Process-local lifecycle owner for multi-session RPC runtimes. */\nexport class RpcSessionRegistry {\n\tprivate readonly entries = new Map<string, RpcSessionEntry>();\n\tprivate readonly reservations = new Set<string>();\n\tprivate nextHandle = 0;\n\tprivate readonly options: RpcSessionRegistryOptions;\n\n\tconstructor(options: RpcSessionRegistryOptions) {\n\t\tthis.options = options;\n\t}\n\n\tasync openSession(profile: RpcSessionLaunchProfile): Promise<OpenRpcSession> {\n\t\tthis.validateProfile(profile);\n\t\tconst sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;\n\t\tif (sessionPath && this.reservations.has(sessionPath)) {\n\t\t\t// Attach-on-open: a live session outlives individual client attachments, so a\n\t\t\t// resume (or a second surface) for an already-hosted path joins the existing\n\t\t\t// runtime instead of failing. Entries still opening or closing keep the\n\t\t\t// exclusive reservation and reject as before.\n\t\t\tconst existing = [...this.entries].find(\n\t\t\t\t([, entry]) => entry.reservationKey === sessionPath && entry.state === \"open\",\n\t\t\t);\n\t\t\tif (!existing) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\tconst [handle, entry] = existing;\n\t\t\tentry.attachments += 1;\n\t\t\tif (!entry.durableSessionId) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\treturn {\n\t\t\t\tsessionId: handle,\n\t\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\t\tsessionPath: entry.sessionPath,\n\t\t\t\tattached: true,\n\t\t\t};\n\t\t}\n\t\tif (sessionPath) this.reservations.add(sessionPath);\n\n\t\t// Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):\n\t\t// Create-only launch semantics mirror classic startup flags. A resumed\n\t\t// session restores its persisted model and thinking level instead of being\n\t\t// overridden by the new open_session request.\n\t\tconst isResume = sessionPath !== undefined && existsSync(sessionPath);\n\t\tconst storedProfile = frozenProfile({ ...profile, ...(sessionPath ? { sessionPath } : {}) });\n\t\tconst runtimeProfile = isResume\n\t\t\t? frozenProfile({ ...storedProfile, creationModel: undefined, initialThinkingLevel: undefined })\n\t\t\t: storedProfile;\n\n\t\tconst handle = `rpc-${++this.nextHandle}`;\n\t\tconst entry: RpcSessionEntry = {\n\t\t\tstate: \"opening\",\n\t\t\tscope: new ProviderScope(),\n\t\t\tprofile: storedProfile,\n\t\t\tsessionPath,\n\t\t\treservationKey: sessionPath,\n\t\t\tattachments: 1,\n\t\t\tlifecycleMutex: Promise.resolve(),\n\t\t};\n\t\tthis.entries.set(handle, entry);\n\t\ttry {\n\t\t\tconst manager = sessionPath\n\t\t\t\t? SessionManager.open(sessionPath, undefined, storedProfile.cwd)\n\t\t\t\t: SessionManager.create(storedProfile.cwd);\n\t\t\tentry.runtime = await runWithProviderScope(entry.scope, () =>\n\t\t\t\tcreateAgentSessionRuntime(this.options.createRuntime, {\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tagentDir: this.options.agentDir,\n\t\t\t\t\tsessionManager: manager,\n\t\t\t\t\tlaunchProfile: runtimeProfile,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.sessionPath ??= manager.getSessionFile();\n\t\t\tentry.state = \"open\";\n\t\t\treturn { sessionId: handle, durableSessionId: entry.durableSessionId, sessionPath: entry.sessionPath };\n\t\t} catch (error) {\n\t\t\t// Runtime construction may have started extensions, watchers, and provider\n\t\t\t// registrations before it rejects. Keep the reservation and entry private\n\t\t\t// until all of those resources have been torn down, then release them as\n\t\t\t// one rollback so the path can immediately be opened again.\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t} catch {\n\t\t\t\t// The original construction error remains the externally visible cause.\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait entry.scope.close?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.entries.delete(handle);\n\t\t\t\t\tif (sessionPath) this.reservations.delete(sessionPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error instanceof RpcSessionRegistryError) throw error;\n\t\t\tthrow new RpcSessionRegistryError(\"open_failed\", error instanceof Error ? error.message : undefined);\n\t\t}\n\t}\n\n\t/**\n\t * Read-only lookup with no state transitions or attachment accounting.\n\t * Exists so lifecycle decisions (e.g. deferring a dropped connection's\n\t * release while a turn is still streaming) can inspect the live entry\n\t * without claiming it.\n\t */\n\tpeek(handle: string): RpcSessionEntry | undefined {\n\t\treturn this.entries.get(handle);\n\t}\n\n\tgetForCommand(handle: string, command: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (!entry) throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tif (entry.state === \"closing\" && ![\"abort\", \"abort_bash\", \"extension_ui_response\"].includes(command)) {\n\t\t\tthrow new RpcSessionRegistryError(\"session_closing\");\n\t\t}\n\t\tif (entry.state !== \"open\" && entry.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Starts a close synchronously. Call this before disposing any session-owned\n\t * binding so a concurrent command cannot reach a half-disposed handler.\n\t * Each call releases one attachment; the entry transitions to \"closing\" only\n\t * when the last attachment closes, so callers must check the returned state\n\t * and skip finalization while other attachments remain.\n\t */\n\tbeginClose(handle: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"open\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.attachments -= 1;\n\t\tif (entry.attachments > 0) return entry;\n\t\tentry.state = \"closing\";\n\t\treturn entry;\n\t}\n\n\tasync close(handle: string): Promise<void> {\n\t\tconst entry = this.beginClose(handle);\n\t\t// Other attachments may still own the live session; only the last close finalizes.\n\t\tif (entry.state !== \"closing\") return;\n\t\treturn this.closeMarked(handle);\n\t}\n\n\t/** Completes a close previously made visible by beginClose(). */\n\tasync closeMarked(handle: string): Promise<void> {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (entry?.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tentry.lifecycleMutex = (async () => {\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.session.abort();\n\t\t\t\tawait entry.runtime?.session.waitForIdle();\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t\tawait entry.scope.close?.();\n\t\t\t} finally {\n\t\t\t\tentry.state = \"closed\";\n\t\t\t\tthis.entries.delete(handle);\n\t\t\t\tif (entry.sessionPath) this.reservations.delete(entry.sessionPath);\n\t\t\t}\n\t\t})();\n\t\treturn entry.lifecycleMutex;\n\t}\n\n\tlist(): Array<{\n\t\tsessionId: string;\n\t\tdurableSessionId?: string;\n\t\tsessionPath?: string;\n\t\tcwd: string;\n\t\tname?: string;\n\t\tstatus: RpcSessionState;\n\t}> {\n\t\treturn [...this.entries].map(([sessionId, entry]) => ({\n\t\t\tsessionId,\n\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\tsessionPath: entry.sessionPath,\n\t\t\tcwd: entry.profile.cwd,\n\t\t\tname: entry.runtime?.session.sessionManager.getSessionName(),\n\t\t\tstatus: entry.state,\n\t\t}));\n\t}\n\n\tprivate validateProfile(profile: RpcSessionLaunchProfile): void {\n\t\tif (!isAbsolute(profile.cwd) || (profile.sessionPath !== undefined && !isAbsolute(profile.sessionPath))) {\n\t\t\tthrow new RpcSessionRegistryError(\"invalid_path\");\n\t\t}\n\t}\n}\n"]}
package/docs/providers.md CHANGED
@@ -302,6 +302,54 @@ credential under the provider you select; an environment variable is shared by b
302
302
 
303
303
  The file is created with `0600` permissions (user read/write only). Auth file credentials take priority over environment variables.
304
304
 
305
+ #### Multiple accounts per provider
306
+
307
+ Any provider can hold more than one credential. The quickest way is numbered environment variables
308
+ over the provider's primary key variable - a gap in the numbering is fine:
309
+
310
+ ```bash
311
+ export OPENAI_API_KEY="sk-first"
312
+ export OPENAI_API_KEY_2="sk-second" # any provider: ANTHROPIC_API_KEY_2, GEMINI_API_KEY_2, ...
313
+ ```
314
+
315
+ Stored credentials pool through an `accounts` array. The flat top-level fields always stay a valid
316
+ credential (older binaries keep authenticating with them), and each slot's `name` is its stable
317
+ identity:
318
+
319
+ ```json
320
+ {
321
+ "openai": {
322
+ "type": "api_key",
323
+ "key": "sk-first",
324
+ "accounts": [
325
+ { "name": "default", "key": "sk-first", "source": "login" },
326
+ { "name": "work", "key": "sk-second", "source": "login" }
327
+ ],
328
+ "pinned": "work"
329
+ }
330
+ }
331
+ ```
332
+
333
+ With more than one account, requests rotate automatically: a session sticks to one account
334
+ (session-affine selection), and a rate-limited or auth-failed account fails over to a healthy
335
+ sibling **within the same provider and model** before the model fallback chain is consulted -
336
+ credential rotation changes which account serves the request, never which model answers it.
337
+ Rotation never happens after a response has started streaming. Cooldowns persist in
338
+ `~/.senpi/agent/credential-pool-state.json` (health only - never key material).
339
+
340
+ Manage accounts with `/account <provider> [list | pin <name> | unpin | remove <name>]`, and tune
341
+ behavior per provider in `models.json`:
342
+
343
+ ```json
344
+ {
345
+ "providers": {
346
+ "openai": {
347
+ "credentials": { "rotation": true, "affinity": true, "cooldownBaseMs": 60000 }
348
+ }
349
+ }
350
+ }
351
+ ```
352
+
305
353
  API key credentials can also include provider-scoped environment values. These values are used before process environment variables when resolving the credential key, provider/model headers, and provider configuration such as Cloudflare account IDs, Azure OpenAI settings, Vertex project/location, Bedrock settings, `PI_CACHE_RETENTION`, and `HTTP_PROXY`/`HTTPS_PROXY`.
306
354
 
307
355
  ```json
package/docs/rpc.md CHANGED
@@ -57,6 +57,19 @@ every open session, each tagged with its routing `sessionId`. Correlated respons
57
57
  only to the connection that issued the command. This lets a non-owner observe a foreign turn without requiring a
58
58
  separate subscription protocol.
59
59
 
60
+ ### Session auto-titling
61
+
62
+ Auto-generated session titles are on by default only for interactive launches. RPC hosts opt in with
63
+ `--auto-title-sessions`:
64
+
65
+ ```bash
66
+ senpi --mode rpc --multi-session --auto-title-sessions
67
+ ```
68
+
69
+ With the flag, every session the host opens (classic or multi-session) generates a title from its first user prompt and
70
+ publishes it to clients through the existing `session_info_changed` event; no new command or event is involved. Sessions
71
+ resumed with existing context messages are never retitled, with or without the flag.
72
+
60
73
  Startup: `senpi --mode rpc --multi-session` → NO default session is constructed (no default `AgentSessionRuntime`, no default extension/watcher load). Classic `senpi --mode rpc` is byte-identical to today. Mode is fixed at process start; there is no runtime transition.
61
74
 
62
75
  ### Interactive sessions and shared-host opt-out
@@ -100,7 +113,7 @@ hosts) sees neither variable and is unaffected. A host whose supervisor is alive
100
113
  | Command | Params | Success data | Notes |
101
114
  | --- | --- | --- | --- |
102
115
  | `get_protocol_info` | - | `{ protocolVersion: 1, serverVersion: string, capabilities: string[], mode: "classic"\|"multi" }` | Answered in BOTH modes; side-effect-free; the capability probe. Multi-session hosts include `multi_session` plus the negotiated launch capabilities. |
103
- | `open_session` | `sessionPath?`, `cwd?`, `provider?`, `modelId?`, `thinkingLevel?`, `permissionPreset?` (all optional; paths MUST be absolute) | `{ sessionId, state: RpcSessionState }` | `sessionPath` = today's `--session` semantics (open-if-exists else create persisting there, `session-manager.ts:926-940`); `provider`/`modelId` applied only on create (resume restores the session's model — mirrors `SenpiSessionRuntime.ts:198-200`); params form the immutable launch profile (D8). |
116
+ | `open_session` | `sessionPath?`, `cwd?`, `provider?`, `modelId?`, `thinkingLevel?`, `permissionPreset?` (all optional; paths MUST be absolute) | `{ sessionId, state: RpcSessionState, attached?: true }` | `sessionPath` = today's `--session` semantics (open-if-exists else create persisting there, `session-manager.ts:926-940`); `provider`/`modelId` applied only on create (resume restores the session's model — mirrors `SenpiSessionRuntime.ts:198-200`); params form the immutable launch profile (D8). When the path is already held by a fully-open session, the open ATTACHES to it: same routing handle, `attached: true`, one more attachment counted; the runtime is torn down only when the last attachment closes. |
104
117
  | `close_session` | `sessionId` | `{}` | Aborts active work, awaits agent idle + settled persistence, flushes queued events, detaches subscriptions; its response is the LAST record tagged with that handle — no events after (test-pinned). |
105
118
  | `list_sessions` | - | `{ sessions: [{ sessionId, durableSessionId, sessionPath, cwd, name, status }] }` | Includes `opening`/`closing` entries with their status. |
106
119
  | every existing command | + `sessionId` (REQUIRED in multi mode) | unchanged | Routed to that session. |
@@ -115,7 +128,7 @@ In the response `error` field, machine-matchable:
115
128
 
116
129
  - `unknown_session`
117
130
  - `session_closing`
118
- - `session_path_in_use`
131
+ - `session_path_in_use` (path held by a session still `opening` or already `closing`; a fully-open session is attached instead)
119
132
  - `missing_session_id` (session-scoped command without `sessionId` in multi mode)
120
133
  - `multi_session_disabled` (`open_session` in classic mode)
121
134
  - `invalid_path` (relative `sessionPath`/`cwd`)
@@ -131,7 +144,7 @@ Strict FIFO per session; one total stdout order; cross-session order unspecified
131
144
 
132
145
  ### Duplicate/idempotency
133
146
 
134
- Duplicate `open_session` while a path reservation is held → `session_path_in_use`. `close_session` on unknown/already-closed → `unknown_session` error. Request `id`s are client-owned; the server echoes them without dedup.
147
+ Duplicate `open_session` while a path reservation is held by a fully-open session ATTACH (`attached: true`, same handle); while held by an `opening`/`closing` entry → `session_path_in_use`. `close_session` releases one attachment; the runtime is disposed only when the last attachment closes. `close_session` on unknown/already-closed → `unknown_session` error. Request `id`s are client-owned; the server echoes them without dedup.
135
148
 
136
149
  ## Protocol Overview
137
150
 
@@ -197,9 +210,11 @@ sending/queueing. Bare inline dollar text remains literal.
197
210
 
198
211
  Response:
199
212
  ```json
200
- {"id": "req-1", "type": "response", "command": "prompt", "success": true}
213
+ {"id": "req-1", "type": "response", "command": "prompt", "success": true, "data": { "disposition": "started" }}
201
214
  ```
202
215
 
216
+ The prompt success response carries `data.disposition` (`"started"` | `"queued"` | `"handled"`), captured from the host session's own disposition callback so proxied clients can resolve optimistic-echo contracts exactly like the local path. Older hosts omit `data`; clients must then degrade to canonical-only rendering (treat the echo as rejected). The response is emitted before the user `message_start` event on the same connection, and disposition callbacks registered through the client run synchronously inside response-frame dispatch — never through the resolved promise's microtask.
217
+
203
218
  `success: true` means the prompt was accepted, queued, or handled immediately. `success: false` means the prompt was rejected before acceptance. Failures after acceptance are reported through the normal event and message stream, not as a second `response` for the same request id.
204
219
 
205
220
  The `images` field is optional. Each image uses `ImageContent` format: `{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}`.
@@ -1235,6 +1250,30 @@ Emitted when an extension calls `pi.rpc.emit(name, data)` and the client adverti
1235
1250
  the specific event name before applying it. In multi-session mode the record also includes the
1236
1251
  routing `sessionId`; delivery preserves the owning session and per-session event order.
1237
1252
 
1253
+ The terminal builtin emits `terminal_monitor_state` on this path whenever the active monitor set
1254
+ changes. `data` is `{ activeCount, monitors }`, where each monitor entry has `id`, `description`,
1255
+ `paused`, and `startedAtMs`. The matching in-process `pi.events` channel is unchanged and is not
1256
+ forwarded. Clients receive the wire record only when they advertise the `extension_events`
1257
+ capability:
1258
+
1259
+ ```json
1260
+ {
1261
+ "type": "extension_event",
1262
+ "name": "terminal_monitor_state",
1263
+ "data": {
1264
+ "activeCount": 1,
1265
+ "monitors": [
1266
+ {
1267
+ "id": "bash_1",
1268
+ "description": "watch checks",
1269
+ "paused": false,
1270
+ "startedAtMs": 1710000000000
1271
+ }
1272
+ ]
1273
+ }
1274
+ }
1275
+ ```
1276
+
1238
1277
  ### agent_start
1239
1278
 
1240
1279
  Emitted when the agent begins processing a prompt.
@@ -12,6 +12,32 @@
12
12
 
13
13
  ### Removed
14
14
 
15
+ ## [2026.8.28-2] - 2026-08-28
16
+
17
+ ### Breaking Changes
18
+
19
+ ### Added
20
+
21
+ ### Changed
22
+
23
+ ### Fixed
24
+
25
+ ### Removed
26
+
27
+ ## [2026.8.28] - 2026-08-28
28
+
29
+ ### Breaking Changes
30
+
31
+ ### Added
32
+
33
+ ### Changed
34
+
35
+ ### Fixed
36
+
37
+ - JavaScript and Python eval kernels resolve worker and prelude assets from the executable sidecar in Bun-compiled distributions instead of passing unusable `$bunfs` paths to `Worker` and `python3`.
38
+
39
+ ### Removed
40
+
15
41
  ## [2026.8.27] - 2026-08-27
16
42
 
17
43
  ### Breaking Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-codemode",
3
- "version": "2026.8.27",
3
+ "version": "2026.8.28-2",
4
4
  "private": true,
5
5
  "description": "Source-only senpi extension package for codemode evaluation tools",
6
6
  "type": "module",
@@ -31,14 +31,14 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "@babel/parser": "8.0.4",
34
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.27",
34
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.28-2",
35
35
  "typebox": "1.3.18"
36
36
  },
37
37
  "peerDependencies": {
38
- "@code-yeongyu/senpi": "2026.8.27"
38
+ "@code-yeongyu/senpi": "2026.8.28-2"
39
39
  },
40
40
  "devDependencies": {
41
- "@code-yeongyu/senpi": "2026.8.27"
41
+ "@code-yeongyu/senpi": "2026.8.28-2"
42
42
  },
43
43
  "keywords": [
44
44
  "senpi",
@@ -1,5 +1,8 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
3
  import type { HostToKernelMessage, KernelToHostMessage } from "../../bridge/protocol.ts";
2
4
  import type { KernelInterruptHandle } from "../../tool/types.ts";
5
+ import { type CodemodeRuntimeAssetEnvironment, resolveCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
3
6
  import { createInlineWorker, type WorkerLike } from "./inline-worker.ts";
4
7
  import {
5
8
  assertJavaScriptKernelOpen,
@@ -16,6 +19,15 @@ import { bridgeError, spawnNodeWorker, WorkerStartupCancelledError, waitForReady
16
19
  export { JavaScriptKernelClosedError, type JavaScriptKernelMode, type JavaScriptRunInput } from "./kernel-contract.ts";
17
20
  export type { JavaScriptKernelOptions } from "./local-module-loader.ts";
18
21
 
22
+ export interface JavaScriptWorkerEntryUrlOptions extends CodemodeRuntimeAssetEnvironment {
23
+ readonly localPath?: string;
24
+ }
25
+
26
+ export function resolveJsWorkerEntryUrl(options: JavaScriptWorkerEntryUrlOptions = {}): URL {
27
+ const localPath = options.localPath ?? join(dirname(fileURLToPath(import.meta.url)), "worker-entry.js");
28
+ return pathToFileURL(resolveCodemodeRuntimeAsset(localPath, join("kernels", "js", "worker-entry.js"), options));
29
+ }
30
+
19
31
  export class JavaScriptKernel {
20
32
  readonly #options: JavaScriptKernelOptions;
21
33
  readonly #moduleLoader: LocalModuleLoader;
@@ -161,7 +173,7 @@ export class JavaScriptKernel {
161
173
 
162
174
  #spawnWorker(): WorkerLike {
163
175
  try {
164
- const url = this.#options.workerEntryUrl ?? new URL("./worker-entry.js", import.meta.url);
176
+ const url = this.#options.workerEntryUrl ?? resolveJsWorkerEntryUrl();
165
177
  return spawnNodeWorker(url, this.#options.cwd, this.#options.parallelPoolWidth);
166
178
  } catch (error) {
167
179
  if (!(error instanceof Error)) throw error;
@@ -1,7 +1,21 @@
1
+ import { dirname, join } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
3
  import type { HostToKernelMessage, KernelToHostMessage } from "../../bridge/protocol.ts";
4
+ import { type CodemodeRuntimeAssetEnvironment, resolveCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
2
5
  import type { JavaScriptKernelMode } from "./kernel-contract.ts";
3
6
  import { spawnNodeWorker } from "./worker-host.ts";
4
7
 
8
+ export interface JavaScriptInlineWorkerEntryUrlOptions extends CodemodeRuntimeAssetEnvironment {
9
+ readonly localPath?: string;
10
+ }
11
+
12
+ export function resolveInlineWorkerEntryUrl(options: JavaScriptInlineWorkerEntryUrlOptions = {}): URL {
13
+ const localPath = options.localPath ?? join(dirname(fileURLToPath(import.meta.url)), "inline-worker-entry.js");
14
+ return pathToFileURL(
15
+ resolveCodemodeRuntimeAsset(localPath, join("kernels", "js", "inline-worker-entry.js"), options),
16
+ );
17
+ }
18
+
5
19
  export interface WorkerLike {
6
20
  readonly mode: JavaScriptKernelMode;
7
21
  postMessage(message: HostToKernelMessage): void;
@@ -11,5 +25,5 @@ export interface WorkerLike {
11
25
  }
12
26
 
13
27
  export function createInlineWorker(cwd: string, parallelPoolWidth: number): WorkerLike {
14
- return spawnNodeWorker(new URL("./inline-worker-entry.js", import.meta.url), cwd, parallelPoolWidth, "inline");
28
+ return spawnNodeWorker(resolveInlineWorkerEntryUrl(), cwd, parallelPoolWidth, "inline");
15
29
  }
@@ -8,6 +8,7 @@ import {
8
8
  isKernelToHostMessage,
9
9
  type KernelToHostMessage,
10
10
  } from "../../bridge/protocol.ts";
11
+ import { type CodemodeRuntimeAssetEnvironment, resolveCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
11
12
  import {
12
13
  defaultSpawn,
13
14
  hardKill,
@@ -47,6 +48,18 @@ export interface PythonTransportOptions {
47
48
 
48
49
  const hardKillWaitMs = 500;
49
50
 
51
+ export interface PythonPreludePathOptions extends CodemodeRuntimeAssetEnvironment {
52
+ readonly localPath?: string;
53
+ }
54
+
55
+ export function resolvePythonPreludePath(options: PythonPreludePathOptions = {}): string {
56
+ return resolveCodemodeRuntimeAsset(
57
+ options.localPath ?? join(dirname(fileURLToPath(import.meta.url)), "prelude.py"),
58
+ join("kernels", "py", "prelude.py"),
59
+ options,
60
+ );
61
+ }
62
+
50
63
  export class PythonKernelTransport {
51
64
  readonly #options: PythonTransportOptions;
52
65
  readonly #child: KernelChild;
@@ -64,7 +77,7 @@ export class PythonKernelTransport {
64
77
  }
65
78
 
66
79
  static async start(options: PythonTransportOptions): Promise<PythonKernelTransport> {
67
- const scriptPath = join(dirname(fileURLToPath(import.meta.url)), "prelude.py");
80
+ const scriptPath = resolvePythonPreludePath();
68
81
  const invocation = splitCommand(options.interpreterPath);
69
82
  const spawnOptions: KernelSpawnOptions = {
70
83
  command: invocation.command,
@@ -1 +1 @@
1
- {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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"typebox";
2
2
  import { applyEditsToNormalizedContent, detectLineEnding, generateDiffString, generateUnifiedPatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js";
3
3
  import { withFileMutationQueue } from "./file-mutation-queue.js";
4
4
  import { resolveToolPath } from "./path-utils.js";
5
+ import { appendPostMutateNote, runPostMutate } from "./post-mutate.js";
5
6
  const replaceEditSchema = Type.Object({
6
7
  oldText: Type.String({
7
8
  description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.",
@@ -63,7 +64,7 @@ export function createEditTool() {
63
64
  description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",
64
65
  parameters: editSchema,
65
66
  prepareArguments: prepareEditArguments,
66
- async execute(_toolCallId, input, signal, _onUpdate, { env }) {
67
+ async execute(_toolCallId, input, signal, _onUpdate, { env, postMutate }) {
67
68
  const { path, edits } = validateEditInput(input);
68
69
  const absolutePath = await resolveToolPath(env, path, signal);
69
70
  return withFileMutationQueue(env, absolutePath, async () => {
@@ -92,12 +93,27 @@ export function createEditTool() {
92
93
  throw editAccessError(path, writeResult.error);
93
94
  if (signal?.aborted)
94
95
  throw new Error("Operation aborted");
95
- const diffResult = generateDiffString(baseContent, newContent);
96
+ const outcome = await runPostMutate(postMutate, { tool: "edit", path: absolutePath, signal });
97
+ if (signal?.aborted)
98
+ throw new Error("Operation aborted");
99
+ let committedContent = newContent;
100
+ let rereadNote;
101
+ if (outcome.fileMayHaveChanged) {
102
+ const postMutateRead = await env.readTextFile(absolutePath, signal);
103
+ // The edit itself already landed, so an unreadable file is the hook's doing, not a
104
+ // failed edit. Report it as a note rather than an error that misattributes the failure.
105
+ if (postMutateRead.ok)
106
+ committedContent = normalizeToLF(stripBom(postMutateRead.value).text);
107
+ else
108
+ rereadNote = `postMutate left the file unreadable: ${postMutateRead.error.code}. Reported diff describes the edit before the hook ran.`;
109
+ }
110
+ const diffResult = generateDiffString(baseContent, committedContent);
111
+ const text = appendPostMutateNote(`Successfully replaced ${edits.length} block(s) in ${path}.`, outcome.note, rereadNote);
96
112
  return {
97
- content: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${path}.` }],
113
+ content: [{ type: "text", text }],
98
114
  details: {
99
115
  diff: diffResult.diff,
100
- patch: generateUnifiedPatch(path, baseContent, newContent),
116
+ patch: generateUnifiedPatch(path, baseContent, committedContent),
101
117
  firstChangedLine: diffResult.firstChangedLine,
102
118
  },
103
119
  };
@@ -1 +1 @@
1
- {"version":3,"file":"edit.js","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAEhB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,QAAQ,GACR,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGlD,MAAM,iBAAiB,GAAG,IAAI,CAAC,MAAM,CACpC;IACC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC;QACpB,WAAW,EACV,uJAAuJ;KACxJ,CAAC;IACF,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0CAA0C,EAAE,CAAC;CACjF,EACD,EAAE,CACF,CAAC;AAEF,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAC7B;IACC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,iDAAiD,EAAE,CAAC;IACrF,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAAE;QACpC,WAAW,EACV,0OAA0O;KAC3O,CAAC;CACF,EACD,EAAE,CACF,CAAC;AAMF,SA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AK,EAAE,IAAI,CAAC,CAAC;gBAClG,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAE1D,MAAM,YAAY,GAAG,GAAG,GAAG,kBAAkB,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;gBAC1E,MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,YAAY,EAAE,MAAM,CAAC,CAAC;gBAC5E,IAAI,CAAC,WAAW,CAAC,EAAE;oBAAE,MAAM,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;gBACpE,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAE1D,MAAM,UAAU,GAAG,kBAAkB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;gBAC/D,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,KAAK,CAAC,MAAM,gBAAgB,IAAI,GAAG,EAAE,CAAC;oBAC/F,OAAO,EAAE;wBACR,IAAI,EAAE,UAAU,CAAC,IAAI;wBACrB,KAAK,EAAE,oBAAoB,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC;wBAC1D,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;qBAC7C;iBACD,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { AgentHarnessTool, FileError } from \"../types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tdetectLineEnding,\n\ttype Edit,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToolPath } from \"./path-utils.ts\";\nimport type { ExecutionToolContext } from \"./tool-context.ts\";\n\nconst replaceEditSchema = Type.Object(\n\t{\n\t\toldText: Type.String({\n\t\t\tdescription:\n\t\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t\t}),\n\t\tnewText: Type.String({ description: \"Replacement text for this targeted edit.\" }),\n\t},\n\t{},\n);\n\nconst editSchema = Type.Object(\n\t{\n\t\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\t\tedits: Type.Array(replaceEditSchema, {\n\t\t\tdescription:\n\t\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t\t}),\n\t},\n\t{},\n);\n\nexport type EditToolInput = Static<typeof editSchema>;\ntype LegacyEditToolInput = EditToolInput & { oldText?: unknown; newText?: unknown };\ntype SingleEditInput = { oldText: string; newText: string };\n\nfunction isSingleEditInput(value: unknown): value is SingleEditInput {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst edit = value as Record<string, unknown>;\n\treturn typeof edit.oldText === \"string\" && typeof edit.newText === \"string\";\n}\n\nexport interface EditToolDetails {\n\tdiff: string;\n\tpatch: string;\n\tfirstChangedLine?: number;\n}\n\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\") return input as EditToolInput;\n\tconst args = input as Record<string, unknown>;\n\tif (typeof args.edits === \"string\") {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(args.edits);\n\t\t\tif (Array.isArray(parsed)) {\n\t\t\t\targs.edits = parsed;\n\t\t\t} else if (isSingleEditInput(parsed)) {\n\t\t\t\targs.edits = [parsed];\n\t\t\t}\n\t\t} catch {}\n\t} else if (isSingleEditInput(args.edits)) {\n\t\targs.edits = [args.edits];\n\t}\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") return args as EditToolInput;\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits } as EditToolInput;\n}\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\nfunction editAccessError(path: string, error: FileError): Error {\n\treturn new Error(`Could not edit file: ${path}. Error code: ${error.code}.`, { cause: error });\n}\n\nexport function createEditTool<TContext extends ExecutionToolContext = ExecutionToolContext>(): AgentHarnessTool<\n\tTContext,\n\ttypeof editSchema,\n\tEditToolDetails | undefined\n> {\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tparameters: editSchema,\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(_toolCallId, input, signal, _onUpdate, { env }) {\n\t\t\tconst { path, edits } = validateEditInput(input);\n\t\t\tconst absolutePath = await resolveToolPath(env, path, signal);\n\t\t\treturn withFileMutationQueue(env, absolutePath, async () => {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tconst info = await env.fileInfo(absolutePath, signal);\n\t\t\t\tif (!info.ok) throw editAccessError(path, info.error);\n\t\t\t\tif (info.value.kind !== \"file\" && info.value.kind !== \"symlink\") {\n\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. Path is not a file.`);\n\t\t\t\t}\n\n\t\t\t\tconst readResult = await env.readTextFile(absolutePath, signal);\n\t\t\t\tif (!readResult.ok) throw editAccessError(path, readResult.error);\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tconst { bom, text: content } = stripBom(readResult.value);\n\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\tconst writeResult = await env.writeFile(absolutePath, finalContent, signal);\n\t\t\t\tif (!writeResult.ok) throw editAccessError(path, writeResult.error);\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tconst diffResult = generateDiffString(baseContent, newContent);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully replaced ${edits.length} block(s) in ${path}.` }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tdiff: diffResult.diff,\n\t\t\t\t\t\tpatch: generateUnifiedPatch(path, baseContent, newContent),\n\t\t\t\t\t\tfirstChangedLine: diffResult.firstChangedLine,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"edit.js","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAEhB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,QAAQ,GACR,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGvE,MAAM,iBAAiB,GAAG,IAAI,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A8B,CAAC;gBACnC,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC;oBAChC,MAAM,cAAc,GAAG,MAAM,GAAG,CAAC,YAAY,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;oBACpE,mFAAmF;oBACnF,wFAAwF;oBACxF,IAAI,cAAc,CAAC,EAAE;wBAAE,gBAAgB,GAAG,aAAa,CAAC,QAAQ,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC;;wBAE5F,UAAU,GAAG,wCAAwC,cAAc,CAAC,KAAK,CAAC,IAAI,yDAAyD,CAAC;gBAC1I,CAAC;gBAED,MAAM,UAAU,GAAG,kBAAkB,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC;gBACrE,MAAM,IAAI,GAAG,oBAAoB,CAChC,yBAAyB,KAAK,CAAC,MAAM,gBAAgB,IAAI,GAAG,EAC5D,OAAO,CAAC,IAAI,EACZ,UAAU,CACV,CAAC;gBACF,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;oBACjC,OAAO,EAAE;wBACR,IAAI,EAAE,UAAU,CAAC,IAAI;wBACrB,KAAK,EAAE,oBAAoB,CAAC,IAAI,EAAE,WAAW,EAAE,gBAAgB,CAAC;wBAChE,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;qBAC7C;iBACD,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { AgentHarnessTool, FileError } from \"../types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tdetectLineEnding,\n\ttype Edit,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToolPath } from \"./path-utils.ts\";\nimport { appendPostMutateNote, runPostMutate } from \"./post-mutate.ts\";\nimport type { ExecutionToolContext } from \"./tool-context.ts\";\n\nconst replaceEditSchema = Type.Object(\n\t{\n\t\toldText: Type.String({\n\t\t\tdescription:\n\t\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t\t}),\n\t\tnewText: Type.String({ description: \"Replacement text for this targeted edit.\" }),\n\t},\n\t{},\n);\n\nconst editSchema = Type.Object(\n\t{\n\t\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\t\tedits: Type.Array(replaceEditSchema, {\n\t\t\tdescription:\n\t\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t\t}),\n\t},\n\t{},\n);\n\nexport type EditToolInput = Static<typeof editSchema>;\ntype LegacyEditToolInput = EditToolInput & { oldText?: unknown; newText?: unknown };\ntype SingleEditInput = { oldText: string; newText: string };\n\nfunction isSingleEditInput(value: unknown): value is SingleEditInput {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst edit = value as Record<string, unknown>;\n\treturn typeof edit.oldText === \"string\" && typeof edit.newText === \"string\";\n}\n\nexport interface EditToolDetails {\n\tdiff: string;\n\tpatch: string;\n\tfirstChangedLine?: number;\n}\n\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\") return input as EditToolInput;\n\tconst args = input as Record<string, unknown>;\n\tif (typeof args.edits === \"string\") {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(args.edits);\n\t\t\tif (Array.isArray(parsed)) {\n\t\t\t\targs.edits = parsed;\n\t\t\t} else if (isSingleEditInput(parsed)) {\n\t\t\t\targs.edits = [parsed];\n\t\t\t}\n\t\t} catch {}\n\t} else if (isSingleEditInput(args.edits)) {\n\t\targs.edits = [args.edits];\n\t}\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") return args as EditToolInput;\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits } as EditToolInput;\n}\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\nfunction editAccessError(path: string, error: FileError): Error {\n\treturn new Error(`Could not edit file: ${path}. Error code: ${error.code}.`, { cause: error });\n}\n\nexport function createEditTool<TContext extends ExecutionToolContext = ExecutionToolContext>(): AgentHarnessTool<\n\tTContext,\n\ttypeof editSchema,\n\tEditToolDetails | undefined\n> {\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tparameters: editSchema,\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(_toolCallId, input, signal, _onUpdate, { env, postMutate }) {\n\t\t\tconst { path, edits } = validateEditInput(input);\n\t\t\tconst absolutePath = await resolveToolPath(env, path, signal);\n\t\t\treturn withFileMutationQueue(env, absolutePath, async () => {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tconst info = await env.fileInfo(absolutePath, signal);\n\t\t\t\tif (!info.ok) throw editAccessError(path, info.error);\n\t\t\t\tif (info.value.kind !== \"file\" && info.value.kind !== \"symlink\") {\n\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. Path is not a file.`);\n\t\t\t\t}\n\n\t\t\t\tconst readResult = await env.readTextFile(absolutePath, signal);\n\t\t\t\tif (!readResult.ok) throw editAccessError(path, readResult.error);\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tconst { bom, text: content } = stripBom(readResult.value);\n\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\tconst writeResult = await env.writeFile(absolutePath, finalContent, signal);\n\t\t\t\tif (!writeResult.ok) throw editAccessError(path, writeResult.error);\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tconst outcome = await runPostMutate(postMutate, { tool: \"edit\", path: absolutePath, signal });\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\n\t\t\t\tlet committedContent = newContent;\n\t\t\t\tlet rereadNote: string | undefined;\n\t\t\t\tif (outcome.fileMayHaveChanged) {\n\t\t\t\t\tconst postMutateRead = await env.readTextFile(absolutePath, signal);\n\t\t\t\t\t// The edit itself already landed, so an unreadable file is the hook's doing, not a\n\t\t\t\t\t// failed edit. Report it as a note rather than an error that misattributes the failure.\n\t\t\t\t\tif (postMutateRead.ok) committedContent = normalizeToLF(stripBom(postMutateRead.value).text);\n\t\t\t\t\telse\n\t\t\t\t\t\trereadNote = `postMutate left the file unreadable: ${postMutateRead.error.code}. Reported diff describes the edit before the hook ran.`;\n\t\t\t\t}\n\n\t\t\t\tconst diffResult = generateDiffString(baseContent, committedContent);\n\t\t\t\tconst text = appendPostMutateNote(\n\t\t\t\t\t`Successfully replaced ${edits.length} block(s) in ${path}.`,\n\t\t\t\t\toutcome.note,\n\t\t\t\t\trereadNote,\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tdiff: diffResult.diff,\n\t\t\t\t\t\tpatch: generateUnifiedPatch(path, baseContent, committedContent),\n\t\t\t\t\t\tfirstChangedLine: diffResult.firstChangedLine,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  export { type BashExecution, type BashPrepare, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashTool, } from "./bash.ts";
2
2
  export { createEditTool, type EditToolDetails, type EditToolInput, } from "./edit.ts";
3
3
  export { createReadTool, type ReadImageProcessor, type ReadImageProcessorResult, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, } from "./read.ts";
4
- export type { ExecutionToolContext } from "./tool-context.ts";
4
+ export type { ExecutionToolContext, PostMutateContext, PostMutateHook, PostMutateResult, } from "./tool-context.ts";
5
5
  export { createWriteTool, type WriteToolInput } from "./write.ts";
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,cAAc,GACd,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,KAAK,eAAe,EACpB,KAAK,aAAa,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,KAAK,kBAAkB,EACvB,KAAK,wBAAwB,EAC7B,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,GACpB,MAAM,WAAW,CAAC;AACnB,YAAY,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,cAAc,GACd,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,KAAK,eAAe,EACpB,KAAK,aAAa,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,KAAK,kBAAkB,EACvB,KAAK,wBAAwB,EAC7B,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,GACpB,MAAM,WAAW,CAAC;AACnB,YAAY,EACX,oBAAoB,EACpB,iBAAiB,EACjB,cAAc,EACd,gBAAgB,GAChB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/harness/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAMN,cAAc,GACd,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,GAGd,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,GAMd,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,eAAe,EAAuB,MAAM,YAAY,CAAC","sourcesContent":["export {\n\ttype BashExecution,\n\ttype BashPrepare,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tcreateBashTool,\n} from \"./bash.ts\";\nexport {\n\tcreateEditTool,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n} from \"./edit.ts\";\nexport {\n\tcreateReadTool,\n\ttype ReadImageProcessor,\n\ttype ReadImageProcessorResult,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n} from \"./read.ts\";\nexport type { ExecutionToolContext } from \"./tool-context.ts\";\nexport { createWriteTool, type WriteToolInput } from \"./write.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/harness/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAMN,cAAc,GACd,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,GAGd,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,GAMd,MAAM,WAAW,CAAC;AAOnB,OAAO,EAAE,eAAe,EAAuB,MAAM,YAAY,CAAC","sourcesContent":["export {\n\ttype BashExecution,\n\ttype BashPrepare,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tcreateBashTool,\n} from \"./bash.ts\";\nexport {\n\tcreateEditTool,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n} from \"./edit.ts\";\nexport {\n\tcreateReadTool,\n\ttype ReadImageProcessor,\n\ttype ReadImageProcessorResult,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n} from \"./read.ts\";\nexport type {\n\tExecutionToolContext,\n\tPostMutateContext,\n\tPostMutateHook,\n\tPostMutateResult,\n} from \"./tool-context.ts\";\nexport { createWriteTool, type WriteToolInput } from \"./write.ts\";\n"]}
@@ -0,0 +1,21 @@
1
+ import type { PostMutateContext, PostMutateHook } from "./tool-context.ts";
2
+ /** Result of running a `postMutate` hook, with hook failures degraded to a warning note. */
3
+ export interface PostMutateOutcome {
4
+ /**
5
+ * Whether the file may differ from the bytes the tool itself wrote. True when the hook reported
6
+ * a change, and also when the hook rejected — a hook that fails midway can leave the file
7
+ * partially rewritten, so callers must re-read rather than trust their own bytes.
8
+ */
9
+ fileMayHaveChanged: boolean;
10
+ note?: string;
11
+ }
12
+ /**
13
+ * Run a `postMutate` hook after a write has already landed on disk.
14
+ *
15
+ * The write is committed by the time the hook runs, so a rejecting hook must not fail the tool
16
+ * call and lose that result. Hook failures are reported as an appended warning note instead.
17
+ */
18
+ export declare function runPostMutate(hook: PostMutateHook | undefined, input: PostMutateContext): Promise<PostMutateOutcome>;
19
+ /** Append any `postMutate` notes to tool result text, one per line, skipping absent ones. */
20
+ export declare function appendPostMutateNote(text: string, ...notes: Array<string | undefined>): string;
21
+ //# sourceMappingURL=post-mutate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"post-mutate.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/post-mutate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAoB,MAAM,mBAAmB,CAAC;AAE7F,4FAA4F;AAC5F,MAAM,WAAW,iBAAiB;IACjC;;;;OAIG;IACH,kBAAkB,EAAE,OAAO,CAAC;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAID;;;;;GAKG;AACH,wBAAsB,aAAa,CAClC,IAAI,EAAE,cAAc,GAAG,SAAS,EAChC,KAAK,EAAE,iBAAiB,GACtB,OAAO,CAAC,iBAAiB,CAAC,CAS5B;AAED,6FAA6F;AAC7F,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,CAE9F"}
@@ -0,0 +1,27 @@
1
+ const NO_CHANGE = { fileMayHaveChanged: false };
2
+ /**
3
+ * Run a `postMutate` hook after a write has already landed on disk.
4
+ *
5
+ * The write is committed by the time the hook runs, so a rejecting hook must not fail the tool
6
+ * call and lose that result. Hook failures are reported as an appended warning note instead.
7
+ */
8
+ export async function runPostMutate(hook, input) {
9
+ if (!hook)
10
+ return NO_CHANGE;
11
+ let result;
12
+ try {
13
+ result = await hook(input);
14
+ }
15
+ catch (error) {
16
+ return { fileMayHaveChanged: true, note: `postMutate hook failed: ${errorMessage(error)}` };
17
+ }
18
+ return { fileMayHaveChanged: result.changed, note: result.note };
19
+ }
20
+ /** Append any `postMutate` notes to tool result text, one per line, skipping absent ones. */
21
+ export function appendPostMutateNote(text, ...notes) {
22
+ return [text, ...notes.filter((note) => note !== undefined)].join("\n");
23
+ }
24
+ function errorMessage(error) {
25
+ return error instanceof Error ? error.message : String(error);
26
+ }
27
+ //# sourceMappingURL=post-mutate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"post-mutate.js","sourceRoot":"","sources":["../../../src/harness/tools/post-mutate.ts"],"names":[],"mappings":"AAaA,MAAM,SAAS,GAAsB,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC;AAEnE;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAClC,IAAgC,EAChC,KAAwB;IAExB,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,IAAI,MAAwB,CAAC;IAC7B,IAAI,CAAC;QACJ,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,IAAI,EAAE,2BAA2B,YAAY,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC;IAC7F,CAAC;IACD,OAAO,EAAE,kBAAkB,EAAE,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;AAClE,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,oBAAoB,CAAC,IAAY,EAAE,GAAG,KAAgC;IACrF,OAAO,CAAC,IAAI,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzE,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IACnC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { PostMutateContext, PostMutateHook, PostMutateResult } from \"./tool-context.ts\";\n\n/** Result of running a `postMutate` hook, with hook failures degraded to a warning note. */\nexport interface PostMutateOutcome {\n\t/**\n\t * Whether the file may differ from the bytes the tool itself wrote. True when the hook reported\n\t * a change, and also when the hook rejected — a hook that fails midway can leave the file\n\t * partially rewritten, so callers must re-read rather than trust their own bytes.\n\t */\n\tfileMayHaveChanged: boolean;\n\tnote?: string;\n}\n\nconst NO_CHANGE: PostMutateOutcome = { fileMayHaveChanged: false };\n\n/**\n * Run a `postMutate` hook after a write has already landed on disk.\n *\n * The write is committed by the time the hook runs, so a rejecting hook must not fail the tool\n * call and lose that result. Hook failures are reported as an appended warning note instead.\n */\nexport async function runPostMutate(\n\thook: PostMutateHook | undefined,\n\tinput: PostMutateContext,\n): Promise<PostMutateOutcome> {\n\tif (!hook) return NO_CHANGE;\n\tlet result: PostMutateResult;\n\ttry {\n\t\tresult = await hook(input);\n\t} catch (error) {\n\t\treturn { fileMayHaveChanged: true, note: `postMutate hook failed: ${errorMessage(error)}` };\n\t}\n\treturn { fileMayHaveChanged: result.changed, note: result.note };\n}\n\n/** Append any `postMutate` notes to tool result text, one per line, skipping absent ones. */\nexport function appendPostMutateNote(text: string, ...notes: Array<string | undefined>): string {\n\treturn [text, ...notes.filter((note) => note !== undefined)].join(\"\\n\");\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"]}
@@ -1,6 +1,30 @@
1
1
  import type { ExecutionEnv } from "../types.ts";
2
+ /** Mutation that triggered a `postMutate` hook run. */
3
+ export interface PostMutateContext {
4
+ /** Tool that performed the mutation. */
5
+ tool: "write" | "edit";
6
+ /** Absolute path of the file that was just written. */
7
+ path: string;
8
+ /** Abort signal of the originating tool call, when the caller supplied one. */
9
+ signal?: AbortSignal;
10
+ }
11
+ /** Outcome reported by a `postMutate` hook. */
12
+ export interface PostMutateResult {
13
+ /** Whether the hook itself rewrote the file after the tool's own write landed. */
14
+ changed: boolean;
15
+ /** Single-line note appended to the tool result text. */
16
+ note?: string;
17
+ }
18
+ /** Hook invoked inside the file mutation queue, immediately after a tool write succeeds. */
19
+ export type PostMutateHook = (input: PostMutateContext) => Promise<PostMutateResult>;
2
20
  /** Filesystem and shell context required by the built-in execution tools. */
3
21
  export interface ExecutionToolContext {
4
22
  env: ExecutionEnv;
23
+ /**
24
+ * Optional post-write hook (formatting, codegen, normalization). It runs inside the same
25
+ * mutation-queue slot as the write it follows, so the file cannot be mutated in between.
26
+ * A rejecting hook never discards the landed write; the tool appends a warning note instead.
27
+ */
28
+ postMutate?: PostMutateHook;
5
29
  }
6
30
  //# sourceMappingURL=tool-context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-context.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/tool-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,6EAA6E;AAC7E,MAAM,WAAW,oBAAoB;IACpC,GAAG,EAAE,YAAY,CAAC;CAClB"}
1
+ {"version":3,"file":"tool-context.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/tool-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,uDAAuD;AACvD,MAAM,WAAW,iBAAiB;IACjC,wCAAwC;IACxC,IAAI,EAAE,OAAO,GAAG,MAAM,CAAC;IACvB,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IACb,+EAA+E;IAC/E,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,+CAA+C;AAC/C,MAAM,WAAW,gBAAgB;IAChC,kFAAkF;IAClF,OAAO,EAAE,OAAO,CAAC;IACjB,yDAAyD;IACzD,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,4FAA4F;AAC5F,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAC;AAErF,6EAA6E;AAC7E,MAAM,WAAW,oBAAoB;IACpC,GAAG,EAAE,YAAY,CAAC;IAClB;;;;OAIG;IACH,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B"}