@code-yeongyu/senpi 2026.8.26 → 2026.8.27

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 (231) hide show
  1. package/CHANGELOG.md +55 -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-pool/classify.d.ts +42 -0
  14. package/dist/core/credential-pool/classify.d.ts.map +1 -0
  15. package/dist/core/credential-pool/classify.js +75 -0
  16. package/dist/core/credential-pool/classify.js.map +1 -0
  17. package/dist/core/credential-pool/env-slots.d.ts +22 -0
  18. package/dist/core/credential-pool/env-slots.d.ts.map +1 -0
  19. package/dist/core/credential-pool/env-slots.js +37 -0
  20. package/dist/core/credential-pool/env-slots.js.map +1 -0
  21. package/dist/core/credential-pool/failover.d.ts +54 -0
  22. package/dist/core/credential-pool/failover.d.ts.map +1 -0
  23. package/dist/core/credential-pool/failover.js +106 -0
  24. package/dist/core/credential-pool/failover.js.map +1 -0
  25. package/dist/core/credential-pool/rotation-stream.d.ts +43 -0
  26. package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -0
  27. package/dist/core/credential-pool/rotation-stream.js +96 -0
  28. package/dist/core/credential-pool/rotation-stream.js.map +1 -0
  29. package/dist/core/credential-pool/state-store.d.ts +89 -0
  30. package/dist/core/credential-pool/state-store.d.ts.map +1 -0
  31. package/dist/core/credential-pool/state-store.js +166 -0
  32. package/dist/core/credential-pool/state-store.js.map +1 -0
  33. package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
  34. package/dist/core/extensions/builtin/compaction/index.js +67 -0
  35. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  36. package/dist/core/extensions/builtin/compaction/log.d.ts +1 -1
  37. package/dist/core/extensions/builtin/compaction/log.d.ts.map +1 -1
  38. package/dist/core/extensions/builtin/compaction/log.js +1 -0
  39. package/dist/core/extensions/builtin/compaction/log.js.map +1 -1
  40. package/dist/core/extensions/builtin/config-reload/index.js +14 -22
  41. package/dist/core/extensions/builtin/config-reload/index.js.map +1 -1
  42. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts +1 -0
  43. package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts.map +1 -1
  44. package/dist/core/extensions/builtin/goal/continuation-recovery.js +2 -0
  45. package/dist/core/extensions/builtin/goal/continuation-recovery.js.map +1 -1
  46. package/dist/core/extensions/builtin/goal/continuation.d.ts +8 -1
  47. package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
  48. package/dist/core/extensions/builtin/goal/continuation.js +15 -0
  49. package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
  50. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js +2 -2
  51. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js.map +1 -1
  52. package/dist/core/extensions/builtin/goal/format.d.ts +6 -1
  53. package/dist/core/extensions/builtin/goal/format.d.ts.map +1 -1
  54. package/dist/core/extensions/builtin/goal/format.js +6 -0
  55. package/dist/core/extensions/builtin/goal/format.js.map +1 -1
  56. package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
  57. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +5 -2
  58. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
  59. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  60. package/dist/core/extensions/builtin/goal/monitor-continuation.js +31 -7
  61. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  62. package/dist/core/extensions/builtin/goal/persistence.js +2 -0
  63. package/dist/core/extensions/builtin/goal/persistence.js.map +1 -1
  64. package/dist/core/extensions/builtin/goal/renderers.d.ts +14 -0
  65. package/dist/core/extensions/builtin/goal/renderers.d.ts.map +1 -0
  66. package/dist/core/extensions/builtin/goal/renderers.js +153 -0
  67. package/dist/core/extensions/builtin/goal/renderers.js.map +1 -0
  68. package/dist/core/extensions/builtin/goal/store.d.ts +6 -2
  69. package/dist/core/extensions/builtin/goal/store.d.ts.map +1 -1
  70. package/dist/core/extensions/builtin/goal/store.js +8 -2
  71. package/dist/core/extensions/builtin/goal/store.js.map +1 -1
  72. package/dist/core/extensions/builtin/goal/tool-registration.d.ts.map +1 -1
  73. package/dist/core/extensions/builtin/goal/tool-registration.js +16 -6
  74. package/dist/core/extensions/builtin/goal/tool-registration.js.map +1 -1
  75. package/dist/core/extensions/builtin/goal/types.d.ts +1 -0
  76. package/dist/core/extensions/builtin/goal/types.d.ts.map +1 -1
  77. package/dist/core/extensions/builtin/goal/types.js.map +1 -1
  78. package/dist/core/extensions/builtin/todotools/index.js +1 -1
  79. package/dist/core/extensions/builtin/todotools/index.js.map +1 -1
  80. package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts +1 -1
  81. package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts.map +1 -1
  82. package/dist/core/extensions/builtin/todotools/native-todo-mirror.js +1 -1
  83. package/dist/core/extensions/builtin/todotools/native-todo-mirror.js.map +1 -1
  84. package/dist/core/hidden-stdout-log.d.ts +10 -0
  85. package/dist/core/hidden-stdout-log.d.ts.map +1 -1
  86. package/dist/core/hidden-stdout-log.js +36 -5
  87. package/dist/core/hidden-stdout-log.js.map +1 -1
  88. package/dist/core/model-config-schema.d.ts +85 -12
  89. package/dist/core/model-config-schema.d.ts.map +1 -1
  90. package/dist/core/model-config-schema.js +25 -0
  91. package/dist/core/model-config-schema.js.map +1 -1
  92. package/dist/core/model-runtime.d.ts +34 -1
  93. package/dist/core/model-runtime.d.ts.map +1 -1
  94. package/dist/core/model-runtime.js +98 -5
  95. package/dist/core/model-runtime.js.map +1 -1
  96. package/dist/core/tools/output-accumulator.d.ts +2 -0
  97. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  98. package/dist/core/tools/output-accumulator.js +32 -7
  99. package/dist/core/tools/output-accumulator.js.map +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/main.d.ts.map +1 -1
  105. package/dist/main.js +26 -2
  106. package/dist/main.js.map +1 -1
  107. package/dist/modes/index.d.ts +1 -0
  108. package/dist/modes/index.d.ts.map +1 -1
  109. package/dist/modes/index.js +1 -0
  110. package/dist/modes/index.js.map +1 -1
  111. package/dist/modes/interactive/components/tool-execution-fallback.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/tool-execution-fallback.js +82 -1
  113. package/dist/modes/interactive/components/tool-execution-fallback.js.map +1 -1
  114. package/dist/modes/interactive/interactive-host-runtime.d.ts +29 -0
  115. package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -0
  116. package/dist/modes/interactive/interactive-host-runtime.js +244 -0
  117. package/dist/modes/interactive/interactive-host-runtime.js.map +1 -0
  118. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  119. package/dist/modes/interactive/interactive-mode.js +46 -8
  120. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  121. package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
  122. package/dist/modes/rpc/connection-handler.js +7 -1
  123. package/dist/modes/rpc/connection-handler.js.map +1 -1
  124. package/dist/modes/rpc/host-ensure.d.ts +41 -0
  125. package/dist/modes/rpc/host-ensure.d.ts.map +1 -0
  126. package/dist/modes/rpc/host-ensure.js +245 -0
  127. package/dist/modes/rpc/host-ensure.js.map +1 -0
  128. package/dist/modes/rpc/host-lifecycle.d.ts +57 -0
  129. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -0
  130. package/dist/modes/rpc/host-lifecycle.js +491 -0
  131. package/dist/modes/rpc/host-lifecycle.js.map +1 -0
  132. package/dist/modes/rpc/host-watchdog.d.ts +33 -0
  133. package/dist/modes/rpc/host-watchdog.d.ts.map +1 -0
  134. package/dist/modes/rpc/host-watchdog.js +142 -0
  135. package/dist/modes/rpc/host-watchdog.js.map +1 -0
  136. package/dist/modes/rpc/multi-session-host.d.ts +7 -1
  137. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  138. package/dist/modes/rpc/multi-session-host.js +206 -32
  139. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  140. package/dist/modes/rpc/rpc-client.d.ts +25 -0
  141. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  142. package/dist/modes/rpc/rpc-client.js +83 -10
  143. package/dist/modes/rpc/rpc-client.js.map +1 -1
  144. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  145. package/dist/modes/rpc/rpc-mode.js +1 -1
  146. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  147. package/dist/modes/rpc/rpc-types.d.ts +2 -1
  148. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  149. package/dist/modes/rpc/rpc-types.js.map +1 -1
  150. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  151. package/dist/modes/rpc/session-command-router.js +12 -2
  152. package/dist/modes/rpc/session-command-router.js.map +1 -1
  153. package/dist/modes/rpc/session-event-writer.d.ts +13 -2
  154. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  155. package/dist/modes/rpc/session-event-writer.js +65 -25
  156. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  157. package/docs/rpc.md +53 -1
  158. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +30 -0
  159. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  160. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +711 -1
  161. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -10
  162. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +9 -3
  163. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +6 -1
  164. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  165. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts +1 -1
  166. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts.map +1 -1
  167. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js +46 -14
  168. package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js.map +1 -1
  169. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +11 -0
  170. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
  171. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +30 -16
  172. package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
  173. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts +16 -0
  174. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts.map +1 -0
  175. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js +75 -0
  176. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js.map +1 -0
  177. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts +45 -0
  178. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts.map +1 -0
  179. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js +81 -0
  180. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js.map +1 -0
  181. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts +31 -0
  182. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts.map +1 -0
  183. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js +65 -0
  184. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js.map +1 -0
  185. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts +12 -0
  186. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts.map +1 -1
  187. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js +37 -0
  188. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js.map +1 -1
  189. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts +6 -0
  190. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts.map +1 -1
  191. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +32 -6
  192. package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js.map +1 -1
  193. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts +6 -0
  194. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  195. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +6 -1
  196. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  197. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +75 -0
  198. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
  199. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +75 -0
  200. package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
  201. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  202. package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  203. package/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  204. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  205. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  206. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  207. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
  208. package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
  209. package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  210. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  211. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  212. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  213. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  214. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  215. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  216. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  217. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  218. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
  219. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +4 -0
  220. package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
  221. package/node_modules/@earendil-works/pi-ai/package.json +5 -5
  222. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  223. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  224. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +5 -0
  225. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
  226. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +90 -1
  227. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
  228. package/node_modules/@earendil-works/pi-tui/dist/tui.js +1 -1
  229. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  230. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  231. package/package.json +7 -7
