@namzu/sdk 36.0.0 → 38.0.0

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 (412) hide show
  1. package/CHANGELOG.md +244 -0
  2. package/README.md +68 -41
  3. package/dist/bridge/a2a/mapper.d.ts.map +1 -1
  4. package/dist/bridge/a2a/mapper.js +4 -0
  5. package/dist/bridge/a2a/mapper.js.map +1 -1
  6. package/dist/bridge/sse/mapper.d.ts.map +1 -1
  7. package/dist/bridge/sse/mapper.js +16 -1
  8. package/dist/bridge/sse/mapper.js.map +1 -1
  9. package/dist/compaction/extractor.d.ts +1 -1
  10. package/dist/compaction/extractor.d.ts.map +1 -1
  11. package/dist/compaction/extractor.js +15 -7
  12. package/dist/compaction/extractor.js.map +1 -1
  13. package/dist/compaction/manager.d.ts +2 -0
  14. package/dist/compaction/manager.d.ts.map +1 -1
  15. package/dist/compaction/manager.js +12 -1
  16. package/dist/compaction/manager.js.map +1 -1
  17. package/dist/compaction/verifier.d.ts.map +1 -1
  18. package/dist/compaction/verifier.js +82 -15
  19. package/dist/compaction/verifier.js.map +1 -1
  20. package/dist/config/runtime.d.ts +16 -6
  21. package/dist/config/runtime.d.ts.map +1 -1
  22. package/dist/config/runtime.js +2 -0
  23. package/dist/config/runtime.js.map +1 -1
  24. package/dist/contracts/api.d.ts +1 -1
  25. package/dist/contracts/api.d.ts.map +1 -1
  26. package/dist/contracts/schemas.d.ts +10 -10
  27. package/dist/eval/harness-verification.d.ts +63 -0
  28. package/dist/eval/harness-verification.d.ts.map +1 -0
  29. package/dist/eval/harness-verification.js +165 -0
  30. package/dist/eval/harness-verification.js.map +1 -0
  31. package/dist/eval/index.d.ts +2 -0
  32. package/dist/eval/index.d.ts.map +1 -1
  33. package/dist/eval/index.js +1 -0
  34. package/dist/eval/index.js.map +1 -1
  35. package/dist/execution/code-runtime/json-value.d.ts +10 -0
  36. package/dist/execution/code-runtime/json-value.d.ts.map +1 -0
  37. package/dist/execution/code-runtime/json-value.js +89 -0
  38. package/dist/execution/code-runtime/json-value.js.map +1 -0
  39. package/dist/execution/code-runtime/worker-program.d.ts +8 -0
  40. package/dist/execution/code-runtime/worker-program.d.ts.map +1 -0
  41. package/dist/execution/code-runtime/worker-program.js +240 -0
  42. package/dist/execution/code-runtime/worker-program.js.map +1 -0
  43. package/dist/execution/code-runtime/worker.d.ts +22 -0
  44. package/dist/execution/code-runtime/worker.d.ts.map +1 -1
  45. package/dist/execution/code-runtime/worker.js +148 -111
  46. package/dist/execution/code-runtime/worker.js.map +1 -1
  47. package/dist/manager/agent/lifecycle.d.ts +12 -0
  48. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  49. package/dist/manager/agent/lifecycle.js +316 -46
  50. package/dist/manager/agent/lifecycle.js.map +1 -1
  51. package/dist/manager/run/persistence.d.ts +2 -0
  52. package/dist/manager/run/persistence.d.ts.map +1 -1
  53. package/dist/manager/run/persistence.js +6 -0
  54. package/dist/manager/run/persistence.js.map +1 -1
  55. package/dist/prompt/coding-agent-doctrine.d.ts +2 -2
  56. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  57. package/dist/prompt/coding-agent-doctrine.js +11 -5
  58. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  59. package/dist/provider/capabilities.d.ts +5 -1
  60. package/dist/provider/capabilities.d.ts.map +1 -1
  61. package/dist/provider/capabilities.js +24 -0
  62. package/dist/provider/capabilities.js.map +1 -1
  63. package/dist/provider/fallback.d.ts.map +1 -1
  64. package/dist/provider/fallback.js +6 -2
  65. package/dist/provider/fallback.js.map +1 -1
  66. package/dist/public-runtime.d.ts +4 -1
  67. package/dist/public-runtime.d.ts.map +1 -1
  68. package/dist/public-runtime.js +3 -1
  69. package/dist/public-runtime.js.map +1 -1
  70. package/dist/public-tools.d.ts +2 -1
  71. package/dist/public-tools.d.ts.map +1 -1
  72. package/dist/public-tools.js +2 -1
  73. package/dist/public-tools.js.map +1 -1
  74. package/dist/public-types.d.ts +2 -0
  75. package/dist/public-types.d.ts.map +1 -1
  76. package/dist/registry/tool/execute.d.ts +3 -0
  77. package/dist/registry/tool/execute.d.ts.map +1 -1
  78. package/dist/registry/tool/execute.js +11 -80
  79. package/dist/registry/tool/execute.js.map +1 -1
  80. package/dist/run/command-gate.d.ts.map +1 -1
  81. package/dist/run/command-gate.js +65 -12
  82. package/dist/run/command-gate.js.map +1 -1
  83. package/dist/run/index.d.ts +2 -0
  84. package/dist/run/index.d.ts.map +1 -1
  85. package/dist/run/index.js +1 -0
  86. package/dist/run/index.js.map +1 -1
  87. package/dist/run/memory-promoter.d.ts +3 -35
  88. package/dist/run/memory-promoter.d.ts.map +1 -1
  89. package/dist/run/memory-promoter.js +32 -40
  90. package/dist/run/memory-promoter.js.map +1 -1
  91. package/dist/run/memory-recall.d.ts +25 -0
  92. package/dist/run/memory-recall.d.ts.map +1 -0
  93. package/dist/run/memory-recall.js +228 -0
  94. package/dist/run/memory-recall.js.map +1 -0
  95. package/dist/run/reporter.d.ts.map +1 -1
  96. package/dist/run/reporter.js +2 -0
  97. package/dist/run/reporter.js.map +1 -1
  98. package/dist/run/token-budget.d.ts +12 -4
  99. package/dist/run/token-budget.d.ts.map +1 -1
  100. package/dist/run/token-budget.js +49 -14
  101. package/dist/run/token-budget.js.map +1 -1
  102. package/dist/run/workspace-fingerprint.d.ts +10 -3
  103. package/dist/run/workspace-fingerprint.d.ts.map +1 -1
  104. package/dist/run/workspace-fingerprint.js +17 -8
  105. package/dist/run/workspace-fingerprint.js.map +1 -1
  106. package/dist/runtime/query/checkpoint.d.ts +14 -0
  107. package/dist/runtime/query/checkpoint.d.ts.map +1 -1
  108. package/dist/runtime/query/checkpoint.js +82 -1
  109. package/dist/runtime/query/checkpoint.js.map +1 -1
  110. package/dist/runtime/query/executor.d.ts +8 -3
  111. package/dist/runtime/query/executor.d.ts.map +1 -1
  112. package/dist/runtime/query/executor.js +94 -30
  113. package/dist/runtime/query/executor.js.map +1 -1
  114. package/dist/runtime/query/index.d.ts +7 -8
  115. package/dist/runtime/query/index.d.ts.map +1 -1
  116. package/dist/runtime/query/index.js +55 -7
  117. package/dist/runtime/query/index.js.map +1 -1
  118. package/dist/runtime/query/iteration/index.d.ts +12 -0
  119. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  120. package/dist/runtime/query/iteration/index.js +348 -38
  121. package/dist/runtime/query/iteration/index.js.map +1 -1
  122. package/dist/runtime/query/iteration/native-output.d.ts +10 -0
  123. package/dist/runtime/query/iteration/native-output.d.ts.map +1 -0
  124. package/dist/runtime/query/iteration/native-output.js +32 -0
  125. package/dist/runtime/query/iteration/native-output.js.map +1 -0
  126. package/dist/runtime/query/iteration/phases/advisory.d.ts.map +1 -1
  127. package/dist/runtime/query/iteration/phases/advisory.js +18 -13
  128. package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
  129. package/dist/runtime/query/iteration/phases/compaction.d.ts +2 -0
  130. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  131. package/dist/runtime/query/iteration/phases/compaction.js +32 -11
  132. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  133. package/dist/runtime/query/iteration/phases/context.d.ts +9 -0
  134. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  135. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  136. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  137. package/dist/runtime/query/iteration/phases/tool-review.js +1 -1
  138. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  139. package/dist/runtime/query/iteration/phases/working-memory.d.ts +1 -1
  140. package/dist/runtime/query/iteration/phases/working-memory.d.ts.map +1 -1
  141. package/dist/runtime/query/iteration/phases/working-memory.js +23 -6
  142. package/dist/runtime/query/iteration/phases/working-memory.js.map +1 -1
  143. package/dist/runtime/query/iteration/stream-turn.d.ts.map +1 -1
  144. package/dist/runtime/query/iteration/stream-turn.js +12 -0
  145. package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
  146. package/dist/runtime/query/observation-context.d.ts +10 -0
  147. package/dist/runtime/query/observation-context.d.ts.map +1 -0
  148. package/dist/runtime/query/observation-context.js +84 -0
  149. package/dist/runtime/query/observation-context.js.map +1 -0
  150. package/dist/runtime/query/request-context.d.ts +30 -0
  151. package/dist/runtime/query/request-context.d.ts.map +1 -0
  152. package/dist/runtime/query/request-context.js +76 -0
  153. package/dist/runtime/query/request-context.js.map +1 -0
  154. package/dist/runtime/query/request-rich-content.d.ts.map +1 -1
  155. package/dist/runtime/query/request-rich-content.js +6 -3
  156. package/dist/runtime/query/request-rich-content.js.map +1 -1
  157. package/dist/runtime/query/review-policy.d.ts +3 -0
  158. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  159. package/dist/runtime/query/review-policy.js +4 -1
  160. package/dist/runtime/query/review-policy.js.map +1 -1
  161. package/dist/runtime/query/steering.d.ts +6 -2
  162. package/dist/runtime/query/steering.d.ts.map +1 -1
  163. package/dist/runtime/query/steering.js +17 -2
  164. package/dist/runtime/query/steering.js.map +1 -1
  165. package/dist/runtime/query/tool-call-budget.d.ts +19 -0
  166. package/dist/runtime/query/tool-call-budget.d.ts.map +1 -0
  167. package/dist/runtime/query/tool-call-budget.js +110 -0
  168. package/dist/runtime/query/tool-call-budget.js.map +1 -0
  169. package/dist/runtime/query/tooling.d.ts +3 -0
  170. package/dist/runtime/query/tooling.d.ts.map +1 -1
  171. package/dist/runtime/query/tooling.js +5 -0
  172. package/dist/runtime/query/tooling.js.map +1 -1
  173. package/dist/sandbox/file-walk-program.d.ts.map +1 -1
  174. package/dist/sandbox/file-walk-program.js +8 -0
  175. package/dist/sandbox/file-walk-program.js.map +1 -1
  176. package/dist/sandbox/file-walk.d.ts.map +1 -1
  177. package/dist/sandbox/file-walk.js +9 -0
  178. package/dist/sandbox/file-walk.js.map +1 -1
  179. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  180. package/dist/scheduler/completion-inbox.js +3 -0
  181. package/dist/scheduler/completion-inbox.js.map +1 -1
  182. package/dist/scheduler/local.d.ts.map +1 -1
  183. package/dist/scheduler/local.js +1 -0
  184. package/dist/scheduler/local.js.map +1 -1
  185. package/dist/session/handoff/capacity.d.ts +2 -2
  186. package/dist/session/handoff/capacity.d.ts.map +1 -1
  187. package/dist/session/handoff/capacity.js +3 -2
  188. package/dist/session/handoff/capacity.js.map +1 -1
  189. package/dist/store/memory/disk.d.ts +6 -2
  190. package/dist/store/memory/disk.d.ts.map +1 -1
  191. package/dist/store/memory/disk.js +42 -25
  192. package/dist/store/memory/disk.js.map +1 -1
  193. package/dist/store/memory/index.d.ts +4 -0
  194. package/dist/store/memory/index.d.ts.map +1 -1
  195. package/dist/store/memory/index.js +55 -19
  196. package/dist/store/memory/index.js.map +1 -1
  197. package/dist/store/memory/memory.d.ts +3 -2
  198. package/dist/store/memory/memory.d.ts.map +1 -1
  199. package/dist/store/memory/memory.js +11 -2
  200. package/dist/store/memory/memory.js.map +1 -1
  201. package/dist/store/memory/operation-lock.d.ts +11 -0
  202. package/dist/store/memory/operation-lock.d.ts.map +1 -0
  203. package/dist/store/memory/operation-lock.js +94 -0
  204. package/dist/store/memory/operation-lock.js.map +1 -0
  205. package/dist/store/run/token-budget-disk.js +3 -0
  206. package/dist/store/run/token-budget-disk.js.map +1 -1
  207. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  208. package/dist/tools/builtins/computer-use.js +60 -10
  209. package/dist/tools/builtins/computer-use.js.map +1 -1
  210. package/dist/tools/builtins/edit.d.ts.map +1 -1
  211. package/dist/tools/builtins/edit.js +12 -26
  212. package/dist/tools/builtins/edit.js.map +1 -1
  213. package/dist/tools/builtins/file-write-result.d.ts +4 -0
  214. package/dist/tools/builtins/file-write-result.d.ts.map +1 -0
  215. package/dist/tools/builtins/file-write-result.js +72 -0
  216. package/dist/tools/builtins/file-write-result.js.map +1 -0
  217. package/dist/tools/builtins/glob.d.ts.map +1 -1
  218. package/dist/tools/builtins/glob.js +8 -1
  219. package/dist/tools/builtins/glob.js.map +1 -1
  220. package/dist/tools/builtins/grep.d.ts.map +1 -1
  221. package/dist/tools/builtins/grep.js +10 -0
  222. package/dist/tools/builtins/grep.js.map +1 -1
  223. package/dist/tools/builtins/job.d.ts.map +1 -1
  224. package/dist/tools/builtins/job.js +6 -0
  225. package/dist/tools/builtins/job.js.map +1 -1
  226. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  227. package/dist/tools/builtins/read-file.js +10 -0
  228. package/dist/tools/builtins/read-file.js.map +1 -1
  229. package/dist/tools/builtins/run-code.d.ts +6 -0
  230. package/dist/tools/builtins/run-code.d.ts.map +1 -1
  231. package/dist/tools/builtins/run-code.js +15 -4
  232. package/dist/tools/builtins/run-code.js.map +1 -1
  233. package/dist/tools/builtins/search-tools.d.ts.map +1 -1
  234. package/dist/tools/builtins/search-tools.js +14 -2
  235. package/dist/tools/builtins/search-tools.js.map +1 -1
  236. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  237. package/dist/tools/builtins/write-file.js +30 -44
  238. package/dist/tools/builtins/write-file.js.map +1 -1
  239. package/dist/tools/defineTool.d.ts +2 -0
  240. package/dist/tools/defineTool.d.ts.map +1 -1
  241. package/dist/tools/defineTool.js +3 -0
  242. package/dist/tools/defineTool.js.map +1 -1
  243. package/dist/tools/file-read-tracker.d.ts +4 -0
  244. package/dist/tools/file-read-tracker.d.ts.map +1 -0
  245. package/dist/tools/file-read-tracker.js +16 -0
  246. package/dist/tools/file-read-tracker.js.map +1 -0
  247. package/dist/tools/memory/delete.d.ts +4 -0
  248. package/dist/tools/memory/delete.d.ts.map +1 -0
  249. package/dist/tools/memory/delete.js +26 -0
  250. package/dist/tools/memory/delete.js.map +1 -0
  251. package/dist/tools/memory/index.d.ts +2 -0
  252. package/dist/tools/memory/index.d.ts.map +1 -1
  253. package/dist/tools/memory/index.js +6 -0
  254. package/dist/tools/memory/index.js.map +1 -1
  255. package/dist/tools/memory/save.d.ts.map +1 -1
  256. package/dist/tools/memory/save.js +3 -2
  257. package/dist/tools/memory/save.js.map +1 -1
  258. package/dist/tools/memory/search.d.ts.map +1 -1
  259. package/dist/tools/memory/search.js +12 -5
  260. package/dist/tools/memory/search.js.map +1 -1
  261. package/dist/tools/memory/update.d.ts +4 -0
  262. package/dist/tools/memory/update.d.ts.map +1 -0
  263. package/dist/tools/memory/update.js +47 -0
  264. package/dist/tools/memory/update.js.map +1 -0
  265. package/dist/tools/task/list.js +2 -2
  266. package/dist/tools/task/list.js.map +1 -1
  267. package/dist/types/agent/scheduler.d.ts +5 -0
  268. package/dist/types/agent/scheduler.d.ts.map +1 -1
  269. package/dist/types/agent/task.d.ts +10 -0
  270. package/dist/types/agent/task.d.ts.map +1 -1
  271. package/dist/types/computer-use/index.d.ts +6 -0
  272. package/dist/types/computer-use/index.d.ts.map +1 -1
  273. package/dist/types/computer-use/index.js.map +1 -1
  274. package/dist/types/errors/catalog.js +1 -1
  275. package/dist/types/errors/catalog.js.map +1 -1
  276. package/dist/types/hitl/index.d.ts +11 -1
  277. package/dist/types/hitl/index.d.ts.map +1 -1
  278. package/dist/types/hitl/index.js.map +1 -1
  279. package/dist/types/memory/index.d.ts +14 -1
  280. package/dist/types/memory/index.d.ts.map +1 -1
  281. package/dist/types/plugin/index.d.ts +7 -0
  282. package/dist/types/plugin/index.d.ts.map +1 -1
  283. package/dist/types/plugin/index.js.map +1 -1
  284. package/dist/types/project/entity.d.ts +1 -0
  285. package/dist/types/project/entity.d.ts.map +1 -1
  286. package/dist/types/provider/chat.d.ts +4 -0
  287. package/dist/types/provider/chat.d.ts.map +1 -1
  288. package/dist/types/provider/config.d.ts +4 -0
  289. package/dist/types/provider/config.d.ts.map +1 -1
  290. package/dist/types/provider/model.d.ts +4 -0
  291. package/dist/types/provider/model.d.ts.map +1 -1
  292. package/dist/types/provider/stream.d.ts +6 -0
  293. package/dist/types/provider/stream.d.ts.map +1 -1
  294. package/dist/types/run/answer-review.d.ts +2 -0
  295. package/dist/types/run/answer-review.d.ts.map +1 -1
  296. package/dist/types/run/config.d.ts +2 -0
  297. package/dist/types/run/config.d.ts.map +1 -1
  298. package/dist/types/run/events.d.ts +19 -0
  299. package/dist/types/run/events.d.ts.map +1 -1
  300. package/dist/types/run/events.js.map +1 -1
  301. package/dist/types/run/prepare-step.d.ts +19 -1
  302. package/dist/types/run/prepare-step.d.ts.map +1 -1
  303. package/dist/types/sandbox/index.d.ts +1 -0
  304. package/dist/types/sandbox/index.d.ts.map +1 -1
  305. package/dist/types/sandbox/index.js.map +1 -1
  306. package/dist/types/structured-output/index.d.ts +8 -2
  307. package/dist/types/structured-output/index.d.ts.map +1 -1
  308. package/dist/types/tool/index.d.ts +15 -0
  309. package/dist/types/tool/index.d.ts.map +1 -1
  310. package/dist/types/tool/index.js.map +1 -1
  311. package/dist/types/tool/presentation.d.ts +4 -0
  312. package/dist/types/tool/presentation.d.ts.map +1 -1
  313. package/dist/utils/json-snapshot.d.ts +3 -0
  314. package/dist/utils/json-snapshot.d.ts.map +1 -0
  315. package/dist/utils/json-snapshot.js +79 -0
  316. package/dist/utils/json-snapshot.js.map +1 -0
  317. package/package.json +4 -2
  318. package/src/bridge/a2a/mapper.ts +4 -0
  319. package/src/bridge/sse/mapper.ts +16 -1
  320. package/src/compaction/extractor.ts +21 -8
  321. package/src/compaction/manager.ts +11 -1
  322. package/src/compaction/verifier.ts +80 -18
  323. package/src/config/runtime.ts +2 -0
  324. package/src/contracts/api.ts +1 -0
  325. package/src/eval/harness-verification.ts +270 -0
  326. package/src/eval/index.ts +10 -0
  327. package/src/execution/code-runtime/json-value.ts +82 -0
  328. package/src/execution/code-runtime/worker-program.ts +239 -0
  329. package/src/execution/code-runtime/worker.ts +164 -111
  330. package/src/manager/agent/lifecycle.ts +352 -54
  331. package/src/manager/run/persistence.ts +7 -0
  332. package/src/prompt/coding-agent-doctrine.ts +11 -5
  333. package/src/provider/capabilities.ts +41 -1
  334. package/src/provider/fallback.ts +9 -2
  335. package/src/public-runtime.ts +6 -0
  336. package/src/public-tools.ts +7 -1
  337. package/src/public-types.ts +7 -0
  338. package/src/registry/tool/execute.ts +17 -79
  339. package/src/run/command-gate.ts +61 -13
  340. package/src/run/index.ts +2 -0
  341. package/src/run/memory-promoter.ts +32 -40
  342. package/src/run/memory-recall.ts +254 -0
  343. package/src/run/reporter.ts +2 -0
  344. package/src/run/token-budget.ts +55 -14
  345. package/src/run/workspace-fingerprint.ts +17 -8
  346. package/src/runtime/query/checkpoint.ts +96 -2
  347. package/src/runtime/query/executor.ts +100 -29
  348. package/src/runtime/query/index.ts +76 -16
  349. package/src/runtime/query/iteration/index.ts +405 -46
  350. package/src/runtime/query/iteration/native-output.ts +35 -0
  351. package/src/runtime/query/iteration/phases/advisory.ts +21 -11
  352. package/src/runtime/query/iteration/phases/compaction.ts +36 -14
  353. package/src/runtime/query/iteration/phases/context.ts +9 -0
  354. package/src/runtime/query/iteration/phases/tool-review.ts +5 -1
  355. package/src/runtime/query/iteration/phases/working-memory.ts +23 -5
  356. package/src/runtime/query/iteration/stream-turn.ts +15 -0
  357. package/src/runtime/query/observation-context.ts +86 -0
  358. package/src/runtime/query/request-context.ts +103 -0
  359. package/src/runtime/query/request-rich-content.ts +8 -3
  360. package/src/runtime/query/review-policy.ts +7 -1
  361. package/src/runtime/query/steering.ts +19 -2
  362. package/src/runtime/query/tool-call-budget.ts +115 -0
  363. package/src/runtime/query/tooling.ts +8 -0
  364. package/src/sandbox/file-walk-program.ts +8 -0
  365. package/src/sandbox/file-walk.ts +9 -0
  366. package/src/scheduler/completion-inbox.ts +3 -0
  367. package/src/scheduler/local.ts +1 -0
  368. package/src/session/handoff/capacity.ts +7 -3
  369. package/src/store/memory/disk.ts +52 -30
  370. package/src/store/memory/index.ts +75 -27
  371. package/src/store/memory/memory.ts +18 -6
  372. package/src/store/memory/operation-lock.ts +99 -0
  373. package/src/store/run/token-budget-disk.ts +3 -0
  374. package/src/tools/builtins/computer-use.ts +61 -7
  375. package/src/tools/builtins/edit.ts +12 -27
  376. package/src/tools/builtins/file-write-result.ts +84 -0
  377. package/src/tools/builtins/glob.ts +7 -1
  378. package/src/tools/builtins/grep.ts +10 -0
  379. package/src/tools/builtins/job.ts +8 -0
  380. package/src/tools/builtins/read-file.ts +10 -0
  381. package/src/tools/builtins/run-code.ts +24 -5
  382. package/src/tools/builtins/search-tools.ts +18 -3
  383. package/src/tools/builtins/write-file.ts +39 -44
  384. package/src/tools/defineTool.ts +5 -0
  385. package/src/tools/file-read-tracker.ts +16 -0
  386. package/src/tools/memory/delete.ts +29 -0
  387. package/src/tools/memory/index.ts +6 -0
  388. package/src/tools/memory/save.ts +4 -2
  389. package/src/tools/memory/search.ts +12 -5
  390. package/src/tools/memory/update.ts +50 -0
  391. package/src/tools/task/list.ts +2 -2
  392. package/src/types/agent/scheduler.ts +6 -0
  393. package/src/types/agent/task.ts +13 -0
  394. package/src/types/computer-use/index.ts +6 -0
  395. package/src/types/errors/catalog.ts +1 -1
  396. package/src/types/hitl/index.ts +11 -1
  397. package/src/types/memory/index.ts +16 -1
  398. package/src/types/plugin/index.ts +10 -0
  399. package/src/types/project/entity.ts +1 -0
  400. package/src/types/provider/chat.ts +2 -0
  401. package/src/types/provider/config.ts +4 -0
  402. package/src/types/provider/model.ts +4 -0
  403. package/src/types/provider/stream.ts +7 -0
  404. package/src/types/run/answer-review.ts +2 -0
  405. package/src/types/run/config.ts +2 -0
  406. package/src/types/run/events.ts +20 -0
  407. package/src/types/run/prepare-step.ts +19 -1
  408. package/src/types/sandbox/index.ts +1 -0
  409. package/src/types/structured-output/index.ts +15 -2
  410. package/src/types/tool/index.ts +16 -0
  411. package/src/types/tool/presentation.ts +4 -0
  412. package/src/utils/json-snapshot.ts +76 -0
