@code-yeongyu/senpi 2026.8.26 → 2026.8.28

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 (297) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +3 -3
  3. package/dist/cli/args.d.ts +3 -1
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +14 -1
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/core/agent-session.d.ts.map +1 -1
  8. package/dist/core/agent-session.js +10 -1
  9. package/dist/core/agent-session.js.map +1 -1
  10. package/dist/core/bash-executor.d.ts.map +1 -1
  11. package/dist/core/bash-executor.js +67 -29
  12. package/dist/core/bash-executor.js.map +1 -1
  13. package/dist/core/credential-accounts.d.ts +31 -0
  14. package/dist/core/credential-accounts.d.ts.map +1 -0
  15. package/dist/core/credential-accounts.js +125 -0
  16. package/dist/core/credential-accounts.js.map +1 -0
  17. package/dist/core/credential-pool/classify.d.ts +42 -0
  18. package/dist/core/credential-pool/classify.d.ts.map +1 -0
  19. package/dist/core/credential-pool/classify.js +75 -0
  20. package/dist/core/credential-pool/classify.js.map +1 -0
  21. package/dist/core/credential-pool/env-slots.d.ts +22 -0
  22. package/dist/core/credential-pool/env-slots.d.ts.map +1 -0
  23. package/dist/core/credential-pool/env-slots.js +37 -0
  24. package/dist/core/credential-pool/env-slots.js.map +1 -0
  25. package/dist/core/credential-pool/failover.d.ts +54 -0
  26. package/dist/core/credential-pool/failover.d.ts.map +1 -0
  27. package/dist/core/credential-pool/failover.js +106 -0
  28. package/dist/core/credential-pool/failover.js.map +1 -0
  29. package/dist/core/credential-pool/rotation-stream.d.ts +43 -0
  30. package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -0
  31. package/dist/core/credential-pool/rotation-stream.js +96 -0
  32. package/dist/core/credential-pool/rotation-stream.js.map +1 -0
  33. package/dist/core/credential-pool/state-store.d.ts +89 -0
  34. package/dist/core/credential-pool/state-store.d.ts.map +1 -0
  35. package/dist/core/credential-pool/state-store.js +166 -0
  36. package/dist/core/credential-pool/state-store.js.map +1 -0
  37. package/dist/core/extensions/builtin/account/index.d.ts +9 -0
  38. package/dist/core/extensions/builtin/account/index.d.ts.map +1 -0
  39. package/dist/core/extensions/builtin/account/index.js +69 -0
  40. package/dist/core/extensions/builtin/account/index.js.map +1 -0
  41. package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
  42. package/dist/core/extensions/builtin/compaction/index.js +67 -0
  43. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  44. package/dist/core/extensions/builtin/compaction/log.d.ts +1 -1
  45. package/dist/core/extensions/builtin/compaction/log.d.ts.map +1 -1
  46. package/dist/core/extensions/builtin/compaction/log.js +1 -0
  47. package/dist/core/extensions/builtin/compaction/log.js.map +1 -1
  48. package/dist/core/extensions/builtin/config-reload/index.js +14 -22
  49. package/dist/core/extensions/builtin/config-reload/index.js.map +1 -1
  50. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts +1 -0
  51. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts.map +1 -1
  52. package/dist/core/extensions/builtin/goal/continuation-recovery.js +2 -0
  53. package/dist/core/extensions/builtin/goal/continuation-recovery.js.map +1 -1
  54. package/dist/core/extensions/builtin/goal/continuation.d.ts +8 -1
  55. package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
  56. package/dist/core/extensions/builtin/goal/continuation.js +15 -0
  57. package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
  58. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js +2 -2
  59. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js.map +1 -1
  60. package/dist/core/extensions/builtin/goal/format.d.ts +6 -1
  61. package/dist/core/extensions/builtin/goal/format.d.ts.map +1 -1
  62. package/dist/core/extensions/builtin/goal/format.js +6 -0
  63. package/dist/core/extensions/builtin/goal/format.js.map +1 -1
  64. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
  65. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +5 -2
  66. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
  67. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  68. package/dist/core/extensions/builtin/goal/monitor-continuation.js +31 -7
  69. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  70. package/dist/core/extensions/builtin/goal/persistence.js +2 -0
  71. package/dist/core/extensions/builtin/goal/persistence.js.map +1 -1
  72. package/dist/core/extensions/builtin/goal/renderers.d.ts +14 -0
  73. package/dist/core/extensions/builtin/goal/renderers.d.ts.map +1 -0
  74. package/dist/core/extensions/builtin/goal/renderers.js +153 -0
  75. package/dist/core/extensions/builtin/goal/renderers.js.map +1 -0
  76. package/dist/core/extensions/builtin/goal/store.d.ts +6 -2
  77. package/dist/core/extensions/builtin/goal/store.d.ts.map +1 -1
  78. package/dist/core/extensions/builtin/goal/store.js +8 -2
  79. package/dist/core/extensions/builtin/goal/store.js.map +1 -1
  80. package/dist/core/extensions/builtin/goal/tool-registration.d.ts.map +1 -1
  81. package/dist/core/extensions/builtin/goal/tool-registration.js +16 -6
  82. package/dist/core/extensions/builtin/goal/tool-registration.js.map +1 -1
  83. package/dist/core/extensions/builtin/goal/types.d.ts +1 -0
  84. package/dist/core/extensions/builtin/goal/types.d.ts.map +1 -1
  85. package/dist/core/extensions/builtin/goal/types.js.map +1 -1
  86. package/dist/core/extensions/builtin/imagegen/index.d.ts.map +1 -1
  87. package/dist/core/extensions/builtin/imagegen/index.js +10 -3
  88. package/dist/core/extensions/builtin/imagegen/index.js.map +1 -1
  89. package/dist/core/extensions/builtin/index.d.ts.map +1 -1
  90. package/dist/core/extensions/builtin/index.js +4 -0
  91. package/dist/core/extensions/builtin/index.js.map +1 -1
  92. package/dist/core/extensions/builtin/todotools/index.js +1 -1
  93. package/dist/core/extensions/builtin/todotools/index.js.map +1 -1
  94. package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts +1 -1
  95. package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts.map +1 -1
  96. package/dist/core/extensions/builtin/todotools/native-todo-mirror.js +1 -1
  97. package/dist/core/extensions/builtin/todotools/native-todo-mirror.js.map +1 -1
  98. package/dist/core/hidden-stdout-log.d.ts +10 -0
  99. package/dist/core/hidden-stdout-log.d.ts.map +1 -1
  100. package/dist/core/hidden-stdout-log.js +36 -5
  101. package/dist/core/hidden-stdout-log.js.map +1 -1
  102. package/dist/core/model-config-schema.d.ts +85 -12
  103. package/dist/core/model-config-schema.d.ts.map +1 -1
  104. package/dist/core/model-config-schema.js +25 -0
  105. package/dist/core/model-config-schema.js.map +1 -1
  106. package/dist/core/model-runtime.d.ts +34 -1
  107. package/dist/core/model-runtime.d.ts.map +1 -1
  108. package/dist/core/model-runtime.js +98 -5
  109. package/dist/core/model-runtime.js.map +1 -1
  110. package/dist/core/tools/output-accumulator.d.ts +2 -0
  111. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  112. package/dist/core/tools/output-accumulator.js +32 -7
  113. package/dist/core/tools/output-accumulator.js.map +1 -1
  114. package/dist/index.d.ts +1 -1
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +1 -1
  117. package/dist/index.js.map +1 -1
  118. package/dist/main.d.ts.map +1 -1
  119. package/dist/main.js +38 -3
  120. package/dist/main.js.map +1 -1
  121. package/dist/modes/app-server/server/account.d.ts.map +1 -1
  122. package/dist/modes/app-server/server/account.js +5 -5
  123. package/dist/modes/app-server/server/account.js.map +1 -1
  124. package/dist/modes/index.d.ts +1 -0
  125. package/dist/modes/index.d.ts.map +1 -1
  126. package/dist/modes/index.js +1 -0
  127. package/dist/modes/index.js.map +1 -1
  128. package/dist/modes/interactive/components/footer.d.ts +11 -3
  129. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/footer.js +31 -1
  131. package/dist/modes/interactive/components/footer.js.map +1 -1
  132. package/dist/modes/interactive/components/tool-execution-fallback.d.ts.map +1 -1
  133. package/dist/modes/interactive/components/tool-execution-fallback.js +82 -1
  134. package/dist/modes/interactive/components/tool-execution-fallback.js.map +1 -1
  135. package/dist/modes/interactive/grok/chrome.d.ts +4 -4
  136. package/dist/modes/interactive/grok/chrome.d.ts.map +1 -1
  137. package/dist/modes/interactive/grok/chrome.js.map +1 -1
  138. package/dist/modes/interactive/grok/footer.d.ts +3 -3
  139. package/dist/modes/interactive/grok/footer.d.ts.map +1 -1
  140. package/dist/modes/interactive/grok/footer.js.map +1 -1
  141. package/dist/modes/interactive/interactive-host-runtime.d.ts +44 -0
  142. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -0
  143. package/dist/modes/interactive/interactive-host-runtime.js +271 -0
  144. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -0
  145. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  146. package/dist/modes/interactive/interactive-mode.js +65 -21
  147. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  148. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  149. package/dist/modes/rpc/connection-handler.js +19 -6
  150. package/dist/modes/rpc/connection-handler.js.map +1 -1
  151. package/dist/modes/rpc/host-ensure.d.ts +41 -0
  152. package/dist/modes/rpc/host-ensure.d.ts.map +1 -0
  153. package/dist/modes/rpc/host-ensure.js +245 -0
  154. package/dist/modes/rpc/host-ensure.js.map +1 -0
  155. package/dist/modes/rpc/host-lifecycle.d.ts +57 -0
  156. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -0
  157. package/dist/modes/rpc/host-lifecycle.js +491 -0
  158. package/dist/modes/rpc/host-lifecycle.js.map +1 -0
  159. package/dist/modes/rpc/host-watchdog.d.ts +33 -0
  160. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -0
  161. package/dist/modes/rpc/host-watchdog.js +142 -0
  162. package/dist/modes/rpc/host-watchdog.js.map +1 -0
  163. package/dist/modes/rpc/multi-session-host.d.ts +7 -1
  164. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  165. package/dist/modes/rpc/multi-session-host.js +206 -32
  166. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  167. package/dist/modes/rpc/rpc-client.d.ts +41 -3
  168. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  169. package/dist/modes/rpc/rpc-client.js +125 -14
  170. package/dist/modes/rpc/rpc-client.js.map +1 -1
  171. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  172. package/dist/modes/rpc/rpc-mode.js +1 -1
  173. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  174. package/dist/modes/rpc/rpc-types.d.ts +6 -2
  175. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  176. package/dist/modes/rpc/rpc-types.js.map +1 -1
  177. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  178. package/dist/modes/rpc/session-command-router.js +24 -6
  179. package/dist/modes/rpc/session-command-router.js.map +1 -1
  180. package/dist/modes/rpc/session-event-writer.d.ts +13 -2
  181. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  182. package/dist/modes/rpc/session-event-writer.js +65 -25
  183. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  184. package/dist/modes/rpc/session-registry.d.ts +9 -0
  185. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  186. package/dist/modes/rpc/session-registry.js +31 -3
  187. package/dist/modes/rpc/session-registry.js.map +1 -1
  188. package/docs/providers.md +48 -0
  189. package/docs/rpc.md +59 -5
  190. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +44 -0
  191. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  192. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +13 -1
  193. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +15 -1
  194. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +711 -1
  195. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +14 -1
  196. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -10
  197. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +9 -3
  198. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +6 -1
  199. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.d.ts.map +1 -1
  200. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +20 -4
  201. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js.map +1 -1
  202. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts +1 -1
  203. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts.map +1 -1
  204. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js.map +1 -1
  205. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts +21 -0
  206. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts.map +1 -0
  207. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js +27 -0
  208. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js.map +1 -0
  209. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts +24 -0
  210. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts.map +1 -1
  211. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js.map +1 -1
  212. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.d.ts.map +1 -1
  213. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +7 -2
  214. package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js.map +1 -1
  215. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  216. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts +1 -1
  217. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts.map +1 -1
  218. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js +46 -14
  219. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js.map +1 -1
  220. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +11 -0
  221. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
  222. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +30 -16
  223. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
  224. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts +2 -1
  225. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts.map +1 -1
  226. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js +2 -1
  227. package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js.map +1 -1
  228. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts +16 -0
  229. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts.map +1 -0
  230. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js +75 -0
  231. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js.map +1 -0
  232. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts +45 -0
  233. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts.map +1 -0
  234. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js +81 -0
  235. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js.map +1 -0
  236. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts +31 -0
  237. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts.map +1 -0
  238. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js +65 -0
  239. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js.map +1 -0
  240. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts +12 -0
  241. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts.map +1 -1
  242. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js +37 -0
  243. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js.map +1 -1
  244. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts +6 -0
  245. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts.map +1 -1
  246. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +32 -6
  247. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js.map +1 -1
  248. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts +3 -2
  249. package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts.map +1 -1
  250. package/node_modules/@earendil-works/pi-ai/dist/auth/types.js.map +1 -1
  251. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts +6 -0
  252. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  253. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +6 -1
  254. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  255. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +75 -0
  256. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  257. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +75 -0
  258. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  259. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  260. package/node_modules/@earendil-works/pi-ai/dist/providers/data/alibaba-token-plan.json +1 -1
  261. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  262. package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  263. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  264. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  265. package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  266. package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  267. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  268. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  269. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  270. package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  271. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  272. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
  273. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  274. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  275. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  276. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  277. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  278. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
  279. package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
  280. package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  281. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  282. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  283. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  284. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
  285. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +4 -0
  286. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
  287. package/node_modules/@earendil-works/pi-ai/package.json +5 -5
  288. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  289. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  290. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +5 -0
  291. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
  292. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +90 -1
  293. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
  294. package/node_modules/@earendil-works/pi-tui/dist/tui.js +1 -1
  295. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  296. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  297. package/package.json +7 -7