@@ -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,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-agent-core",
3
- "version": "2026.8.26",
3
+ "version": "2026.8.27",
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.27",
39
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.8.27",
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++;
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-tool-pairs.js","sourceRoot":"","sources":["../../src/api/anthropic-tool-pairs.ts"],"names":[],"mappings":"AAEA,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACpD,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACvC,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;AACzD,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAc;IAC1C,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AAC1D,CAAC;AAED,SAAS,cAAc,CAAC,KAAwB;IAC/C,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,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AG,mBAAmB,CAAC,cAAc,CAAC,CAAC;YACrD,IAAI,QAAQ,CAAC,OAAO;gBAAE,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YAC/D,OAAO,KAAK,QAAQ,CAAC,OAAO,CAAC;YAC7B,SAAS;QACV,CAAC;QAED,iBAAiB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7B,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { ContentBlockParam, MessageParam } from \"@anthropic-ai/sdk/resources/messages.js\";\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction hasMessagesArray(value: unknown): value is { messages: unknown[] } {\n\treturn isObject(value) && Array.isArray(value.messages);\n}\n\nfunction isContentBlockParam(value: unknown): value is ContentBlockParam {\n\treturn isObject(value) && typeof value.type === \"string\";\n}\n\nfunction isToolUseBlock(block: ContentBlockParam): block is Extract<ContentBlockParam, { type: \"tool_use\" }> {\n\treturn block.type === \"tool_use\" && \"id\" in block && typeof block.id === \"string\";\n}\n\nfunction isToolResultBlock(block: ContentBlockParam): block is Extract<ContentBlockParam, { type: \"tool_result\" }> {\n\treturn block.type === \"tool_result\";\n}\n\nconst SYNTHETIC_OUTPUT = \"Tool output unavailable (interrupted before result)\";\n\nfunction isMessageWithArrayContent<Role extends MessageParam[\"role\"]>(\n\tvalue: unknown,\n\trole: Role,\n): value is MessageParam & { role: Role; content: ContentBlockParam[] } {\n\tif (!isObject(value) || value.role !== role || !Array.isArray(value.content)) return false;\n\tfor (const block of value.content) {\n\t\tif (!isContentBlockParam(block)) return false;\n\t}\n\treturn true;\n}\n\nfunction isUserMessageWithStringContent(value: unknown): value is MessageParam & { role: \"user\"; content: string } {\n\treturn isObject(value) && value.role === \"user\" && typeof value.content === \"string\";\n}\n\nfunction getToolUseIds(message: MessageParam & { content: ContentBlockParam[] }): string[] {\n\tconst ids: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const block of message.content) {\n\t\tif (!isToolUseBlock(block) || block.id.length === 0 || seen.has(block.id)) continue;\n\t\tseen.add(block.id);\n\t\tids.push(block.id);\n\t}\n\treturn ids;\n}\n\nfunction syntheticToolResult(toolUseId: string): Extract<ContentBlockParam, { type: \"tool_result\" }> {\n\treturn {\n\t\ttype: \"tool_result\",\n\t\ttool_use_id: toolUseId,\n\t\tcontent: SYNTHETIC_OUTPUT,\n\t\tis_error: true,\n\t};\n}\n\nfunction sameBlocks(left: ContentBlockParam[], right: ContentBlockParam[]): boolean {\n\treturn left.length === right.length && left.every((block, index) => block === right[index]);\n}\n\nfunction repairFollowingUserMessage(\n\tmessage: MessageParam & { role: \"user\"; content: ContentBlockParam[] },\n\texpectedIds: string[],\n): { message: MessageParam; changed: boolean } {\n\tconst expected = new Set(expectedIds);\n\tconst found = new Set<string>();\n\tconst results: ContentBlockParam[] = [];\n\tconst ordinary: ContentBlockParam[] = [];\n\n\tfor (const block of message.content) {\n\t\tif (!isToolResultBlock(block)) {\n\t\t\tordinary.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tconst id = block.tool_use_id;\n\t\tif (typeof id !== \"string\" || !expected.has(id) || found.has(id)) continue;\n\t\tfound.add(id);\n\t\tresults.push(block);\n\t}\n\n\tfor (const id of expectedIds) {\n\t\tif (!found.has(id)) results.push(syntheticToolResult(id));\n\t}\n\n\tconst content = [...results, ...ordinary];\n\tif (sameBlocks(content, message.content)) return { message, changed: false };\n\treturn { message: { ...message, content }, changed: true };\n}\n\nfunction removeOrphanResults(message: MessageParam & { role: \"user\"; content: ContentBlockParam[] }): {\n\tmessage?: MessageParam;\n\tchanged: boolean;\n} {\n\tconst content = message.content.filter((block) => !isToolResultBlock(block));\n\tif (content.length === message.content.length) return { message, changed: false };\n\tif (content.length === 0) return { changed: true };\n\treturn { message: { ...message, content }, changed: true };\n}\n\n/** Repairs Anthropic client tool_use/tool_result adjacency without mutating the input payload. */\nexport function sanitizeAnthropicToolPairs(payload: unknown): unknown {\n\tif (!hasMessagesArray(payload)) return payload;\n\n\tlet changed = false;\n\tconst sanitizedMessages: unknown[] = [];\n\n\tfor (let index = 0; index < payload.messages.length; index++) {\n\t\tconst unknownMessage = payload.messages[index];\n\t\tif (isMessageWithArrayContent(unknownMessage, \"assistant\")) {\n\t\t\tsanitizedMessages.push(unknownMessage);\n\t\t\tconst expectedIds = getToolUseIds(unknownMessage);\n\t\t\tif (expectedIds.length === 0) continue;\n\n\t\t\tconst nextMessage = payload.messages[index + 1];\n\t\t\tif (isMessageWithArrayContent(nextMessage, \"user\")) {\n\t\t\t\tconst repaired = repairFollowingUserMessage(nextMessage, expectedIds);\n\t\t\t\tsanitizedMessages.push(repaired.message);\n\t\t\t\tchanged ||= repaired.changed;\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isUserMessageWithStringContent(nextMessage)) {\n\t\t\t\tsanitizedMessages.push({\n\t\t\t\t\t...nextMessage,\n\t\t\t\t\tcontent: [...expectedIds.map(syntheticToolResult), { type: \"text\", text: nextMessage.content }],\n\t\t\t\t});\n\t\t\t\tchanged = true;\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsanitizedMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: expectedIds.map(syntheticToolResult),\n\t\t\t});\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isMessageWithArrayContent(unknownMessage, \"user\")) {\n\t\t\tconst repaired = removeOrphanResults(unknownMessage);\n\t\t\tif (repaired.message) sanitizedMessages.push(repaired.message);\n\t\t\tchanged ||= repaired.changed;\n\t\t\tcontinue;\n\t\t}\n\n\t\tsanitizedMessages.push(unknownMessage);\n\t}\n\n\tif (!changed) return payload;\n\treturn { ...payload, messages: s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QAAQ,CAAC,OAAO;gBAAE,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YAC/D,OAAO,KAAK,QAAQ,CAAC,OAAO,CAAC;YAC7B,SAAS;QACV,CAAC;QAED,iBAAiB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7B,OAAO,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { ContentBlockParam, MessageParam } from \"@anthropic-ai/sdk/resources/messages.js\";\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction hasMessagesArray(value: unknown): value is { messages: unknown[] } {\n\treturn isObject(value) && Array.isArray(value.messages);\n}\n\nfunction isContentBlockParam(value: unknown): value is ContentBlockParam {\n\treturn isObject(value) && typeof value.type === \"string\";\n}\n\nfunction isToolUseBlock(block: ContentBlockParam): block is Extract<ContentBlockParam, { type: \"tool_use\" }> {\n\treturn block.type === \"tool_use\" && \"id\" in block && typeof block.id === \"string\";\n}\n\nfunction isToolResultBlock(block: ContentBlockParam): block is Extract<ContentBlockParam, { type: \"tool_result\" }> {\n\treturn block.type === \"tool_result\";\n}\n\nconst SYNTHETIC_OUTPUT = \"Tool output unavailable (interrupted before result)\";\n\nfunction cloneWith<T extends object>(block: T, patch: Partial<T>): T {\n\treturn { ...block, ...patch };\n}\n\nfunction isMessageWithArrayContent<Role extends MessageParam[\"role\"]>(\n\tvalue: unknown,\n\trole: Role,\n): value is MessageParam & { role: Role; content: ContentBlockParam[] } {\n\tif (!isObject(value) || value.role !== role || !Array.isArray(value.content)) return false;\n\tfor (const block of value.content) {\n\t\tif (!isContentBlockParam(block)) return false;\n\t}\n\treturn true;\n}\n\nfunction isUserMessageWithStringContent(value: unknown): value is MessageParam & { role: \"user\"; content: string } {\n\treturn isObject(value) && value.role === \"user\" && typeof value.content === \"string\";\n}\n\ninterface AssistantToolUseDedupe {\n\tmessage: MessageParam & { role: \"assistant\"; content: ContentBlockParam[] };\n\tchanged: boolean;\n\texpectedIds: string[];\n\tremapQueues: Map<string, string[]>;\n}\n\nfunction dedupeAssistantToolUses(\n\tmessage: MessageParam & { role: \"assistant\"; content: ContentBlockParam[] },\n\tusedIds: Set<string>,\n): AssistantToolUseDedupe {\n\tconst content: ContentBlockParam[] = [];\n\tconst expectedIds: string[] = [];\n\tconst remapQueues = new Map<string, string[]>();\n\tlet changed = false;\n\tfor (const block of message.content) {\n\t\tif (!isToolUseBlock(block) || block.id.length === 0) {\n\t\t\tcontent.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tlet finalId = block.id;\n\t\tif (usedIds.has(finalId)) {\n\t\t\tlet suffix = 2;\n\t\t\twhile (usedIds.has(`${block.id}__dedup${suffix}`)) suffix += 1;\n\t\t\tfinalId = `${block.id}__dedup${suffix}`;\n\t\t\tchanged = true;\n\t\t}\n\t\tusedIds.add(finalId);\n\t\texpectedIds.push(finalId);\n\t\tconst queue = remapQueues.get(block.id);\n\t\tif (queue === undefined) remapQueues.set(block.id, [finalId]);\n\t\telse queue.push(finalId);\n\t\tcontent.push(finalId === block.id ? block : cloneWith(block, { id: finalId }));\n\t}\n\tif (!changed) return { message, changed: false, expectedIds, remapQueues };\n\treturn { message: { ...message, content }, changed: true, expectedIds, remapQueues };\n}\n\nfunction syntheticToolResult(toolUseId: string): Extract<ContentBlockParam, { type: \"tool_result\" }> {\n\treturn {\n\t\ttype: \"tool_result\",\n\t\ttool_use_id: toolUseId,\n\t\tcontent: SYNTHETIC_OUTPUT,\n\t\tis_error: true,\n\t};\n}\n\nfunction sameBlocks(left: ContentBlockParam[], right: ContentBlockParam[]): boolean {\n\treturn left.length === right.length && left.every((block, index) => block === right[index]);\n}\n\nfunction repairFollowingUserMessage(\n\tmessage: MessageParam & { role: \"user\"; content: ContentBlockParam[] },\n\texpectedIds: string[],\n\tremapQueues: Map<string, string[]>,\n): { message: MessageParam; changed: boolean } {\n\tconst expected = new Set(expectedIds);\n\tconst found = new Set<string>();\n\tconst results: ContentBlockParam[] = [];\n\tconst ordinary: ContentBlockParam[] = [];\n\n\tfor (const block of message.content) {\n\t\tif (!isToolResultBlock(block)) {\n\t\t\tordinary.push(block);\n\t\t\tcontinue;\n\t\t}\n\t\tconst rawId = block.tool_use_id;\n\t\tlet id = rawId;\n\t\tif (typeof rawId === \"string\") {\n\t\t\tconst queue = remapQueues.get(rawId);\n\t\t\tif (queue !== undefined && queue.length > 0) id = queue.shift() as string;\n\t\t}\n\t\tif (typeof id !== \"string\" || !expected.has(id) || found.has(id)) continue;\n\t\tfound.add(id);\n\t\tresults.push(id === rawId ? block : cloneWith(block, { tool_use_id: id }));\n\t}\n\n\tfor (const id of expectedIds) {\n\t\tif (!found.has(id)) results.push(syntheticToolResult(id));\n\t}\n\n\tconst content = [...results, ...ordinary];\n\tif (sameBlocks(content, message.content)) return { message, changed: false };\n\treturn { message: { ...message, content }, changed: true };\n}\n\nfunction removeOrphanResults(message: MessageParam & { role: \"user\"; content: ContentBlockParam[] }): {\n\tmessage?: MessageParam;\n\tchanged: boolean;\n} {\n\tconst content = message.content.filter((block) => !isToolResultBlock(block));\n\tif (content.length === message.content.length) return { message, changed: false };\n\tif (content.length === 0) return { changed: true };\n\treturn { message: { ...message, content }, changed: true };\n}\n\n/** Repairs Anthropic client tool_use/tool_result adjacency and duplicate tool_use ids without mutating the input payload. */\nexport function sanitizeAnthropicToolPairs(payload: unknown): unknown {\n\tif (!hasMessagesArray(payload)) return payload;\n\n\tlet changed = false;\n\tconst usedToolUseIds = new Set<string>();\n\tconst sanitizedMessages: unknown[] = [];\n\n\tfor (let index = 0; index < payload.messages.length; index++) {\n\t\tconst unknownMessage = payload.messages[index];\n\t\tif (isMessageWithArrayContent(unknownMessage, \"assistant\")) {\n\t\t\tconst deduped = dedupeAssistantToolUses(unknownMessage, usedToolUseIds);\n\t\t\tsanitizedMessages.push(deduped.message);\n\t\t\tchanged ||= deduped.changed;\n\t\t\tconst expectedIds = deduped.expectedIds;\n\t\t\tif (expectedIds.length === 0) continue;\n\n\t\t\tconst nextMessage = payload.messages[index + 1];\n\t\t\tif (isMessageWithArrayContent(nextMessage, \"user\")) {\n\t\t\t\tconst repaired = repairFollowingUserMessage(nextMessage, expectedIds, deduped.remapQueues);\n\t\t\t\tsanitizedMessages.push(repaired.message);\n\t\t\t\tchanged ||= repaired.changed;\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isUserMessageWithStringContent(nextMessage)) {\n\t\t\t\tsanitizedMessages.push({\n\t\t\t\t\t...nextMessage,\n\t\t\t\t\tcontent: [...expectedIds.map(syntheticToolResult), { type: \"text\", text: nextMessage.content }],\n\t\t\t\t});\n\t\t\t\tchanged = true;\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsanitizedMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: expectedIds.map(syntheticToolResult),\n\t\t\t});\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isMessageWithArrayContent(unknownMessage, \"user\")) {\n\t\t\tconst repaired = removeOrphanResults(unknownMessage);\n\t\t\tif (repaired.message) sanitizedMessages.push(repaired.message);\n\t\t\tchanged ||= repaired.changed;\n\t\t\tcontinue;\n\t\t}\n\n\t\tsanitizedMessages.push(unknownMessage);\n\t}\n\n\tif (!changed) return payload;\n\treturn { ...payload, messages: sanitizedMessages };\n}\n"]}
@@ -145,6 +145,17 @@ export declare function flushOpenToolCalls(output: AssistantMessage, stream: Ass
145
145
  * - otherwise → completion wins.
146
146
  */
147
147
  export declare function mergeCursorMcpToolCallArgs(streamed: Record<string, unknown> | undefined, completion: Record<string, unknown> | undefined): Record<string, unknown>;
148
+ /**
149
+ * Ensure a Cursor exec frame's tool-call id is present and unique within the
150
+ * assistant message before a block is synthesized from it. Cursor reuses one
151
+ * parent tool-call id across the exec sub-frames of a compound tool
152
+ * (StrReplace → read + write); recording both verbatim persists duplicate
153
+ * `toolCall` ids, which Anthropic later rejects wholesale on resume
154
+ * (`tool_use` ids must be unique), bricking the session. Exported for tests.
155
+ */
156
+ export declare function ensureUniqueCursorExecToolCallId(output: AssistantMessage, args: {
157
+ toolCallId?: string;
158
+ }): void;
148
159
  /**
149
160
  * Synthesize a completed `toolCall` content block for a Cursor exec-channel
150
161
  * native tool or for an MCP exec frame whose corresponding interaction block
@@ -1 +1 @@
1
- {"version":3,"file":"cursor-agent.d.ts","sourceRoot":"","sources":["../../src/api/cursor-agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AAKpC,OAAO,KAAK,EAEX,gBAAgB,EAGhB,OAAO,EAEP,mBAAmB,EACnB,cAAc,EACd,WAAW,EACX,eAAe,EACf,IAAI,EACJ,QAAQ,EACR,iBAAiB,EACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAGN,mBAAmB,EACnB,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AA0BvE,OAAO,EAIN,KAAK,kBAAkB,EAcvB,KAAK,0BAA0B,EA+D/B,KAAK,iBAAiB,EAsDtB,MAAM,gCAAgC,CAAC;AAgBxC,OAAO,KAAK,EACX,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,iBAAiB,EAGjB,uBAAuB,EACvB,MAAM,yBAAyB,CAAC;AASjC,YAAY,EACX,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,iBAAiB,EACjB,aAAa,EACb,YAAY,EACZ,0BAA0B,EAC1B,uBAAuB,GACvB,MAAM,yBAAyB,CAAC;AAEjC,eAAO,MAAM,cAA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E,OAAO,CAAC;CACvB;AAED;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACtD,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB,GAAG,OAAO,CAAC,qBAAqB,EAAE,GAAG,IAAI,CAAC,CAqG1C"}
@@ -1028,8 +1028,7 @@ async function dispatchExecServerMessage(context) {
1028
1028
  switch (execCase) {
1029
1029
  case "readArgs": {
1030
1030
  const args = execMsg.message.value;
1031
- if (!args.toolCallId)
1032
- args.toolCallId = randomUUID();
1031
+ ensureUniqueCursorExecToolCallId(output, args);
1033
1032
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "read", {
1034
1033
  path: args.path,
1035
1034
  offset: args.offset,
@@ -1041,8 +1040,7 @@ async function dispatchExecServerMessage(context) {
1041
1040
  }
1042
1041
  case "lsArgs": {
1043
1042
  const args = execMsg.message.value;
1044
- if (!args.toolCallId)
1045
- args.toolCallId = randomUUID();
1043
+ ensureUniqueCursorExecToolCallId(output, args);
1046
1044
  // The bridge maps `ls` onto the local `ls` tool; mirror that here so
1047
1045
  // the synthesized block matches the toolResult's `toolName`.
1048
1046
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "ls", { path: piLsPath(args.path) });
@@ -1052,8 +1050,7 @@ async function dispatchExecServerMessage(context) {
1052
1050
  }
1053
1051
  case "grepArgs": {
1054
1052
  const args = execMsg.message.value;
1055
- if (!args.toolCallId)
1056
- args.toolCallId = randomUUID();
1053
+ ensureUniqueCursorExecToolCallId(output, args);
1057
1054
  // Cursor's model sometimes emits `grepArgs` with an empty `pattern`
1058
1055
  // and a non-empty `glob`, expecting grep to list files matching the
1059
1056
  // glob. Reject that up front with an actionable error.
@@ -1076,8 +1073,7 @@ async function dispatchExecServerMessage(context) {
1076
1073
  }
1077
1074
  case "writeArgs": {
1078
1075
  const args = execMsg.message.value;
1079
- if (!args.toolCallId)
1080
- args.toolCallId = randomUUID();
1076
+ ensureUniqueCursorExecToolCallId(output, args);
1081
1077
  // Match the bridge: prefer `fileText`, fall back to decoded `fileBytes`.
1082
1078
  const content = args.fileText ?? new TextDecoder().decode(args.fileBytes ?? new Uint8Array());
1083
1079
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "write", {
@@ -1095,8 +1091,7 @@ async function dispatchExecServerMessage(context) {
1095
1091
  }
1096
1092
  case "deleteArgs": {
1097
1093
  const args = execMsg.message.value;
1098
- if (!args.toolCallId)
1099
- args.toolCallId = randomUUID();
1094
+ ensureUniqueCursorExecToolCallId(output, args);
1100
1095
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "delete", { path: args.path });
1101
1096
  const { execResult } = await resolveExecHandler(args, execHandlers?.delete?.bind(execHandlers), onToolResult, (toolResult) => buildDeleteResultFromToolResult(args.path, toolResult), (reason) => buildDeleteRejectedResult(args.path, reason), (error) => buildDeleteErrorResult(args.path, error), { toolCallId: args.toolCallId, toolName: "delete" });
1102
1097
  sendExecClientMessage(h2Request, execMsg, "deleteResult", execResult);
@@ -1104,8 +1099,7 @@ async function dispatchExecServerMessage(context) {
1104
1099
  }
1105
1100
  case "shellArgs": {
1106
1101
  const args = execMsg.message.value;
1107
- if (!args.toolCallId)
1108
- args.toolCallId = randomUUID();
1102
+ ensureUniqueCursorExecToolCallId(output, args);
1109
1103
  const normalizedArgs = { ...args, workingDirectory: args.workingDirectory || process.cwd() };
1110
1104
  const shellTimeout = args.timeout && args.timeout > 0 ? args.timeout : undefined;
1111
1105
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "bash", {
@@ -1118,8 +1112,7 @@ async function dispatchExecServerMessage(context) {
1118
1112
  }
1119
1113
  case "shellStreamArgs": {
1120
1114
  const args = execMsg.message.value;
1121
- if (!args.toolCallId)
1122
- args.toolCallId = randomUUID();
1115
+ ensureUniqueCursorExecToolCallId(output, args);
1123
1116
  const shellStreamTimeout = args.timeout && args.timeout > 0 ? args.timeout : undefined;
1124
1117
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "bash", {
1125
1118
  command: composeShellCommand(args.command, args.workingDirectory || undefined),
@@ -1338,8 +1331,7 @@ async function dispatchExecServerMessage(context) {
1338
1331
  // Same `ShellArgs`/`ShellResult` pair as `shellArgs`, under its own
1339
1332
  // frame number, so the existing shell handler answers it unchanged.
1340
1333
  const args = execMsg.message.value;
1341
- if (!args.toolCallId)
1342
- args.toolCallId = randomUUID();
1334
+ ensureUniqueCursorExecToolCallId(output, args);
1343
1335
  const normalizedArgs = { ...args, workingDirectory: args.workingDirectory || process.cwd() };
1344
1336
  synthesizeCursorExecToolCall(output, stream, state, args.toolCallId, "bash", {
1345
1337
  command: composeShellCommand(args.command, args.workingDirectory || undefined),
@@ -2518,6 +2510,28 @@ function endCurrentThinkingBlock(output, stream, state) {
2518
2510
  });
2519
2511
  state.setThinkingBlock(null);
2520
2512
  }
2513
+ /**
2514
+ * Ensure a Cursor exec frame's tool-call id is present and unique within the
2515
+ * assistant message before a block is synthesized from it. Cursor reuses one
2516
+ * parent tool-call id across the exec sub-frames of a compound tool
2517
+ * (StrReplace → read + write); recording both verbatim persists duplicate
2518
+ * `toolCall` ids, which Anthropic later rejects wholesale on resume
2519
+ * (`tool_use` ids must be unique), bricking the session. Exported for tests.
2520
+ */
2521
+ export function ensureUniqueCursorExecToolCallId(output, args) {
2522
+ if (!args.toolCallId) {
2523
+ args.toolCallId = randomUUID();
2524
+ return;
2525
+ }
2526
+ const base = args.toolCallId;
2527
+ let candidate = base;
2528
+ let suffix = 2;
2529
+ while (output.content.some((block) => block.type === "toolCall" && block.id === candidate)) {
2530
+ candidate = `${base}-${suffix}`;
2531
+ suffix += 1;
2532
+ }
2533
+ args.toolCallId = candidate;
2534
+ }
2521
2535
  /**
2522
2536
  * Synthesize a completed `toolCall` content block for a Cursor exec-channel
2523
2537
  * native tool or for an MCP exec frame whose corresponding interaction block