@@ -0,0 +1,35 @@
1
+ import type { z } from 'zod'
2
+ import type { ChatCompletionResponse } from '../../../types/provider/index.js'
3
+ import { cloneJsonValue } from '../../../utils/json-snapshot.js'
4
+
5
+ /** Native constraints are transport assistance; local validation still owns acceptance. */
6
+ export async function parseNativeCandidate(
7
+ schema: z.ZodType,
8
+ response: ChatCompletionResponse,
9
+ signal: AbortSignal,
10
+ ): Promise<{ success: true; value: unknown } | { success: false }> {
11
+ signal.throwIfAborted()
12
+ if (response.finishReason !== 'stop' || response.message.toolCalls?.length)
13
+ return { success: false }
14
+ let input: unknown
15
+ try {
16
+ input = JSON.parse(response.message.content ?? '')
17
+ } catch {
18
+ return { success: false }
19
+ }
20
+ let abort!: () => void
21
+ const cancelled = new Promise<never>((_resolve, reject) => {
22
+ abort = () => reject(signal.reason ?? new Error('Native output validation cancelled'))
23
+ signal.addEventListener('abort', abort, { once: true })
24
+ })
25
+ try {
26
+ const parsed = await Promise.race([schema.safeParseAsync(input), cancelled])
27
+ signal.throwIfAborted()
28
+ if (!parsed.success) return { success: false }
29
+ // Match the serialized result contract of output-tool mode. Never rerun transforms.
30
+ const value = cloneJsonValue(parsed.data, false)
31
+ return { success: true, value }
32
+ } finally {
33
+ signal.removeEventListener('abort', abort)
34
+ }
35
+ }
@@ -5,6 +5,7 @@ import { toolResultToText } from '../../../../types/message/content.js'
5
5
  import { createRuntimeContextMessage } from '../../../../types/message/index.js'