@@ -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,
@@ -70,21 +70,21 @@ type EvalPromptExample = {
70
70
  const REUSE_CHAIN_EXAMPLES = [
71
71
  {
72
72
  caption: "First call — set up once",
73
- language: "py",
73
+ language: "js",
74
74
  summary: "Count all TypeScript source files under src/ excluding tests",
75
- code: "from pathlib import Path\nfrom collections import Counter\nfiles = [p for p in Path('src').rglob('*.ts') if 'test' not in p.parts]\nprint(len(files))",
75
+ code: "import { readdir } from 'node:fs/promises'\nimport { extname } from 'node:path'\nconst files = (await readdir('src', { recursive: true })).filter(f => extname(f) === '.ts' && !f.includes('test'))\nprint(files.length)",
76
76
  },
77
77
  {
78
- caption: "Second call — reuse `files`, batch-read in one cell",
79
- language: "py",
80
- summary: "Find which files reference legacyClient so we know what to migrate",
81
- code: "hits = Counter()\nfor p in files:\n hits[p.name] = read(p).count('legacyClient')\ndisplay({k: v for k, v in hits.items() if v})",
78
+ caption: "Second call — reuse `files`, fan out session tools in parallel",
79
+ language: "js",
80
+ summary: "Grep legacyClient per directory in one cell",
81
+ code: "const dirs = [...new Set(files.map(f => f.split('/')[0]))]\nconst hits = await Promise.all(dirs.map(d => tool.grep({ pattern: 'legacyClient', path: d })))\ndisplay(hits.map(h => h.matches?.length ?? 0))",
82
82
  },
83
83
  {
84
- caption: "Third call reuse results, fan out session tools in parallel",
84
+ caption: "JS kernel is busy with a detached cell continue in py",
85
85
  language: "py",
86
- summary: "Confirm exact callsite lines in each directory to plan the refactor",
87
- code: "dirs = ['src/core', 'src/tools']\ndisplay(parallel([lambda d=d: tool.grep({'pattern': 'legacyClient', 'path': d}) for d in dirs]))",
86
+ summary: "Aggregate legacyClient hits while JS is busy",
87
+ code: "from pathlib import Path\nprint(sum('legacyClient' in read(p) for p in Path('src').rglob('*.ts')))",
88
88
  },
89
89
  ] as const satisfies readonly EvalPromptExample[];
90
90
 
@@ -129,7 +129,7 @@ Fields:
129
129
  - \`reset\` (optional) — wipe this language's kernel first.{{#ifAll py js}} Per-language: a \`py\` reset never touches the JS VM.{{/ifAll}}
130
130
  - \`action\` (optional) — defaults to \`"run"\`. A detached cell returns its id: use \`eval({ action: "peek", cell_id })\` for buffered output/state or \`eval({ action: "stop", cell_id })\` to cancel it.
131
131
 
132
- A detached cell keeps its language kernel busy while it finishes. Do not re-run a detached cell: the same-language busy error names its cell id and output tail; another language can continue. Completion arrives as one notification with the final value/error and buffered output. Stopping a cell interrupts its kernel; the stop result states whether kernel state survived or the kernel was restarted and its variables lost.
132
+ A detached cell keeps its language kernel busy while it finishes; another language can continue. Do not re-run a detached cell: the same-language busy error names its cell id and output tail. Completion arrives as one notification with the final value/error and buffered output. Stopping a cell interrupts its kernel; the stop result states whether kernel state survived or the kernel was restarted and its variables lost.
133
133
 
134
134
  {{#if py}}Live event loop: use top-level \`await\` directly; \`asyncio.run(…)\` raises "cannot be called from a running event loop".{{/if}}
135
135
  {{#if js}}JS runs under Node.js worker: top-level \`await\`/\`return\` work; \`fetch\`/\`Buffer\` available.{{/if}}
@@ -5,7 +5,7 @@ import type {
5
5
  EvalDetachedCellState,
6
6
  } from "./detached-cell-manager.ts";
7
7
  import { interruptionStateNote } from "./interrupt-note.ts";
8
- import type { EvalCellResult, EvalControlInput, EvalToolDetails, EvalToolInput } from "./types.ts";
8
+ import type { EvalCellResult, EvalControlInput, EvalLanguage, EvalToolDetails, EvalToolInput } from "./types.ts";
9
9
 
10
10
  export async function executeEvalControl(
11
11
  cellManager: EvalDetachedCellManager,
@@ -101,10 +101,16 @@ export function resultForDetachedState(
101
101
  };
102
102
  }
103
103
 
104
- export function detachedKernelBusyError(snapshot: EvalDetachedCellSnapshot): Error {
104
+ export function detachedKernelBusyError(
105
+ snapshot: EvalDetachedCellSnapshot,
106
+ idleLanguages: readonly EvalLanguage[] = [],
107
+ ): Error {
105
108
  const tail = snapshot.outputTail.length === 0 ? "(no output yet)" : snapshot.outputTail;
109
+ const peek = `eval({ action: "peek", cell_id: "${snapshot.cellId}" })`;
110
+ const idleHint =
111
+ idleLanguages.length === 0 ? "" : ` or continue this step in an idle kernel: ${idleLanguages.join(", ")}`;
106
112
  return new Error(
107
- `The ${snapshot.language} eval kernel is busy running detached cell ${snapshot.cellId}. Do not re-run it; use eval({ action: "peek", cell_id: "${snapshot.cellId}" }). Current output tail:\n${tail}`,
113
+ `The ${snapshot.language} eval kernel is busy running detached cell ${snapshot.cellId} - peek with ${peek}${idleHint}. Do not re-run the busy cell. Current output tail:\n${tail}`,
108
114
  );
109
115
  }
110
116
 
@@ -67,7 +67,12 @@ export function createEvalTool(options: CreateEvalToolOptions): ToolDefinition<E
67
67
  `Unsupported eval language "${request.language}". Enabled languages: ${languages.join(", ")}`,
68
68
  );
69
69
  const busy = cellManager.busyFor(request.language);
70
- if (busy !== undefined) throw detachedKernelBusyError(busy);
70
+ if (busy !== undefined) {
71
+ const idleLanguages = languages.filter(
72
+ (language) => language !== request.language && cellManager.busyFor(language) === undefined,
73
+ );
74
+ throw detachedKernelBusyError(busy, idleLanguages);
75
+ }
71
76
  options.executionTracker?.assertEvalExecutionAllowed();
72
77
  const lifecycleController = new AbortController();
73
78
  const combinedSignal = signal
@@ -1 +1 @@
1
- {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,gBAAgB,EAAa,MAAM,aAAa,CAAC;AAa/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAa9D,QAAA,MAAM,UAAU;;;;;;EASf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAUtD,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAqCD,wBAAgB,cAAc,CAAC,QAAQ,SAAS,oBAAoB,GAAG,oBAAoB,KAAK,gBAAgB,CAC/G,QAAQ,EACR,OAAO,UAAU,EACjB,eAAe,GAAG,SAAS,CAC3B,CA8CA"}
1
+ {"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,gBAAgB,EAAa,MAAM,aAAa,CAAC;AAc/D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAa9D,QAAA,MAAM,UAAU;;;;;;EASf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAUtD,MAAM,WAAW,eAAe;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAqCD,wBAAgB,cAAc,CAAC,QAAQ,SAAS,oBAAoB,GAAG,oBAAoB,KAAK,gBAAgB,CAC/G,QAAQ,EACR,OAAO,UAAU,EACjB,eAAe,GAAG,SAAS,CAC3B,CAiEA"}
@@ -2,6 +2,7 @@ import { Type } from "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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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,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;Q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ED,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"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-context.js","sourceRoot":"","sources":["../../../src/harness/tools/tool-context.ts"],"names":[],"mappings":"","sourcesContent":["import type { ExecutionEnv } from \"../types.ts\";\n\n/** Filesystem and shell context required by the built-in execution tools. */\nexport interface ExecutionToolContext {\n\tenv: ExecutionEnv;\n}\n"]}
1
+ {"version":3,"file":"tool-context.js","sourceRoot":"","sources":["../../../src/harness/tools/tool-context.ts"],"names":[],"mappings":"","sourcesContent":["import type { ExecutionEnv } from \"../types.ts\";\n\n/** Mutation that triggered a `postMutate` hook run. */\nexport interface PostMutateContext {\n\t/** Tool that performed the mutation. */\n\ttool: \"write\" | \"edit\";\n\t/** Absolute path of the file that was just written. */\n\tpath: string;\n\t/** Abort signal of the originating tool call, when the caller supplied one. */\n\tsignal?: AbortSignal;\n}\n\n/** Outcome reported by a `postMutate` hook. */\nexport interface PostMutateResult {\n\t/** Whether the hook itself rewrote the file after the tool's own write landed. */\n\tchanged: boolean;\n\t/** Single-line note appended to the tool result text. */\n\tnote?: string;\n}\n\n/** Hook invoked inside the file mutation queue, immediately after a tool write succeeds. */\nexport type PostMutateHook = (input: PostMutateContext) => Promise<PostMutateResult>;\n\n/** Filesystem and shell context required by the built-in execution tools. */\nexport interface ExecutionToolContext {\n\tenv: ExecutionEnv;\n\t/**\n\t * Optional post-write hook (formatting, codegen, normalization). It runs inside the same\n\t * mutation-queue slot as the write it follows, so the file cannot be mutated in between.\n\t * A rejecting hook never discards the landed write; the tool appends a warning note instead.\n\t */\n\tpostMutate?: PostMutateHook;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAIpD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD,wBAAgB,eAAe,CAAC,QAAQ,SAAS,oBAAoB,GAAG,oBAAoB,KAAK,gBAAgB,CAChH,QAAQ,EACR,OAAO,WAAW,EAClB,SAAS,CACT,CAoBA"}
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAKpD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD,wBAAgB,eAAe,CAAC,QAAQ,SAAS,oBAAoB,GAAG,oBAAoB,KAAK,gBAAgB,CAChH,QAAQ,EACR,OAAO,WAAW,EAClB,SAAS,CACT,CAuBA"}
@@ -2,6 +2,7 @@ import { Type } from "typebox";
2
2
  import { getOrThrow } from "../types.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 writeSchema = Type.Object({
6
7
  path: Type.String({ description: "Path to the file to write (relative or absolute)" }),
7
8
  content: Type.String({ description: "Content to write to the file" }),
@@ -12,7 +13,7 @@ export function createWriteTool() {
12
13
  label: "write",
13
14
  description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
14
15
  parameters: writeSchema,
15
- async execute(_toolCallId, { path, content }, signal, _onUpdate, { env }) {
16
+ async execute(_toolCallId, { path, content }, signal, _onUpdate, { env, postMutate }) {
16
17
  const absolutePath = await resolveToolPath(env, path, signal);
17
18
  return withFileMutationQueue(env, absolutePath, async () => {
18
19
  if (signal?.aborted)
@@ -20,8 +21,12 @@ export function createWriteTool() {
20
21
  getOrThrow(await env.writeFile(absolutePath, content, signal));
21
22
  if (signal?.aborted)
22
23
  throw new Error("Operation aborted");
24
+ const outcome = await runPostMutate(postMutate, { tool: "write", path: absolutePath, signal });
25
+ if (signal?.aborted)
26
+ throw new Error("Operation aborted");
27
+ const text = appendPostMutateNote(`Successfully wrote ${content.length} bytes to ${path}`, outcome.note);
23
28
  return {
24
- content: [{ type: "text", text: `Successfully wrote ${content.length} bytes to ${path}` }],
29
+ content: [{ type: "text", text }],
25
30
  details: undefined,
26
31
  };
27
32
  });
@@ -1 +1 @@
1
- {"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/harness/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGlD,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC;IAC/B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,kDAAkD,EAAE,CAAC;IACtF,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,8BAA8B,EAAE,CAAC;CACrE,CAAC,CAAC;AAIH,MAAM,UAAU,eAAe;IAK9B,OAAO;QACN,IAAI,EAAE,OAAO;QACb,KAAK,EAAE,OAAO;QACd,WAAW,EACV,iIAAiI;QAClI,UAAU,EAAE,WAAW;QACvB,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE;YACvE,MAAM,YAAY,GAAG,MAAM,eAAe,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;YAC9D,OAAO,qBAAqB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,IAAI,EAAE;gBAC1D,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAC1D,UAAU,CAAC,MAAM,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;gBAC/D,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAC1D,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,sBAAsB,OAAO,CAAC,MAAM,aAAa,IAAI,EAAE,EAAE,CAAC;oBAC1F,OAAO,EAAE,SAAS;iBAClB,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { AgentHarnessTool } from \"../types.ts\";\nimport { getOrThrow } from \"../types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToolPath } from \"./path-utils.ts\";\nimport type { ExecutionToolContext } from \"./tool-context.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport function createWriteTool<TContext extends ExecutionToolContext = ExecutionToolContext>(): AgentHarnessTool<\n\tTContext,\n\ttypeof writeSchema,\n\tundefined\n> {\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tparameters: writeSchema,\n\t\tasync execute(_toolCallId, { path, content }, signal, _onUpdate, { env }) {\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\tgetOrThrow(await env.writeFile(absolutePath, content, signal));\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t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,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAC1D,MAAM,OAAO,GAAG,MAAM,aAAa,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC;gBAC/F,IAAI,MAAM,EAAE,OAAO;oBAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;gBAC1D,MAAM,IAAI,GAAG,oBAAoB,CAAC,sBAAsB,OAAO,CAAC,MAAM,aAAa,IAAI,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;gBACzG,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;oBACjC,OAAO,EAAE,SAAS;iBAClB,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { AgentHarnessTool } from \"../types.ts\";\nimport { getOrThrow } from \"../types.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 writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\nexport function createWriteTool<TContext extends ExecutionToolContext = ExecutionToolContext>(): AgentHarnessTool<\n\tTContext,\n\ttypeof writeSchema,\n\tundefined\n> {\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tparameters: writeSchema,\n\t\tasync execute(_toolCallId, { path, content }, signal, _onUpdate, { env, postMutate }) {\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\tgetOrThrow(await env.writeFile(absolutePath, content, signal));\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tconst outcome = await runPostMutate(postMutate, { tool: \"write\", path: absolutePath, signal });\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tconst text = appendPostMutateNote(`Successfully wrote ${content.length} bytes to ${path}`, outcome.note);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-agent-core",
3
- "version": "2026.8.26",
3
+ "version": "2026.8.28",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -35,8 +35,8 @@
35
35
  "prepublishOnly": "npm run build"
36
36
  },
37
37
  "dependencies": {
38
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.26",
39
- "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.8.26",
38
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.8.28",
39
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.8.28",
40
40
  "diff": "9.0.0",
41
41
  "ignore": "7.0.6",
42
42
  "typebox": "1.3.18",
@@ -1,3 +1,3 @@
1
- /** Repairs Anthropic client tool_use/tool_result adjacency without mutating the input payload. */
1
+ /** Repairs Anthropic client tool_use/tool_result adjacency and duplicate tool_use ids without mutating the input payload. */
2
2
  export declare function sanitizeAnthropicToolPairs(payload: unknown): unknown;
3
3
  //# sourceMappingURL=anthropic-tool-pairs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-tool-pairs.d.ts","sourceRoot":"","sources":["../../src/api/anthropic-tool-pairs.ts"],"names":[],"mappings":"AAsGA,kGAAkG;AAClG,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAoDpE"}
1
+ {"version":3,"file":"anthropic-tool-pairs.d.ts","sourceRoot":"","sources":["../../src/api/anthropic-tool-pairs.ts"],"names":[],"mappings":"AA2IA,6HAA6H;AAC7H,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAuDpE"}
@@ -14,6 +14,9 @@ function isToolResultBlock(block) {
14
14
  return block.type === "tool_result";
15
15
  }
16
16
  const SYNTHETIC_OUTPUT = "Tool output unavailable (interrupted before result)";
17
+ function cloneWith(block, patch) {
18
+ return { ...block, ...patch };
19
+ }
17
20
  function isMessageWithArrayContent(value, role) {
18
21
  if (!isObject(value) || value.role !== role || !Array.isArray(value.content))
19
22
  return false;
@@ -26,16 +29,36 @@ function isMessageWithArrayContent(value, role) {
26
29
  function isUserMessageWithStringContent(value) {
27
30
  return isObject(value) && value.role === "user" && typeof value.content === "string";
28
31
  }
29
- function getToolUseIds(message) {
30
- const ids = [];
31
- const seen = new Set();
32
+ function dedupeAssistantToolUses(message, usedIds) {
33
+ const content = [];
34
+ const expectedIds = [];
35
+ const remapQueues = new Map();
36
+ let changed = false;
32
37
  for (const block of message.content) {
33
- if (!isToolUseBlock(block) || block.id.length === 0 || seen.has(block.id))
38
+ if (!isToolUseBlock(block) || block.id.length === 0) {
39
+ content.push(block);
34
40
  continue;
35
- seen.add(block.id);
36
- ids.push(block.id);
41
+ }
42
+ let finalId = block.id;
43
+ if (usedIds.has(finalId)) {
44
+ let suffix = 2;
45
+ while (usedIds.has(`${block.id}__dedup${suffix}`))
46
+ suffix += 1;
47
+ finalId = `${block.id}__dedup${suffix}`;
48
+ changed = true;
49
+ }
50
+ usedIds.add(finalId);
51
+ expectedIds.push(finalId);
52
+ const queue = remapQueues.get(block.id);
53
+ if (queue === undefined)
54
+ remapQueues.set(block.id, [finalId]);
55
+ else
56
+ queue.push(finalId);
57
+ content.push(finalId === block.id ? block : cloneWith(block, { id: finalId }));
37
58
  }
38
- return ids;
59
+ if (!changed)
60
+ return { message, changed: false, expectedIds, remapQueues };
61
+ return { message: { ...message, content }, changed: true, expectedIds, remapQueues };
39
62
  }
40
63
  function syntheticToolResult(toolUseId) {
41
64
  return {
@@ -48,7 +71,7 @@ function syntheticToolResult(toolUseId) {
48
71
  function sameBlocks(left, right) {
49
72
  return left.length === right.length && left.every((block, index) => block === right[index]);
50
73
  }
51
- function repairFollowingUserMessage(message, expectedIds) {
74
+ function repairFollowingUserMessage(message, expectedIds, remapQueues) {
52
75
  const expected = new Set(expectedIds);
53
76
  const found = new Set();
54
77
  const results = [];
@@ -58,11 +81,17 @@ function repairFollowingUserMessage(message, expectedIds) {
58
81
  ordinary.push(block);
59
82
  continue;
60
83
  }
61
- const id = block.tool_use_id;
84
+ const rawId = block.tool_use_id;
85
+ let id = rawId;
86
+ if (typeof rawId === "string") {
87
+ const queue = remapQueues.get(rawId);
88
+ if (queue !== undefined && queue.length > 0)
89
+ id = queue.shift();
90
+ }
62
91
  if (typeof id !== "string" || !expected.has(id) || found.has(id))
63
92
  continue;
64
93
  found.add(id);
65
- results.push(block);
94
+ results.push(id === rawId ? block : cloneWith(block, { tool_use_id: id }));
66
95
  }
67
96
  for (const id of expectedIds) {
68
97
  if (!found.has(id))
@@ -81,22 +110,25 @@ function removeOrphanResults(message) {
81
110
  return { changed: true };
82
111
  return { message: { ...message, content }, changed: true };
83
112
  }
84
- /** Repairs Anthropic client tool_use/tool_result adjacency without mutating the input payload. */
113
+ /** Repairs Anthropic client tool_use/tool_result adjacency and duplicate tool_use ids without mutating the input payload. */
85
114
  export function sanitizeAnthropicToolPairs(payload) {
86
115
  if (!hasMessagesArray(payload))
87
116
  return payload;
88
117
  let changed = false;
118
+ const usedToolUseIds = new Set();
89
119
  const sanitizedMessages = [];
90
120
  for (let index = 0; index < payload.messages.length; index++) {
91
121
  const unknownMessage = payload.messages[index];
92
122
  if (isMessageWithArrayContent(unknownMessage, "assistant")) {
93
- sanitizedMessages.push(unknownMessage);
94
- const expectedIds = getToolUseIds(unknownMessage);
123
+ const deduped = dedupeAssistantToolUses(unknownMessage, usedToolUseIds);
124
+ sanitizedMessages.push(deduped.message);
125
+ changed ||= deduped.changed;
126
+ const expectedIds = deduped.expectedIds;
95
127
  if (expectedIds.length === 0)
96
128
  continue;
97
129
  const nextMessage = payload.messages[index + 1];
98
130
  if (isMessageWithArrayContent(nextMessage, "user")) {
99
- const repaired = repairFollowingUserMessage(nextMessage, expectedIds);
131
+ const repaired = repairFollowingUserMessage(nextMessage, expectedIds, deduped.remapQueues);
100
132
  sanitizedMessages.push(repaired.message);
101
133
  changed ||= repaired.changed;
102
134
  index++;