6
6
  import type { ChatCompletionResponse } from '../../../../types/provider/index.js'
7
7
  import { toErrorMessage } from '../../../../utils/error.js'
8
+ import { activeContextWindow, measureContext } from './compaction.js'
8
9
  import type { IterationContext } from './context.js'
9
10
 
10
11
  function countToolCalls(ctx: IterationContext): number {
@@ -18,9 +19,8 @@ function countToolCalls(ctx: IterationContext): number {
18
19
  }
19
20
 
20
21
  function estimateContextWindowPercent(ctx: IterationContext): number {
21
- const budget = ctx.runConfig.tokenBudget
22
- if (budget <= 0) return 0
23
- return (ctx.runMgr.tokenUsage.totalTokens / budget) * 100
22
+ const window = activeContextWindow(ctx)
23
+ return (measureContext(ctx).tokens / window.tokens) * 100
24
24
  }
25
25
 
26
26
  function computeCostBudgetPercent(ctx: IterationContext): number | undefined {
@@ -67,7 +67,7 @@ export async function runAdvisoryPhase(
67
67
  contextWindowPercent: estimateContextWindowPercent(ctx),
68
68
  totalCostUsd: ctx.runMgr.costInfo.totalCost,
69
69
  costBudgetPercent: computeCostBudgetPercent(ctx),
70
- lastError: extractLastErrorFromMessages(ctx),
70
+ lastError: extractCurrentToolErrors(ctx, response),
71
71
  lastToolCategory: extractLastToolCategory(ctx, response),
72
72
  advisoryCallCount: advisoryCtx.callHistory.length,
73
73
  }
@@ -190,16 +190,26 @@ export async function runAdvisoryPhase(
190
190
  }
191
191
  }
192
192
 
193
- function extractLastErrorFromMessages(ctx: IterationContext): string | undefined {
193
+ function extractCurrentToolErrors(
194
+ ctx: IterationContext,
195
+ response: ChatCompletionResponse,
196
+ ): string | undefined {
197
+ const calls = new Map(response.message.toolCalls?.map((call) => [call.id, call.function.name]))
198
+ if (calls.size === 0) return undefined
194
199
  const messages = ctx.runMgr.messages
200
+ const errors: string[] = []
195
201
  for (let i = messages.length - 1; i >= 0; i--) {
196
202
  const msg = messages[i]
197
- if (msg?.role === 'tool') {
198
- // Tool results can now carry content blocks; the error sentinel is
199
- // a text convention, so flatten before matching it.
200
- const text = toolResultToText(msg.content)
201
- if (text.startsWith('Error:')) return text
203
+ // The current assistant turn starts this batch. Never resurrect an old
204
+ // failure, even if a provider reused a call ID in another iteration.
205
+ if (msg?.role === 'assistant') break
206
+ if (msg?.role === 'tool' && msg.isError === true && calls.has(msg.toolCallId)) {
207
+ errors.push(
208
+ toolResultToText(msg.content).trim() ||
209
+ `Tool ${calls.get(msg.toolCallId)} reported an error.`,
210
+ )
202
211
  }
203
212
  }
204
- return undefined
213
+ // A successful sibling does not erase failed results in this same batch.
214
+ return errors.length > 0 ? errors.reverse().join('\n') : undefined
205
215
  }
@@ -28,6 +28,16 @@ import { isWorkingMemoryMessage } from './working-memory.js'
28
28
  // because `runtime/query/index.ts` already imports it from this path.
29
29
  export { isCompactionMessage } from '../../../../compaction/summary.js'
30
30
 
31
+ /** The selected request model owns the denominator, including overflow recovery. */
32
+ export function activeContextWindow(ctx: IterationContext) {
33
+ const model = ctx.contextModel ?? ctx.runConfig.model
34
+ return resolveContextWindow(
35
+ ctx.compactionConfig?.contextWindowTokens,
36
+ model,
37
+ model === ctx.runConfig.model ? ctx.providerContextWindow : ctx.activeProviderContextWindow,
38
+ )
39
+ }
40
+
31
41
  /**
32
42
  * How much a forced pass must shed before the turn is worth retrying.
33
43
  *
@@ -147,7 +157,12 @@ async function commitToolResultClear(
147
157
  plan: ToolResultClearPlan,
148
158
  contextWindowTokens: number,
149
159
  windowSource: 'config' | 'provider' | 'model-table' | 'default',
160
+ reason: 'threshold' | 'overflow',
150
161
  ): Promise<void> {
162
+ // A shorter replacement also removes evidence. Preserve its original
163
+ // content in the same archive used by whole-message compaction before
164
+ // changing the live history or publishing the clear.
165
+ await recordShed(ctx, [...ctx.runMgr.messages], plan.messages, reason)
151
166
  installMessages(ctx.runMgr.messages, plan.messages)
152
167
  // The provider counted the pre-edit prompt. Leaving that measurement live
153
168
  // makes the next trigger compare the old prompt against the new history.
@@ -547,11 +562,7 @@ async function runCompactionCheckInner(
547
562
  // number. Nothing in the estate ever set `contextWindowTokens`, so the
548
563
  // fallback WAS the behavior, and the shipped CLI's 1M budget put the
549
564
  // trigger at ~700k. See `compaction/context-window.ts`.
550
- const window = resolveContextWindow(
551
- config.contextWindowTokens,
552
- ctx.runConfig.model,
553
- ctx.providerContextWindow,
554
- )
565
+ const window = activeContextWindow(ctx)
555
566
  const budget = window.tokens
556
567
 
557
568
  const usage = estimatedTokens / budget
@@ -659,7 +670,7 @@ async function runCompactionCheckInner(
659
670
  ...(openTasks ? { openTasks } : {}),
660
671
  })
661
672
  if (working.reclaimedTokens > 0) {
662
- await commitToolResultClear(ctx, working, budget, window.source)
673
+ await commitToolResultClear(ctx, working, budget, window.source, pass.reason)
663
674
  }
664
675
  // Under the trigger, the working set was the whole pass: the summary
665
676
  // path is for the trigger, not for the soft target.
@@ -684,7 +695,7 @@ async function runCompactionCheckInner(
684
695
  // the NEXT turn will correct it, and an over-eager summarization is
685
696
  // far more costly than one late pass.
686
697
  if (clearPlan.reliefWasEnough) {
687
- await commitToolResultClear(ctx, clearPlan, budget, window.source)
698
+ await commitToolResultClear(ctx, clearPlan, budget, window.source, pass.reason)
688
699
  return
689
700
  }
690
701
  }
@@ -736,7 +747,7 @@ async function runCompactionCheckInner(
736
747
  // There is no opaque provider wait on this path, so publish that single
737
748
  // complete edit now rather than discarding it.
738
749
  if (stagedClear) {
739
- await commitToolResultClear(ctx, stagedClear, budget, window.source)
750
+ await commitToolResultClear(ctx, stagedClear, budget, window.source, pass.reason)
740
751
  }
741
752
  return
742
753
  }
@@ -823,6 +834,20 @@ async function runCompactionCheckInner(
823
834
 
824
835
  const live = ctx.runMgr.messages
825
836
  const oldCount = live.length
837
+ // Retained history can survive in full while a summary adds another copy
838
+ // of its facts. Even an unretained span may be smaller than the cumulative
839
+ // summary. Compare both candidates with the same estimator, rather than
840
+ // comparing provider usage against an estimate or trusting message count.
841
+ // When a clear was staged, require the summary itself to improve on it;
842
+ // otherwise publish the useful clear without consuming its savings.
843
+ if (estimateMessagesTokens(newMessages) >= estimateMessagesTokens(messages)) {
844
+ if (stagedClear && stagedClear.reclaimedTokens > 0) {
845
+ await commitToolResultClear(ctx, stagedClear, budget, window.source, pass.reason)
846
+ } else {
847
+ await declined(ctx, 'shed_nothing', oldCount)
848
+ }
849
+ return
850
+ }
826
851
  await recordShed(ctx, [...live], newMessages, options?.force ? 'overflow' : 'threshold')
827
852
 
828
853
  installMessages(live, newMessages)
@@ -840,12 +865,9 @@ async function runCompactionCheckInner(
840
865
  // edits are installed and no verifier can still fail between them.
841
866
  if (stagedClear) await emitToolResultClear(ctx, stagedClear)
842
867
 
843
- // Hysteresis. A pass that only gets the context from 0.72 to 0.71 of the
844
- // window leaves the trigger armed, so the next iteration compacts again
845
- // — paying a summarization call and busting the prompt-cache prefix each
846
- // time, for nothing. Report the shortfall rather than repeating a move
847
- // that demonstrably does not work; `resetThreshold` was declared and
848
- // CLI-set but read by nothing until now.
868
+ // Report remaining pressure after a useful edit. This diagnostic does not
869
+ // suppress future passes: appended evidence may become reclaimable even
870
+ // when the protected floor and recent history remain above the target.
849
871
  const reachedReset = newEstimate / budget <= config.resetThreshold
850
872
  if (!reachedReset) {
851
873
  ctx.log.warn('Compaction did not reach its reset threshold — context may still be tight', {
@@ -131,6 +131,8 @@ export interface IterationContext {
131
131
  * drained and no tool result is extended.
132
132
  */
133
133
  readonly steering?: SteeringChannel
134
+ /** Records operator intent only after guidance was accepted by a tool result. */
135
+ readonly onSteeringDelivered?: (text: string) => void
134
136
  /** Exit notices for the run's background jobs, drained into the next tool result. */
135
137
  readonly jobNotices?: SteeringChannel
136
138
  readonly checkpointMgr: CheckpointManager
@@ -179,6 +181,11 @@ export interface IterationContext {
179
181
  * through to the table.
180
182
  */
181
183
  readonly providerContextWindow?: number
184
+ /** Selected request model; its window must not reuse another model's metadata. */
185
+ contextModel?: string
186
+ activeProviderContextWindow?: number
187
+ /** Bounded, run-cached provider metadata lookup for a newly selected model. */
188
+ readonly resolveModelContextWindow?: (model: string) => Promise<number | undefined>
182
189
 
183
190
  /**
184
191
  * Text queued for this run since its last turn.
@@ -188,6 +195,8 @@ export interface IterationContext {
188
195
  * after tool results and before the next turn.
189
196
  */
190
197
  readonly inboundMessages?: () => readonly import('../../../../types/message/index.js').Message[]
198
+ /** Known topic-queue arrivals appended after the restored checkpoint history. */
199
+ readonly resumedInput?: readonly import('../../../../types/message/index.js').Message[]
191
200
  /** Observes pending input without draining it; abort releases the waiter. */
192
201
  readonly waitForInbound?: (signal: AbortSignal) => Promise<void>
193
202
 
@@ -146,7 +146,11 @@ export async function* runToolReview(
146
146
  // user message wedged between them is rejected by the provider. Same
147
147
  // delivery a denial already uses, without the refusal.
148
148
  for (const msg of attachRepeatNotice(
149
- attachNotice(attachSteering(batch.messages, ctx.steering), ctx.jobNotices, formatJobNote),
149
+ attachNotice(
150
+ attachSteering(batch.messages, ctx.steering, ctx.onSteeringDelivered),
151
+ ctx.jobNotices,
152
+ formatJobNote,
153
+ ),
150
154
  notices,
151
155
  )) {
152
156
  ctx.runMgr.pushMessage(msg)
@@ -14,6 +14,10 @@ import type { IterationContext } from './context.js'
14
14
  export const WORKING_MEMORY_HEADER =
15
15
  '[WORKING MEMORY] Authoritative state for this conversation — you produced these.'
16
16
 
17
+ // Stored in the message, so ownership survives checkpoint JSON. Unmarked
18
+ // inherited blocks may be opaque host ledgers and must never be guessed away.
19
+ const TOOL_PINS_HEADER = `${WORKING_MEMORY_HEADER}\n[Tool-managed pins]`
20
+
17
21
  /**
18
22
  * True when `content` is the pinned working-memory slot (header identity only).
19
23
  * Shared with `compaction.ts` so the survival guard re-pins by the SAME rule.
@@ -34,16 +38,15 @@ export function isWorkingMemoryMessage(content: string | null | undefined): bool
34
38
  *
35
39
  * Failure-isolated (the `web-search` seam rule): a throwing/slow provider
36
40
  * degrades to "no refresh this turn" (keeps the prior slot), never breaks the
37
- * run. Early-returns when no provider is configured ⇒ byte-identical run path.
41
+ * run. With no provider or tool-owned slot, the history is left unchanged.
38
42
  */
39
43
  export async function refreshWorkingMemory(ctx: IterationContext): Promise<void> {
40
44
  const provider = ctx.workingMemoryProvider
41
45
  // What the tools pinned joins the slot beside what the host provides: a
42
46
  // pin exists to be in front of the model every iteration, and until this
43
47
  // the working state reached the history only through a compaction
44
- // summary. No provider and no pins leaves the history untouched.
48
+ // summary. When the final pin is removed, retire only a tool-owned slot.
45
49
  const pinned = ctx.workingStateManager ? renderPins(ctx.workingStateManager.getState()) : null
46
- if (!provider && !pinned) return
47
50
 
48
51
  let block = ''
49
52
  if (provider) {
@@ -80,17 +83,32 @@ export async function refreshWorkingMemory(ctx: IterationContext): Promise<void>
80
83
  }
81
84
  }
82
85
 
86
+ if (!provider && !pinned) {
87
+ if (!ctx.workingStateManager) return
88
+ const prior = msgs[idx]?.content
89
+ if (typeof prior !== 'string' || !prior.startsWith(TOOL_PINS_HEADER)) return
90
+ }
91
+
83
92
  if (!block.trim()) {
84
93
  // Empty block ⇒ remove the slot (byte-identical-when-empty).
85
- if (idx >= 0) msgs.splice(idx, 1)
94
+ if (idx >= 0) {
95
+ msgs.splice(idx, 1)
96
+ ctx.runMgr.clearLastPromptTokens?.()
97
+ }
86
98
  return
87
99
  }
88
100
 
89
- const wm = createSystemMessage(`${WORKING_MEMORY_HEADER}\n\n${block}`, 'ephemeral')
101
+ const header = provider ? WORKING_MEMORY_HEADER : TOOL_PINS_HEADER
102
+ const content = `${header}\n\n${block}`
103
+ if (idx >= 0 && msgs[idx]?.content === content) return
104
+ const wm = createSystemMessage(content, 'ephemeral')
90
105
  if (idx >= 0) {
91
106
  msgs[idx] = wm
92
107
  } else {
93
108
  // Insert as the LAST leading system message (after static + dynamic).
94
109
  msgs.splice(leadEnd, 0, wm)
95
110
  }
111
+ // The old provider reading measured a different prefix, and an insertion
112
+ // also moves its tail watermark. Re-estimate until the next request reports.
113
+ ctx.runMgr.clearLastPromptTokens?.()
96
114
  }
@@ -1,4 +1,8 @@
1
1
  import { type Span, SpanStatusCode } from '@opentelemetry/api'
2
+ import {
3
+ assertHostedWebSearchSupported,
4
+ assertNativeStructuredOutputSupported,
5
+ } from '../../../provider/capabilities.js'
2
6
  import { isProviderRequestError } from '../../../provider/errors.js'
3
7
  import { GENAI, NAMZU, chatSpanName, parentContext } from '../../../telemetry/attributes.js'
4
8
  import {
@@ -153,6 +157,8 @@ export async function* streamProviderTurn(
153
157
  readonly onAccepted: (identity: RequestImageIdentity) => Promise<void>
154
158
  },
155
159
  ): AsyncGenerator<RunEvent, StreamingTurnResult> {
160
+ assertNativeStructuredOutputSupported(provider, params)
161
+ assertHostedWebSearchSupported(provider, params)
156
162
  // The `chat {model}` span the GenAI conventions require. There was none:
157
163
  // `chatSpanName` existed with zero call sites, so a trace carried no LLM
158
164
  // latency at all and the token counts landed on the iteration span
@@ -338,6 +344,15 @@ export async function* streamProviderTurn(
338
344
  recordTimeToFirstToken(params.model, Date.now() - callStartedAt)
339
345
  }
340
346
 
347
+ if (chunk.delta.hostedTool) {
348
+ await emitEvent({
349
+ type: 'hosted_tool',
350
+ runId,
351
+ iteration,
352
+ tool: chunk.delta.hostedTool,
353
+ })
354
+ yield* drainPending()
355
+ }
341
356
  if (chunk.delta.citation) citations.push(chunk.delta.citation)
342
357
 
343
358
  const reasoning = chunk.delta.reasoning
@@ -0,0 +1,86 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { findRetainedIndices } from '../../compaction/retention.js'
3
+ import { estimateMessageTokens } from '../../compaction/token-estimate.js'
4
+ import { isClearedToolResult } from '../../compaction/tool-result-editing.js'
5
+ import type { Message, ToolMessage } from '../../types/message/index.js'
6
+ import type { ToolRegistryContract } from '../../types/tool/index.js'
7
+
8
+ /**
9
+ * Request-only exact observation masking. Every reference targets a full result
10
+ * in THIS projection. Recompute from canonical history, never from yesterday's
11
+ * mask, so removing a former representative cannot leave a dangling reference.
12
+ * No tool executions are skipped, and equal output is not a freshness claim.
13
+ */
14
+ export function projectObservationContext(
15
+ messages: Message[],
16
+ tools: Pick<ToolRegistryContract, 'get'>,
17
+ preserveToolResultsFrom: readonly string[] = [],
18
+ ): Message[] {
19
+ const calls = new Map<string, { name: string; arguments: string } | null>()
20
+ for (const message of messages) {
21
+ if (message.role !== 'assistant') continue
22
+ for (const call of message.toolCalls ?? []) {
23
+ // Ambiguous IDs cannot prove which observation belongs to which call.
24
+ if (calls.has(call.id)) calls.set(call.id, null)
25
+ else calls.set(call.id, call.metadata?.inputTruncated ? null : call.function)
26
+ }
27
+ }
28
+ const resultCounts = new Map<string, number>()
29
+ for (const message of messages) {
30
+ if (message.role === 'tool') {
31
+ resultCounts.set(message.toolCallId, (resultCounts.get(message.toolCallId) ?? 0) + 1)
32
+ }
33
+ }
34
+ const protectedIndices = findRetainedIndices(messages)
35
+ const representatives = new Map<string, ToolMessage>()
36
+ let projected: Message[] | undefined
37
+ for (let index = 0; index < messages.length; index++) {
38
+ const message = messages[index]
39
+ if (
40
+ !message ||
41
+ message.role !== 'tool' ||
42
+ message.isError ||
43
+ typeof message.content !== 'string' ||
44
+ message.content.length < 1024 ||
45
+ isClearedToolResult(message.content) ||
46
+ resultCounts.get(message.toolCallId) !== 1
47
+ )
48
+ continue
49
+ const call = calls.get(message.toolCallId)
50
+ if (!call || preserveToolResultsFrom.includes(call.name)) continue
51
+ const definition = tools.get(call.name)
52
+ if (!definition) continue
53
+ try {
54
+ const input = definition.inputSchema.safeParse(JSON.parse(call.arguments))
55
+ if (
56
+ !input.success ||
57
+ definition.isReadOnly?.(input.data) !== true ||
58
+ definition.isDestructive?.(input.data) === true
59
+ )
60
+ continue
61
+ } catch {
62
+ // Classification is advisory; invalid input or a broken custom predicate
63
+ // must leave evidence intact, not abort the request.
64
+ continue
65
+ }
66
+ // Exact arguments intentionally: equivalent JSON with different formatting
67
+ // is a missed optimization, not permission to merge different file ranges.
68
+ const key = createHash('sha256')
69
+ .update(JSON.stringify([call.name, call.arguments, message.content]))
70
+ .digest('hex')
71
+ const representative = representatives.get(key)
72
+ if (!representative) {
73
+ representatives.set(key, message)
74
+ continue
75
+ }
76
+ if (protectedIndices.has(index)) continue
77
+ const replacement: ToolMessage = {
78
+ ...message,
79
+ content: `[Duplicate observation: this call returned exactly the same text as tool result ${JSON.stringify(representative.toolCallId)}, whose full content remains in this request. Both calls occurred. This is historical evidence, not a claim that external state is still unchanged.]`,
80
+ }
81
+ if (estimateMessageTokens(replacement) >= estimateMessageTokens(message)) continue
82
+ projected ??= [...messages]
83
+ projected[index] = replacement
84
+ }
85
+ return projected ?? messages
86
+ }
@@ -0,0 +1,103 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { Message, MessageRole } from '../../types/message/index.js'
3
+
4
+ /** A content block present at the SDK's provider-input boundary, not a file freshness claim. */
5
+ export interface RequestContextPart {
6
+ readonly messageIndex: number
7
+ readonly partIndex: number
8
+ readonly role: MessageRole
9
+ readonly kind: 'text' | 'image' | 'document' | 'stored' | 'tool-call'
10
+ readonly digest: string
11
+ readonly toolCallId?: string
12
+ readonly isError?: boolean
13
+ }
14
+
15
+ export interface RequestContextSnapshot {
16
+ readonly boundary: 'provider-input'
17
+ readonly parts: readonly RequestContextPart[]
18
+ }
19
+
20
+ export interface RequestContextChange {
21
+ /** Parts from the earlier snapshot no longer present, including replaced content. */
22
+ readonly removed: readonly RequestContextPart[]
23
+ /** Parts in the new snapshot not present before. */
24
+ readonly added: readonly RequestContextPart[]
25
+ }
26
+
27
+ function canonicalJson(value: unknown): string {
28
+ return JSON.stringify(value, (_key, item: unknown) => {
29
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return item
30
+ return Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
31
+ })
32
+ }
33
+
34
+ /**
35
+ * Inspect supplied messages after compaction and request projection. No content
36
+ * is retained in the snapshot. A digest identifies exact blocks, not semantic
37
+ * knowledge, token counts, file versions or provider-private reasoning replay.
38
+ */
39
+ export function snapshotRequestContext(messages: readonly Message[]): RequestContextSnapshot {
40
+ const parts: RequestContextPart[] = []
41
+ for (const [messageIndex, message] of messages.entries()) {
42
+ let partIndex = 0
43
+ const add = (kind: RequestContextPart['kind'], payload: unknown, toolCallId?: string) => {
44
+ parts.push(
45
+ Object.freeze({
46
+ messageIndex,
47
+ partIndex: partIndex++,
48
+ role: message.role,
49
+ kind,
50
+ digest: createHash('sha256').update(canonicalJson(payload)).digest('hex'),
51
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
52
+ ...(message.role === 'tool' ? { isError: message.isError === true } : {}),
53
+ }),
54
+ )
55
+ }
56
+ const callId = message.role === 'tool' ? message.toolCallId : undefined
57
+ if (typeof message.content === 'string') add('text', message.content, callId)
58
+ else if (Array.isArray(message.content)) {
59
+ for (const block of message.content) {
60
+ if (block.type === 'text') add('text', block.text, callId)
61
+ else add(block.type, block, callId)
62
+ }
63
+ }
64
+ if (message.role === 'user') {
65
+ for (const attachment of message.attachments ?? []) {
66
+ add(attachment.type ?? 'image', attachment)
67
+ }
68
+ }
69
+ if (message.role === 'assistant') {
70
+ for (const call of message.toolCalls ?? []) {
71
+ add('tool-call', [call.function.name, call.function.arguments], call.id)
72
+ }
73
+ }
74
+ }
75
+ return Object.freeze({ boundary: 'provider-input', parts: Object.freeze(parts) })
76
+ }
77
+
78
+ const key = (part: RequestContextPart): string =>
79
+ JSON.stringify([part.role, part.kind, part.toolCallId, part.isError, part.digest])
80
+
81
+ /** Compare occurrences, not sets: removing one of two identical blocks is a removal. */
82
+ export function diffRequestContext(
83
+ previous: RequestContextSnapshot,
84
+ next: RequestContextSnapshot,
85
+ ): RequestContextChange {
86
+ const unmatched = new Map<string, RequestContextPart[]>()
87
+ for (const part of previous.parts) {
88
+ const identity = key(part)
89
+ const occurrences = unmatched.get(identity) ?? []
90
+ occurrences.push(part)
91
+ unmatched.set(identity, occurrences)
92
+ }
93
+ const added: RequestContextPart[] = []
94
+ for (const part of next.parts) {
95
+ const occurrences = unmatched.get(key(part))
96
+ if (occurrences?.length) occurrences.pop()
97
+ else added.push(part)
98
+ }
99
+ const removed = [...unmatched.values()]
100
+ .flat()
101
+ .sort((a, b) => a.messageIndex - b.messageIndex || a.partIndex - b.partIndex)
102
+ return Object.freeze({ removed: Object.freeze(removed), added: Object.freeze(added) })
103
+ }
@@ -45,20 +45,25 @@ export interface RequestImageIdentity {
45
45
  const userMarker = (kind: RichKind): string =>
46
46
  `[${kind} omitted from this model request to keep the accumulated rich-content payload within its configured size limit; attach it again in a new message if it is still needed.]`
47
47
 
48
+ // Losing an observation does not undo the action that produced it. This
49
+ // projection knows the result bytes, not whether repeating its tool is safe.
50
+ const toolRecovery =
51
+ 'The original result is retained in conversation history, but this content is not available in the current model request. Recover it from an available saved artifact or a read-only observation if needed. Do not repeat a state-changing action merely to recover its output.'
52
+
48
53
  const toolMarker = (kind: RichKind): string =>
49
- `[${kind} omitted from this model request to keep the accumulated rich-content payload within its configured size limit; call the producing tool again if it is still needed.]`
54
+ `[${kind} omitted from this model request to keep the accumulated rich-content payload within its configured size limit. ${toolRecovery}]`
50
55
 
51
56
  const rejectedUserImageMarker = (): string =>
52
57
  '[image omitted from this model request because the provider rejected this image; attach a corrected image in a new message if it is still needed.]'
53
58
 
54
59
  const rejectedToolImageMarker = (): string =>
55
- '[image omitted from this model request because the provider rejected this image; call the producing tool again after correcting its image source if it is still needed.]'
60
+ `[image omitted from this model request because the provider rejected this image. ${toolRecovery} Correct the image source before presenting it again.]`
56
61
 
57
62
  const invalidUserImageMarker = (): string =>
58
63
  '[image omitted from this model request because its encoded bytes are not a complete supported raster matching the declared media type; attach a corrected image in a new message if it is still needed.]'
59
64
 
60
65
  const invalidToolImageMarker = (): string =>
61
- '[image omitted from this model request because the producing tool returned encoded bytes that are not a complete supported raster matching the declared media type; call the tool again after correcting its image source if it is still needed.]'
66
+ `[image omitted from this model request because the producing tool returned encoded bytes that are not a complete supported raster matching the declared media type. ${toolRecovery} Correct the image source before presenting it again.]`
62
67
 
63
68
  function assertInlineAttachment(
64
69
  attachment: MessageAttachment,
@@ -25,6 +25,7 @@ import type { ToolRegistry } from '../../registry/tool/execute.js'
25
25
  import { isTrustedReadOnly } from '../../tools/trusted-read-only.js'
26
26
  import type { HITLResumeDecision, ResumeHandler, ToolCallSummary } from '../../types/hitl/index.js'
27
27
  import type { ApprovalPolicy } from '../../types/hitl/policy.js'
28
+ import type { RunId } from '../../types/ids/index.js'
28
29
  import { PLAN_MODE_REFUSAL } from '../../types/permission/index.js'
29
30
 
30
31
  export type ReviewMode =
@@ -141,6 +142,8 @@ export function batchNeedsReview(
141
142
 
142
143
  /** The batch a person is asked about. */
143
144
  export interface ToolReviewRequest {
145
+ /** Originating run, preserved by createReviewHandler for host attribution. */
146
+ readonly runId?: RunId
144
147
  readonly toolCalls: readonly ToolCallSummary[]
145
148
  }
146
149
 
@@ -204,7 +207,10 @@ export function createReviewHandler(options: ReviewPolicyOptions = {}): ResumeHa
204
207
  if (mode === 'auto' || !prompt || remembered.all) {
205
208
  return { action: 'approve_tools' }
206
209
  }
207
- const answer = await prompt({ toolCalls: request.toolCalls })
210
+ const answer = await prompt({
211
+ runId: request.runId,
212
+ toolCalls: request.toolCalls,
213
+ })
208
214
  switch (answer.kind) {
209
215
  case 'approve':
210
216
  return { action: 'approve_tools' }
@@ -1,4 +1,15 @@
1
- import type { Message } from '../../types/message/index.js'
1
+ import type { Message, UserMessage } from '../../types/message/index.js'
2
+
3
+ /** User-role runtime reports are context, not new operator intent. */
4
+ export function isOperatorUserMessage(message: Message): message is UserMessage {
5
+ if (message.role !== 'user') return false
6
+ const source = message.source
7
+ return (
8
+ !source ||
9
+ source.type === 'goal-round' ||
10
+ (source.type === 'runtime-context' && source.kind === 'steering')
11
+ )
12
+ }
2
13
 
3
14
  /**
4
15
  * Guidance a host hands to a turn that is already running.
@@ -134,6 +145,8 @@ export function formatSteeringNote(text: string): string {
134
145
  export function attachSteering(
135
146
  messages: readonly Message[],
136
147
  channel: SteeringChannel | undefined,
148
+ /** Receives accepted operator text, never inferred from a tool's output. */
149
+ onDelivered?: (text: string) => void,
137
150
  ): readonly Message[] {
138
151
  if (!channel?.pending) return messages
139
152
 
@@ -162,6 +175,10 @@ export function attachSteering(
162
175
  }
163
176
 
164
177
  const next = [...messages]
165
- next[lastToolIndex] = { ...target, content: target.content + formatSteeringNote(guidance) }
178
+ next[lastToolIndex] = {
179
+ ...target,
180
+ content: target.content + formatSteeringNote(guidance),
181
+ }
182
+ onDelivered?.(guidance)
166
183
  return next
167
184
  }