@zvada/agent-server 0.3.22 → 0.3.23

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 (348) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/dist/types/accounts/chatgpt.d.ts +1 -1
  3. package/dist/types/accounts/chatgpt.d.ts.map +1 -1
  4. package/dist/types/accounts/http.d.ts +2 -4
  5. package/dist/types/accounts/http.d.ts.map +1 -1
  6. package/dist/types/client/client.d.ts +37 -11
  7. package/dist/types/client/client.d.ts.map +1 -1
  8. package/dist/types/client/connection.d.ts +64 -13
  9. package/dist/types/client/connection.d.ts.map +1 -1
  10. package/dist/types/client/index.d.ts +1 -1
  11. package/dist/types/client/index.d.ts.map +1 -1
  12. package/dist/types/client/logins.d.ts +2 -1
  13. package/dist/types/client/logins.d.ts.map +1 -1
  14. package/dist/types/client/streams.d.ts +9 -3
  15. package/dist/types/client/streams.d.ts.map +1 -1
  16. package/dist/types/client/turns.d.ts +1 -1
  17. package/dist/types/client/turns.d.ts.map +1 -1
  18. package/dist/types/core/agents/acp/acp-agent.d.ts +34 -1
  19. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  20. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  21. package/dist/types/core/agents/acp/client.d.ts +12 -3
  22. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  23. package/dist/types/core/agents/acp/mappings.d.ts +8 -2
  24. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  25. package/dist/types/core/agents/base.d.ts +22 -8
  26. package/dist/types/core/agents/base.d.ts.map +1 -1
  27. package/dist/types/core/agents/claude-code/adapter.d.ts +7 -0
  28. package/dist/types/core/agents/claude-code/adapter.d.ts.map +1 -1
  29. package/dist/types/core/agents/claude-code/approvals.d.ts +4 -1
  30. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  31. package/dist/types/core/agents/claude-code/claude-agent.d.ts +16 -5
  32. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  33. package/dist/types/core/agents/claude-code/events.d.ts +9 -1
  34. package/dist/types/core/agents/claude-code/events.d.ts.map +1 -1
  35. package/dist/types/core/agents/claude-code/login.d.ts +4 -1
  36. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  37. package/dist/types/core/agents/claude-code/mcp.d.ts +21 -7
  38. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -1
  39. package/dist/types/core/agents/claude-code/models.d.ts +5 -1
  40. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -1
  41. package/dist/types/core/agents/claude-code/options.d.ts +10 -4
  42. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  43. package/dist/types/core/agents/claude-code/outcome.d.ts +3 -5
  44. package/dist/types/core/agents/claude-code/outcome.d.ts.map +1 -1
  45. package/dist/types/core/agents/claude-code/results.d.ts +16 -0
  46. package/dist/types/core/agents/claude-code/results.d.ts.map +1 -0
  47. package/dist/types/core/agents/claude-code/sdk-pair.d.ts +13 -0
  48. package/dist/types/core/agents/claude-code/sdk-pair.d.ts.map +1 -0
  49. package/dist/types/core/agents/claude-code/session.d.ts +50 -12
  50. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  51. package/dist/types/core/agents/claude-code/spend.d.ts +2 -1
  52. package/dist/types/core/agents/claude-code/spend.d.ts.map +1 -1
  53. package/dist/types/core/agents/claude-code/tools.d.ts +26 -3
  54. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -1
  55. package/dist/types/core/agents/codex-app-server/adapter.d.ts +2 -2
  56. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -1
  57. package/dist/types/core/agents/codex-app-server/client.d.ts +12 -2
  58. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  59. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +58 -13
  60. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  61. package/dist/types/core/agents/codex-app-server/commands.d.ts +2 -2
  62. package/dist/types/core/agents/codex-app-server/commands.d.ts.map +1 -1
  63. package/dist/types/core/agents/codex-app-server/credentials.d.ts +5 -1
  64. package/dist/types/core/agents/codex-app-server/credentials.d.ts.map +1 -1
  65. package/dist/types/core/agents/codex-app-server/effort.d.ts +2 -1
  66. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -1
  67. package/dist/types/core/agents/codex-app-server/homes.d.ts +19 -0
  68. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  69. package/dist/types/core/agents/codex-app-server/items.d.ts +27 -2
  70. package/dist/types/core/agents/codex-app-server/items.d.ts.map +1 -1
  71. package/dist/types/core/agents/codex-app-server/login.d.ts +4 -1
  72. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  73. package/dist/types/core/agents/codex-app-server/mcp.d.ts +15 -30
  74. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  75. package/dist/types/core/agents/codex-app-server/models.d.ts +3 -10
  76. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -1
  77. package/dist/types/core/agents/codex-app-server/options.d.ts +27 -4
  78. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  79. package/dist/types/core/agents/codex-app-server/plan-approval.d.ts +2 -1
  80. package/dist/types/core/agents/codex-app-server/plan-approval.d.ts.map +1 -1
  81. package/dist/types/core/agents/codex-app-server/protocol.d.ts +16 -3
  82. package/dist/types/core/agents/codex-app-server/protocol.d.ts.map +1 -1
  83. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  84. package/dist/types/core/agents/codex-app-server/session.d.ts +68 -40
  85. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  86. package/dist/types/core/agents/codex-app-server/subagents.d.ts +9 -4
  87. package/dist/types/core/agents/codex-app-server/subagents.d.ts.map +1 -1
  88. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts +3 -2
  89. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -1
  90. package/dist/types/core/agents/codex-app-server/turn-items.d.ts +2 -1
  91. package/dist/types/core/agents/codex-app-server/turn-items.d.ts.map +1 -1
  92. package/dist/types/core/agents/codex-app-server/turn.d.ts +31 -8
  93. package/dist/types/core/agents/codex-app-server/turn.d.ts.map +1 -1
  94. package/dist/types/core/agents/codex-app-server/user-login.d.ts +28 -0
  95. package/dist/types/core/agents/codex-app-server/user-login.d.ts.map +1 -0
  96. package/dist/types/core/agents/credentials.d.ts +3 -1
  97. package/dist/types/core/agents/credentials.d.ts.map +1 -1
  98. package/dist/types/core/agents/diffs.d.ts +9 -0
  99. package/dist/types/core/agents/diffs.d.ts.map +1 -0
  100. package/dist/types/core/agents/elicitation.d.ts +3 -2
  101. package/dist/types/core/agents/elicitation.d.ts.map +1 -1
  102. package/dist/types/core/agents/login.d.ts +6 -0
  103. package/dist/types/core/agents/login.d.ts.map +1 -1
  104. package/dist/types/core/agents/mcp-config.d.ts +0 -4
  105. package/dist/types/core/agents/mcp-config.d.ts.map +1 -1
  106. package/dist/types/core/agents/process-pool.d.ts +193 -0
  107. package/dist/types/core/agents/process-pool.d.ts.map +1 -0
  108. package/dist/types/core/agents/scripted/adapter.d.ts +68 -0
  109. package/dist/types/core/agents/scripted/adapter.d.ts.map +1 -0
  110. package/dist/types/core/agents/scripted/mcp-call.d.ts +56 -0
  111. package/dist/types/core/agents/scripted/mcp-call.d.ts.map +1 -0
  112. package/dist/types/core/agents/scripted/scripted-agent.d.ts +73 -0
  113. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -0
  114. package/dist/types/core/agents/scripted/scripts.d.ts +29 -0
  115. package/dist/types/core/agents/scripted/scripts.d.ts.map +1 -0
  116. package/dist/types/core/agents/scripted/steps.d.ts +132 -0
  117. package/dist/types/core/agents/scripted/steps.d.ts.map +1 -0
  118. package/dist/types/core/agents/session-agent.d.ts +49 -6
  119. package/dist/types/core/agents/session-agent.d.ts.map +1 -1
  120. package/dist/types/core/diagnostics.d.ts +4 -1
  121. package/dist/types/core/diagnostics.d.ts.map +1 -1
  122. package/dist/types/core/index.d.ts +5 -0
  123. package/dist/types/core/index.d.ts.map +1 -1
  124. package/dist/types/core/presets.d.ts +32 -6
  125. package/dist/types/core/presets.d.ts.map +1 -1
  126. package/dist/types/core/processes/lifeline.d.ts +0 -20
  127. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  128. package/dist/types/core/provision/index.d.ts +2 -2
  129. package/dist/types/core/provision/index.d.ts.map +1 -1
  130. package/dist/types/core/provision/install-build.d.ts +2 -1
  131. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  132. package/dist/types/core/provision/npm.d.ts +20 -8
  133. package/dist/types/core/provision/npm.d.ts.map +1 -1
  134. package/dist/types/core/provision/provisioner.d.ts +4 -1
  135. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  136. package/dist/types/core/provision/tools.d.ts +2 -1
  137. package/dist/types/core/provision/tools.d.ts.map +1 -1
  138. package/dist/types/core/runtime/agent-runtime.d.ts +16 -8
  139. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  140. package/dist/types/core/runtime/event-processor.d.ts +5 -1
  141. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  142. package/dist/types/core/runtime/harness-clis.d.ts +9 -0
  143. package/dist/types/core/runtime/harness-clis.d.ts.map +1 -1
  144. package/dist/types/core/runtime/harness-logins.d.ts +33 -5
  145. package/dist/types/core/runtime/harness-logins.d.ts.map +1 -1
  146. package/dist/types/core/runtime/model-lists.d.ts +2 -0
  147. package/dist/types/core/runtime/model-lists.d.ts.map +1 -1
  148. package/dist/types/core/runtime/permission-policy.d.ts +5 -3
  149. package/dist/types/core/runtime/permission-policy.d.ts.map +1 -1
  150. package/dist/types/core/runtime/request-broker.d.ts +2 -1
  151. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  152. package/dist/types/core/runtime/turn.d.ts +12 -1
  153. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  154. package/dist/types/core/utils/deadline.d.ts +6 -0
  155. package/dist/types/core/utils/deadline.d.ts.map +1 -1
  156. package/dist/types/core/utils/errors.d.ts +7 -1
  157. package/dist/types/core/utils/errors.d.ts.map +1 -1
  158. package/dist/types/operator/operator.d.ts.map +1 -1
  159. package/dist/types/operator/render.d.ts +6 -4
  160. package/dist/types/operator/render.d.ts.map +1 -1
  161. package/dist/types/protocol/auth.d.ts +54 -24
  162. package/dist/types/protocol/auth.d.ts.map +1 -1
  163. package/dist/types/protocol/clis.d.ts +14 -7
  164. package/dist/types/protocol/clis.d.ts.map +1 -1
  165. package/dist/types/protocol/config.d.ts +2 -0
  166. package/dist/types/protocol/config.d.ts.map +1 -1
  167. package/dist/types/protocol/conversation.d.ts +40 -3
  168. package/dist/types/protocol/conversation.d.ts.map +1 -1
  169. package/dist/types/protocol/credentials.d.ts +7 -0
  170. package/dist/types/protocol/credentials.d.ts.map +1 -1
  171. package/dist/types/protocol/execution.d.ts +2 -1
  172. package/dist/types/protocol/execution.d.ts.map +1 -1
  173. package/dist/types/protocol/factories.d.ts +12 -2
  174. package/dist/types/protocol/factories.d.ts.map +1 -1
  175. package/dist/types/protocol/harness.d.ts +6 -2
  176. package/dist/types/protocol/harness.d.ts.map +1 -1
  177. package/dist/types/protocol/history.d.ts +19 -0
  178. package/dist/types/protocol/history.d.ts.map +1 -1
  179. package/dist/types/protocol/lifecycle.d.ts +47 -8
  180. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  181. package/dist/types/protocol/model-catalog.d.ts.map +1 -1
  182. package/dist/types/protocol/models.d.ts +3 -0
  183. package/dist/types/protocol/models.d.ts.map +1 -1
  184. package/dist/types/protocol/parts.d.ts +14 -0
  185. package/dist/types/protocol/parts.d.ts.map +1 -1
  186. package/dist/types/protocol/tool-state.d.ts +12 -0
  187. package/dist/types/protocol/tool-state.d.ts.map +1 -1
  188. package/dist/types/protocol/wire-api.d.ts +129 -23
  189. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  190. package/dist/types/protocol/wire.d.ts +70 -10
  191. package/dist/types/protocol/wire.d.ts.map +1 -1
  192. package/dist/types/server/acp/binding.d.ts +6 -1
  193. package/dist/types/server/acp/binding.d.ts.map +1 -1
  194. package/dist/types/server/acp/translate.d.ts +33 -7
  195. package/dist/types/server/acp/translate.d.ts.map +1 -1
  196. package/dist/types/server/agent-server.d.ts +6 -0
  197. package/dist/types/server/agent-server.d.ts.map +1 -1
  198. package/dist/types/server/feedback.d.ts +2 -1
  199. package/dist/types/server/feedback.d.ts.map +1 -1
  200. package/dist/types/server/install.d.ts +11 -0
  201. package/dist/types/server/install.d.ts.map +1 -1
  202. package/dist/types/server/session-gate.d.ts +2 -1
  203. package/dist/types/server/session-gate.d.ts.map +1 -1
  204. package/dist/types/server/session-store.d.ts +1 -0
  205. package/dist/types/server/session-store.d.ts.map +1 -1
  206. package/dist/types/server/subscriptions.d.ts +2 -1
  207. package/dist/types/server/subscriptions.d.ts.map +1 -1
  208. package/dist/types/server/transports.d.ts.map +1 -1
  209. package/dist/types/sync/fit.d.ts +8 -7
  210. package/dist/types/sync/fit.d.ts.map +1 -1
  211. package/dist/types/sync/history-sqlite.d.ts.map +1 -1
  212. package/dist/types/sync/index.d.ts +1 -0
  213. package/dist/types/sync/index.d.ts.map +1 -1
  214. package/dist/types/sync/journal-sqlite.d.ts +2 -1
  215. package/dist/types/sync/journal-sqlite.d.ts.map +1 -1
  216. package/dist/types/sync/journal.d.ts +11 -3
  217. package/dist/types/sync/journal.d.ts.map +1 -1
  218. package/dist/types/sync/projection.d.ts +6 -0
  219. package/dist/types/sync/projection.d.ts.map +1 -1
  220. package/dist/types/sync/recovery.d.ts +2 -1
  221. package/dist/types/sync/recovery.d.ts.map +1 -1
  222. package/dist/types/sync/schema.d.ts +10 -0
  223. package/dist/types/sync/schema.d.ts.map +1 -1
  224. package/dist/types/sync/sql.d.ts +2 -1
  225. package/dist/types/sync/sql.d.ts.map +1 -1
  226. package/docs/consuming.md +278 -28
  227. package/docs/deploy.md +36 -8
  228. package/docs/durable-sessions.md +35 -5
  229. package/docs/harnesses.md +385 -24
  230. package/package.json +6 -1
  231. package/src/accounts/chatgpt.ts +2 -2
  232. package/src/accounts/http.ts +2 -16
  233. package/src/client/client.ts +92 -31
  234. package/src/client/connection.ts +103 -22
  235. package/src/client/index.ts +1 -0
  236. package/src/client/logins.ts +1 -1
  237. package/src/client/streams.ts +12 -4
  238. package/src/client/turns.ts +1 -1
  239. package/src/core/agents/acp/acp-agent.ts +181 -52
  240. package/src/core/agents/acp/adapter.ts +9 -1
  241. package/src/core/agents/acp/client.ts +16 -4
  242. package/src/core/agents/acp/mappings.ts +27 -0
  243. package/src/core/agents/base.ts +25 -10
  244. package/src/core/agents/claude-code/adapter.ts +47 -17
  245. package/src/core/agents/claude-code/approvals.ts +6 -5
  246. package/src/core/agents/claude-code/claude-agent.ts +60 -30
  247. package/src/core/agents/claude-code/events.ts +11 -1
  248. package/src/core/agents/claude-code/login.ts +14 -2
  249. package/src/core/agents/claude-code/mcp.ts +31 -15
  250. package/src/core/agents/claude-code/models.ts +7 -2
  251. package/src/core/agents/claude-code/options.ts +11 -3
  252. package/src/core/agents/claude-code/outcome.ts +10 -2
  253. package/src/core/agents/claude-code/results.ts +73 -0
  254. package/src/core/agents/claude-code/sdk-pair.ts +66 -0
  255. package/src/core/agents/claude-code/session.ts +166 -37
  256. package/src/core/agents/claude-code/spend.ts +1 -1
  257. package/src/core/agents/claude-code/tools.ts +108 -12
  258. package/src/core/agents/codex-app-server/adapter.ts +37 -12
  259. package/src/core/agents/codex-app-server/client.ts +37 -8
  260. package/src/core/agents/codex-app-server/codex-agent.ts +115 -50
  261. package/src/core/agents/codex-app-server/commands.ts +2 -2
  262. package/src/core/agents/codex-app-server/credentials.ts +10 -5
  263. package/src/core/agents/codex-app-server/effort.ts +1 -1
  264. package/src/core/agents/codex-app-server/homes.ts +43 -1
  265. package/src/core/agents/codex-app-server/items.ts +219 -31
  266. package/src/core/agents/codex-app-server/login.ts +14 -2
  267. package/src/core/agents/codex-app-server/mcp.ts +47 -32
  268. package/src/core/agents/codex-app-server/models.ts +9 -8
  269. package/src/core/agents/codex-app-server/options.ts +69 -10
  270. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  271. package/src/core/agents/codex-app-server/protocol.ts +14 -4
  272. package/src/core/agents/codex-app-server/requests.ts +14 -6
  273. package/src/core/agents/codex-app-server/session.ts +151 -113
  274. package/src/core/agents/codex-app-server/subagents.ts +21 -14
  275. package/src/core/agents/codex-app-server/thread-settings.ts +18 -8
  276. package/src/core/agents/codex-app-server/turn-items.ts +1 -1
  277. package/src/core/agents/codex-app-server/turn.ts +79 -32
  278. package/src/core/agents/codex-app-server/user-login.ts +107 -0
  279. package/src/core/agents/credentials.ts +5 -2
  280. package/src/core/agents/diffs.ts +25 -0
  281. package/src/core/agents/elicitation.ts +2 -2
  282. package/src/core/agents/login.ts +6 -0
  283. package/src/core/agents/mcp-config.ts +2 -2
  284. package/src/core/agents/process-pool.ts +432 -0
  285. package/src/core/agents/scripted/adapter.ts +142 -0
  286. package/src/core/agents/scripted/mcp-call.ts +134 -0
  287. package/src/core/agents/scripted/scripted-agent.ts +418 -0
  288. package/src/core/agents/scripted/scripts.ts +171 -0
  289. package/src/core/agents/scripted/steps.ts +127 -0
  290. package/src/core/agents/session-agent.ts +105 -8
  291. package/src/core/diagnostics.ts +9 -1
  292. package/src/core/index.ts +11 -0
  293. package/src/core/presets.ts +99 -14
  294. package/src/core/processes/lifeline.ts +99 -25
  295. package/src/core/provision/index.ts +1 -2
  296. package/src/core/provision/install-build.ts +4 -1
  297. package/src/core/provision/npm.ts +309 -97
  298. package/src/core/provision/provisioner.ts +22 -8
  299. package/src/core/provision/tools.ts +44 -19
  300. package/src/core/runtime/agent-runtime.ts +48 -18
  301. package/src/core/runtime/event-processor.ts +18 -2
  302. package/src/core/runtime/harness-clis.ts +36 -1
  303. package/src/core/runtime/harness-logins.ts +82 -31
  304. package/src/core/runtime/model-lists.ts +1 -1
  305. package/src/core/runtime/permission-policy.ts +4 -3
  306. package/src/core/runtime/request-broker.ts +1 -1
  307. package/src/core/runtime/turn.ts +51 -3
  308. package/src/core/utils/deadline.ts +23 -0
  309. package/src/core/utils/errors.ts +11 -4
  310. package/src/operator/operator.ts +8 -4
  311. package/src/operator/render.ts +46 -8
  312. package/src/protocol/auth.ts +30 -23
  313. package/src/protocol/clis.ts +12 -4
  314. package/src/protocol/credentials.ts +19 -0
  315. package/src/protocol/execution.ts +5 -0
  316. package/src/protocol/factories.ts +25 -3
  317. package/src/protocol/harness.ts +11 -1
  318. package/src/protocol/history.ts +20 -0
  319. package/src/protocol/lifecycle.ts +10 -1
  320. package/src/protocol/model-catalog.ts +19 -8
  321. package/src/protocol/parts.ts +12 -1
  322. package/src/protocol/tool-state.ts +14 -1
  323. package/src/protocol/wire.ts +14 -0
  324. package/src/server/acp/binding.ts +113 -23
  325. package/src/server/acp/translate.ts +161 -8
  326. package/src/server/agent-server.ts +10 -1
  327. package/src/server/bin.ts +83 -9
  328. package/src/server/feedback.ts +1 -1
  329. package/src/server/install.ts +82 -4
  330. package/src/server/session-gate.ts +1 -1
  331. package/src/server/session-store.ts +5 -1
  332. package/src/server/subscriptions.ts +1 -1
  333. package/src/server/transports.ts +14 -0
  334. package/src/sync/fit.ts +115 -28
  335. package/src/sync/history-sqlite.ts +6 -2
  336. package/src/sync/index.ts +1 -0
  337. package/src/sync/journal-sqlite.ts +20 -2
  338. package/src/sync/journal.ts +10 -2
  339. package/src/sync/projection.ts +10 -0
  340. package/src/sync/recovery.ts +11 -4
  341. package/src/sync/schema.ts +7 -5
  342. package/src/sync/sql.ts +1 -1
  343. package/dist/types/core/agents/claude-code/session-pool.d.ts +0 -36
  344. package/dist/types/core/agents/claude-code/session-pool.d.ts.map +0 -1
  345. package/dist/types/core/agents/session-pool.d.ts +0 -41
  346. package/dist/types/core/agents/session-pool.d.ts.map +0 -1
  347. package/src/core/agents/claude-code/session-pool.ts +0 -136
  348. package/src/core/agents/session-pool.ts +0 -111
package/src/server/bin.ts CHANGED
@@ -8,7 +8,10 @@
8
8
  // # (with $AGENT_SERVER_DIAL_TOKEN as its bearer token)
9
9
  // agent-server --harness a,b # restrict registered harnesses
10
10
  // agent-server --acp-agent "npx -y pi-acp" # enable the acp harness
11
+ // agent-server --script turns.jsonl # the scripted harness plays this script
12
+ // agent-server --script turns.jsonl --script-position at.json # and goes on after a restart
11
13
  // agent-server --acp --harness claude-code # BE an ACP agent on stdio (for Zed etc.)
14
+ // agent-server --acp --harness codex-app-server --model gpt-6-luna --thinking low
12
15
  // agent-server --buffer 8192 # replay buffer size per session
13
16
  // agent-server --inherit-config none # a turn loads no ambient settings, MCP, hooks, memory
14
17
  // agent-server install # prefetch the pinned agent CLIs
@@ -22,15 +25,18 @@ import {
22
25
  type CredentialSource,
23
26
  type InheritConfig,
24
27
  type ProvisionMode,
28
+ type ScriptSource,
25
29
  createAgentRuntime,
26
30
  credentialsFromUrl,
27
31
  isInheritConfig,
28
32
  resolveAcpLaunch,
29
33
  resolveHarnessName,
34
+ scriptedFile,
30
35
  } from "../core/index.ts";
36
+ import { THINKING_LEVELS, type ThinkingLevel, isThinkingLevel } from "../protocol/index.ts";
31
37
  import { AgentServer } from "./agent-server.ts";
32
38
  import { runFeedbackCommand } from "./feedback.ts";
33
- import { runInstall } from "./install.ts";
39
+ import { installedLine, nothingToInstall, runInstall, toolsFor } from "./install.ts";
34
40
  import { takeSecrets } from "./secrets.ts";
35
41
  import {
36
42
  type ListenOptions,
@@ -55,10 +61,17 @@ interface Args {
55
61
  dialUrl?: string;
56
62
  harnesses?: string[];
57
63
  acpAgent?: string;
64
+ /** --script: the JSONL file the scripted harness plays. */
65
+ script?: string;
66
+ /** --script-position: where the script's position is kept across restarts. */
67
+ scriptPosition?: string;
58
68
  bufferSize?: number;
59
69
  journalPath?: string;
60
70
  provisionMode?: ProvisionMode;
61
71
  inheritConfig?: InheritConfig;
72
+ /** --acp: the model and thinking level of every turn, the operator's alone. */
73
+ model?: string;
74
+ thinking?: ThinkingLevel;
62
75
  /** A product's credential endpoint, asked before each turn (LLP 0012). */
63
76
  credentialsUrl?: string;
64
77
  /** install: the platforms to stage, the folder to stage them into, and whether to prune. */
@@ -74,6 +87,9 @@ function usage(exitCode: number): never {
74
87
  "",
75
88
  " --stdio serve NDJSON JSON-RPC on stdio (the default)",
76
89
  " --acp speak ACP v1 on stdio instead (be the agent)",
90
+ " --model <id> every turn runs on this model (default: the harness's own)",
91
+ ` --thinking <level> and at this thinking level (${THINKING_LEVELS.join(", ")});`,
92
+ " the operator's choice: an ACP client cannot change either",
77
93
  " install download the pinned agent CLIs into the managed cache",
78
94
  " (always downloads — run at image build time to erase",
79
95
  " sandbox cold starts; --provision applies to serving only)",
@@ -95,6 +111,11 @@ function usage(exitCode: number): never {
95
111
  " $AGENT_SERVER_DIAL_TOKEN, never argv or the URL",
96
112
  " --harness <a,b> restrict harnesses (default: all installed)",
97
113
  " --acp-agent <spec> ACP agent: known name (pi|gemini) or launch command",
114
+ " --script <file> the scripted harness plays this JSONL script, one step a",
115
+ " line (its only harness unless --harness names others);",
116
+ " one turn plays at a time, from the start at each start",
117
+ " --script-position <file> keep the script's position here, so a restarted",
118
+ " server goes on where the last one stopped",
98
119
  " --provision <mode> CLI provisioning: auto | pinned | system (default auto)",
99
120
  " --inherit-config <level> what a turn loads by itself (settings, MCP servers, hooks,",
100
121
  " memory): all, the user's and the repository's (the default),",
@@ -145,8 +166,12 @@ const VALUE_OPTIONS = new Set([
145
166
  "--dial",
146
167
  "--harness",
147
168
  "--acp-agent",
169
+ "--script",
170
+ "--script-position",
148
171
  "--provision",
149
172
  "--inherit-config",
173
+ "--model",
174
+ "--thinking",
150
175
  "--credentials-url",
151
176
  "--journal",
152
177
  "--buffer",
@@ -192,6 +217,12 @@ function parseArgs(argv: string[]): Args {
192
217
  if (spec === undefined || !spec.trim() || spec.startsWith("-"))
193
218
  fail("--acp-agent needs a known agent name (pi, gemini) or a launch command");
194
219
  args.acpAgent = spec;
220
+ } else if (arg === "--script") {
221
+ args.script = next();
222
+ if (!args.script) fail("--script needs a file path");
223
+ } else if (arg === "--script-position") {
224
+ args.scriptPosition = next();
225
+ if (!args.scriptPosition) fail("--script-position needs a file path");
195
226
  } else if (arg === "--provision") {
196
227
  const mode = next();
197
228
  if (mode !== "auto" && mode !== "pinned" && mode !== "system")
@@ -201,6 +232,16 @@ function parseArgs(argv: string[]): Args {
201
232
  const level = next();
202
233
  if (!isInheritConfig(level)) fail(`--inherit-config ${level}: use all, project or none`);
203
234
  args.inheritConfig = level;
235
+ } else if (arg === "--model") {
236
+ args.model = next();
237
+ if (!args.model) fail("--model needs a model id");
238
+ } else if (arg === "--thinking") {
239
+ const level = next();
240
+ if (!isThinkingLevel(level))
241
+ fail(
242
+ `--thinking ${level}: use ${THINKING_LEVELS.slice(0, -1).join(", ")} or ${THINKING_LEVELS.at(-1)}`,
243
+ );
244
+ args.thinking = level;
204
245
  } else if (arg === "--credentials-url") {
205
246
  args.credentialsUrl = next();
206
247
  } else if (arg === "--journal") {
@@ -291,25 +332,47 @@ if (args.journalPath && (args.mode === "acp" || args.command !== "serve"))
291
332
  fail("--journal is supported only for the stdio/listen/dial wire server");
292
333
  if (args.command !== "install" && (args.platforms || args.installDir || args.prune))
293
334
  fail("--platform, --dir and --prune are install's: agent-server install --dir <path> …");
335
+ // A wire client names each turn's model and level itself.
336
+ if (
337
+ (args.model !== undefined || args.thinking) &&
338
+ (args.mode !== "acp" || args.command !== "serve")
339
+ )
340
+ fail("--model and --thinking apply to --acp only (a wire client names them on each turn)");
294
341
  const listening = args.command === "serve" && args.mode === "listen";
295
342
  if (!listening && args.tokenFile !== undefined) fail("--token-file applies to --listen only");
296
343
  if (!listening && args.allowedOrigins) fail("--allow-origin applies to --listen only");
297
344
  const listener = listening ? listenOptions(args) : undefined;
298
345
  const credential = args.command === "serve" && args.mode === "dial" ? dialToken() : undefined;
299
346
 
300
- const harnesses = args.harnesses?.map((h) => {
347
+ const named = args.harnesses?.map((h) => {
301
348
  const choice = resolveHarnessName(h);
302
349
  if (!choice) fail(`unknown harness: ${h}`);
303
350
  // Friendly ACP agent names ("pi", "gemini") ride the acp harness.
304
351
  if (choice.acpAgent) args.acpAgent ??= choice.acpAgent;
305
352
  return choice.harness;
306
353
  });
354
+ // A script plays the scripted harness, alone unless --harness names others too.
355
+ if (args.scriptPosition !== undefined && args.script === undefined)
356
+ fail("--script-position keeps a script's position: give --script <file> too");
357
+ if (args.script !== undefined && args.command === "install")
358
+ fail("--script is the server's: agent-server --script <file>");
359
+ if (args.script !== undefined && named && !named.includes("scripted"))
360
+ fail("--script plays the scripted harness: name it in --harness (--harness scripted,…)");
361
+ if (args.command !== "install" && named?.includes("scripted") && args.script === undefined)
362
+ fail("the scripted harness needs a script: --script <file>");
363
+ const harnesses = named ?? (args.script !== undefined ? ["scripted" as const] : undefined);
307
364
  const provision = args.provisionMode ? { mode: args.provisionMode } : {};
308
365
  const acpLaunch = resolveAcpLaunch(args.acpAgent ?? process.env.AGENT_SERVER_ACP_AGENT);
309
- if (harnesses?.includes("acp") && !acpLaunch)
366
+ // `install` runs no agent: an acp harness there has nothing to install, and says so.
367
+ if (args.command !== "install" && harnesses?.includes("acp") && !acpLaunch)
310
368
  fail('the acp harness needs an agent: --harness pi|gemini or --acp-agent "<spec>"');
311
369
 
312
370
  if (args.command === "install") {
371
+ // A harness the engine installs nothing for is said, not passed over in silence.
372
+ for (const [i, harness] of (harnesses ?? []).entries())
373
+ if (!toolsFor([harness]).length)
374
+ console.error(nothingToInstall(args.harnesses?.[i] ?? harness, harness));
375
+ if (harnesses && !toolsFor(harnesses).length) process.exit(0);
313
376
  try {
314
377
  // install always downloads, into the managed cache or --dir; --provision
315
378
  // (a serving concern) is deliberately not forwarded.
@@ -319,11 +382,7 @@ if (args.command === "install") {
319
382
  ...(args.installDir && { dir: args.installDir }),
320
383
  ...(args.prune && { prune: true }),
321
384
  });
322
- for (const { tool, platform, cli } of results) {
323
- console.error(
324
- `${tool} ${cli.version ?? ""} (${platform}) ready: ${cli.path} (${cli.source})`,
325
- );
326
- }
385
+ for (const result of results) console.error(installedLine(result));
327
386
  process.exit(0);
328
387
  } catch (error) {
329
388
  console.error(`install failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -353,9 +412,22 @@ if (args.credentialsUrl) {
353
412
  }
354
413
  }
355
414
 
415
+ let script: ScriptSource | undefined;
416
+ if (args.script !== undefined) {
417
+ try {
418
+ script = scriptedFile(args.script, {
419
+ ...(args.scriptPosition && { position: args.scriptPosition }),
420
+ });
421
+ } catch (error) {
422
+ fail(`--script: ${error instanceof Error ? error.message : String(error)}`);
423
+ }
424
+ }
425
+
356
426
  const runtime = createAgentRuntime({
357
427
  ...(harnesses ? { harnesses } : {}),
358
- ...(acpLaunch ? { acp: { resolveLaunch: () => acpLaunch } } : {}),
428
+ // An ACP agent is told which release drives it (`clientInfo`).
429
+ ...(acpLaunch ? { acp: { resolveLaunch: () => acpLaunch, clientVersion: VERSION } } : {}),
430
+ ...(script && { scripted: { turn: script } }),
359
431
  provision,
360
432
  ...(args.inheritConfig && { inheritConfig: args.inheritConfig }),
361
433
  ...(credentials && { credentials }),
@@ -369,6 +441,8 @@ if (args.mode === "acp") {
369
441
  const connection = await serveAcpStdio({
370
442
  runtime,
371
443
  harness: frontedHarness,
444
+ ...(args.model && { model: args.model }),
445
+ ...(args.thinking && { thinkingLevel: args.thinking }),
372
446
  version: VERSION,
373
447
  sessionDir:
374
448
  process.env.AGENT_SERVER_ACP_SESSION_DIR ??
@@ -34,7 +34,7 @@ export interface FeedbackOptions {
34
34
  fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
35
35
  }
36
36
 
37
- export interface FeedbackResult {
37
+ interface FeedbackResult {
38
38
  delivered: boolean;
39
39
  threadId: string;
40
40
  /** Human-readable lines to print (thread id, guidance, ask). */
@@ -1,5 +1,6 @@
1
- import { chmod, readdir, realpath, rm } from "node:fs/promises";
2
- import { join, relative, sep } from "node:path";
1
+ import { readFileSync } from "node:fs";
2
+ import { chmod, mkdir, readdir, realpath, rm, stat } from "node:fs/promises";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
4
  import {
4
5
  CLI_TOOLS,
5
6
  CliProvisioner,
@@ -11,7 +12,8 @@ import {
11
12
  } from "../core/index.ts";
12
13
  import { openToAll } from "../core/provision/install-build.ts";
13
14
  import { detectPlatform, parsePlatform, platformName } from "../core/provision/platform.ts";
14
- import { CLI_TOOL_SPECS } from "../core/provision/tools.ts";
15
+ import { CLI_RELEASES } from "../core/provision/releases.ts";
16
+ import { CLI_TOOL_SPECS, claudeSdkOnDisk } from "../core/provision/tools.ts";
15
17
  import type { AgentHarness } from "../protocol/index.ts";
16
18
 
17
19
  export interface InstallOptions {
@@ -56,6 +58,50 @@ export function toolsFor(harnesses: AgentHarness[] | undefined): CliTool[] {
56
58
  return CLI_TOOLS.filter((tool) => needed.has(tool));
57
59
  }
58
60
 
61
+ /**
62
+ * What `install` says of a harness it installs nothing for (`acp`, the ACP
63
+ * agents by name, `scripted`): there is no CLI the engine installs.
64
+ */
65
+ export function nothingToInstall(name: string, harness: AgentHarness): string {
66
+ const why =
67
+ harness === "scripted"
68
+ ? "the scripted harness runs no CLI"
69
+ : "an ACP agent runs from its launch command, which the operator installs";
70
+ return `${name}: nothing to install: the engine installs no CLI for it (${why})`;
71
+ }
72
+
73
+ /**
74
+ * The Claude Code version the Claude SDK package `version` carries, where
75
+ * this release pins it or the SDK on disk is that version.
76
+ */
77
+ function claudeCodeVersion(version: string): string | undefined {
78
+ if (CLI_RELEASES.claude.version === version) return CLI_RELEASES.claude.cli;
79
+ const sdk = claudeSdkOnDisk();
80
+ if (sdk?.version !== version) return undefined;
81
+ try {
82
+ return (
83
+ JSON.parse(readFileSync(join(sdk.dir, "package.json"), "utf8")) as {
84
+ claudeCodeVersion?: string;
85
+ }
86
+ ).claudeCodeVersion;
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * The line `install` prints for a CLI it installed, saying what its version
94
+ * is: Claude's is the Claude SDK package's (`0.3.288`), which carries a
95
+ * Claude Code of its own number (`2.1.288`), the one `claude --version` says.
96
+ */
97
+ export function installedLine({ tool, platform, cli }: InstallResult): string {
98
+ const where = `for ${platform} ready: ${cli.path} (${cli.source})`;
99
+ if (tool === "codex") return `codex: Codex CLI ${cli.version ?? "(version not known)"} ${where}`;
100
+ if (!cli.version) return `claude: Claude Code (version not known) ${where}`;
101
+ const code = claudeCodeVersion(cli.version);
102
+ return `claude: Claude SDK package ${cli.version}${code ? ` (Claude Code ${code})` : ""} ${where}`;
103
+ }
104
+
59
105
  /** The platforms named, each one some CLI is published for, or what is wrong. */
60
106
  export function platformsFor(names: readonly string[]): PlatformInfo[] {
61
107
  const known = [...new Set(CLI_TOOLS.flatMap((tool) => CLI_TOOL_SPECS[tool].platforms))];
@@ -88,6 +134,34 @@ function stagedBuild(dir: string, path: string): string {
88
134
  return join(tool, entry);
89
135
  }
90
136
 
137
+ /**
138
+ * `dir` and the parents of it that are missing, created readable and
139
+ * traversable by every user (0755, whatever the umask), as the builds staged
140
+ * in it are: run as root in an image build, the engine's own 0700 would leave
141
+ * a runtime user unable to reach them. A folder that was there is left as it
142
+ * is. The engine's own cache keeps its 0700 (`trustedCacheDirectory`).
143
+ */
144
+ async function createStagingFolders(dir: string): Promise<void> {
145
+ const missing: string[] = [];
146
+ for (let path = resolve(dir); ; path = dirname(path)) {
147
+ const exists = await stat(path).then(
148
+ () => true,
149
+ (error: NodeJS.ErrnoException) => {
150
+ if (error.code === "ENOENT") return false;
151
+ throw error;
152
+ },
153
+ );
154
+ if (exists || dirname(path) === path) break;
155
+ missing.unshift(path);
156
+ }
157
+ for (const path of missing) {
158
+ await mkdir(path, { mode: 0o755 }).catch((error: NodeJS.ErrnoException) => {
159
+ if (error.code !== "EEXIST") throw error;
160
+ });
161
+ await chmod(path, 0o755);
162
+ }
163
+ }
164
+
91
165
  /**
92
166
  * The builds just staged, readable and runnable by every user, and the
93
167
  * folder without the install's records: an owner-only tree baked into an
@@ -116,7 +190,11 @@ export async function runInstall(options: InstallOptions = {}): Promise<InstallR
116
190
  ...(options.dir && { mode: "pinned", cacheDir: options.dir }),
117
191
  };
118
192
  const platforms = options.platforms ? platformsFor(options.platforms) : [detectPlatform()];
119
- if (options.dir) await stageable(options.dir);
193
+ if (options.dir) {
194
+ await stageable(options.dir);
195
+ // @ref LLP 0010#p4--staging-for-images-and-app-bundles — what staging creates, every user may reach
196
+ await createStagingFolders(options.dir);
197
+ }
120
198
  const create =
121
199
  options.createProvisioner ??
122
200
  ((provisionOptions: ProvisionOptions, platform: PlatformInfo) =>
@@ -1,7 +1,7 @@
1
1
  import { type AgentHarness, WireRefusal } from "../protocol/index.ts";
2
2
 
3
3
  /** The turn a session runs. */
4
- export interface ActiveTurn {
4
+ interface ActiveTurn {
5
5
  turnId: string;
6
6
  harness: AgentHarness;
7
7
  }
@@ -242,8 +242,12 @@ export class JournalSessionStore implements SessionLogStore {
242
242
  receipt(sessionId: string, turnId: string): TurnReceipt | undefined {
243
243
  return this.journal.turn(sessionId, turnId);
244
244
  }
245
+ // @ref LLP 0003#commit-before-acknowledging — the latest turn is read for `session/get` alone
246
+ /** `session/get`'s answer: the journal's summary and its latest turn. */
245
247
  session(sessionId: string): DurableSession | undefined {
246
- return this.journal.session(sessionId);
248
+ const session = this.journal.session(sessionId);
249
+ const lastTurn = session && this.journal.lastTurn(sessionId);
250
+ return session && { ...session, ...(lastTurn && { lastTurn }) };
247
251
  }
248
252
  confirmStopped(sessionId: string, expectedHeadSeq: number): boolean {
249
253
  return this.write(() => this.journal.confirmStopped(sessionId, expectedHeadSeq));
@@ -20,7 +20,7 @@ export const DEFAULT_MAX_SUBSCRIPTIONS = 256;
20
20
  */
21
21
  export const DEFAULT_MAX_BACKLOG_BYTES = 16 * 1024 * 1024;
22
22
 
23
- export interface SubscriptionLimits {
23
+ interface SubscriptionLimits {
24
24
  maxSubscriptions: number;
25
25
  maxBacklogBytes: number;
26
26
  }
@@ -30,6 +30,13 @@ export function stdioTransport(
30
30
  return transport;
31
31
  }
32
32
 
33
+ /**
34
+ * How far past the server's backlog bound (`maxBacklogBytes`) a listener's
35
+ * socket may buffer before Bun closes it: room for the frame that crossed the
36
+ * bound, the `session/overflow` notice behind it, and the responses after it.
37
+ */
38
+ const SOCKET_HEADROOM_BYTES = 64 * 1024 * 1024;
39
+
33
40
  /** A WebSocket as a wire transport: its frames come in line by line, each line goes out as a frame. */
34
41
  function socketTransport(
35
42
  ws: { send(line: string): unknown; close(): void },
@@ -157,6 +164,13 @@ export function listen(
157
164
  : new Response("websocket upgrade required", { status: 426 });
158
165
  },
159
166
  websocket: {
167
+ // Above the server's own bound: the overflow notice it sends there is
168
+ // never dropped by Bun's (16 MiB by default, the bound's own default).
169
+ backpressureLimit: server.maxBacklogBytes + SOCKET_HEADROOM_BYTES,
170
+ // @ref LLP 0008#backpressure-and-overflow — a connection is told it overflowed, or closed
171
+ // Past it, a send Bun would drop closes the connection instead: the
172
+ // client redials and replays rather than wait for a lost line.
173
+ closeOnBackpressureLimit: true,
160
174
  open(ws) {
161
175
  ws.data.socket = socketTransport(ws, () => ws.getBufferedAmount());
162
176
  server.attach(ws.data.socket.transport);
package/src/sync/fit.ts CHANGED
@@ -2,6 +2,8 @@ import {
2
2
  HISTORY_MAX_BYTES,
3
3
  HistoryError,
4
4
  type LifecycleEvent,
5
+ OMITTED_BINARY_META_KEY,
6
+ type OmittedBinary,
5
7
  canonicalJson,
6
8
  decodeLifecycleEvent,
7
9
  jsonBytes,
@@ -25,39 +27,124 @@ export const REPLAY_PAGE_BYTES = HISTORY_MAX_BYTES - 64 * 1024;
25
27
  const encoder = new TextEncoder();
26
28
  const decoder = new TextDecoder();
27
29
 
30
+ /** An image or file as the protocol carries one: base64 `data` beside its `mimeType`. */
31
+ function isBinary(value: object): value is Record<string, unknown> & { data: string } {
32
+ const entry = value as Record<string, unknown>;
33
+ return (
34
+ (entry.type === "image" || entry.type === "file") &&
35
+ typeof entry.data === "string" &&
36
+ typeof entry.mimeType === "string"
37
+ );
38
+ }
39
+
40
+ /** The size of what base64 `data` encodes. */
41
+ function decodedBytes(data: string): number {
42
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
43
+ return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
44
+ }
45
+
46
+ /** The part fields that address a part, which its stand-in keeps. */
47
+ const ADDRESS = ["id", "sessionId", "messageId", "parentToolCallId"] as const;
48
+
28
49
  /**
29
- * `event` cut down to `maxBytes`: its longest strings (usually a tool's output)
30
- * are truncated with a visible marker until it fits. `undefined` when only
31
- * short strings remain. An event that already fits is returned as is.
50
+ * What a store keeps in place of `binary`: text saying what it was, in words
51
+ * and under `OMITTED_BINARY_META_KEY`. A part stays at its address as a text
52
+ * part; a tool result's entry becomes a text entry.
32
53
  */
33
- export function fitEvent<T>(event: T, maxBytes = MAX_EVENT_BYTES): T | undefined {
34
- let size = jsonBytes(event);
35
- if (size <= maxBytes) return event;
36
- const copy = structuredClone(event);
37
- for (let attempt = 0; attempt < 8 && size > maxBytes; attempt++) {
38
- let longest: { holder: Record<string, unknown>; key: string; bytes: number } | undefined;
39
- const visit = (value: unknown) => {
40
- if (!value || typeof value !== "object") return;
41
- for (const [key, child] of Object.entries(value)) {
42
- if (typeof child !== "string") visit(child);
43
- else {
44
- const bytes = encoder.encode(child).byteLength;
45
- if (!longest || bytes > longest.bytes)
46
- longest = { holder: value as Record<string, unknown>, key, bytes };
47
- }
54
+ function omittedBinary(
55
+ binary: Record<string, unknown> & { data: string },
56
+ where: string,
57
+ ): Record<string, unknown> {
58
+ const facts: OmittedBinary = {
59
+ type: binary.type as OmittedBinary["type"],
60
+ mimeType: binary.mimeType as string,
61
+ bytes: decodedBytes(binary.data),
62
+ ...(typeof binary.filename === "string" && { filename: binary.filename }),
63
+ };
64
+ const meta =
65
+ binary._meta && typeof binary._meta === "object" && !Array.isArray(binary._meta)
66
+ ? binary._meta
67
+ : {};
68
+ const named = facts.filename === undefined ? "" : ` ${facts.filename}`;
69
+ return {
70
+ type: "text",
71
+ ...Object.fromEntries(
72
+ ADDRESS.filter((key) => typeof binary[key] === "string").map((key) => [key, binary[key]]),
73
+ ),
74
+ text: `[agent-server: ${facts.mimeType} ${facts.type}${named} of ${facts.bytes} bytes omitted to fit ${where}]`,
75
+ _meta: { ...meta, [OMITTED_BINARY_META_KEY]: facts },
76
+ };
77
+ }
78
+
79
+ // @ref LLP 0002#tool-output-has-three-audiences — a cut binary is no display at all: kept whole or replaced
80
+ /**
81
+ * `value` brought down to `maxBytes` by its longest strings, one at a time: a
82
+ * binary's `data` (an image or file, `isBinary`) is never cut, its whole entry
83
+ * is replaced by a text one saying what it was (`omittedBinary`); any other
84
+ * string is cut with a visible marker, when `cutText`. It stops when only
85
+ * short strings remain, so what it returns may still not fit. A value that
86
+ * already fits is returned as is.
87
+ */
88
+ function shrink<T>(value: T, maxBytes: number, where: string, cutText: boolean): T {
89
+ let size = jsonBytes(value);
90
+ if (size <= maxBytes) return value;
91
+ const copy = structuredClone(value);
92
+ // Each replacement removes a binary; cuts are bounded as they always were.
93
+ let cuts = 0;
94
+ while (size > maxBytes) {
95
+ let longest:
96
+ | { holder: Record<string, unknown>; key: string; bytes: number; binary: boolean }
97
+ | undefined;
98
+ const consider = (holder: object, key: string, bytes: number, binary: boolean) => {
99
+ if (!longest || bytes > longest.bytes)
100
+ longest = { holder: holder as Record<string, unknown>, key, bytes, binary };
101
+ };
102
+ const visit = (node: object) => {
103
+ for (const [key, child] of Object.entries(node)) {
104
+ if (child && typeof child === "object") {
105
+ // Base64 is ASCII: its length is its size.
106
+ if (isBinary(child)) consider(node, key, child.data.length, true);
107
+ else visit(child);
108
+ } else if (cutText && typeof child === "string")
109
+ consider(node, key, encoder.encode(child).byteLength, false);
48
110
  }
49
111
  };
50
- visit(copy);
51
- if (!longest || longest.bytes < 1024) return undefined;
52
- const keep = Math.max(0, longest.bytes - (size - maxBytes) - 256);
53
- const head = decoder
54
- .decode(encoder.encode(longest.holder[longest.key] as string).slice(0, keep))
55
- .replace(/�$/, "");
56
- longest.holder[longest.key] =
57
- `${head}\n[agent-server: ${longest.bytes - keep} bytes omitted to fit the journal]`;
112
+ if (copy && typeof copy === "object") visit(copy);
113
+ if (!longest || longest.bytes < 1024) break;
114
+ const { holder, key, bytes } = longest;
115
+ if (longest.binary)
116
+ holder[key] = omittedBinary(holder[key] as Record<string, unknown> & { data: string }, where);
117
+ else {
118
+ if (++cuts > 8) break;
119
+ const keep = Math.max(0, bytes - (size - maxBytes) - 256);
120
+ const head = decoder
121
+ .decode(encoder.encode(holder[key] as string).slice(0, keep))
122
+ .replace(/�$/, "");
123
+ holder[key] = `${head}\n[agent-server: ${bytes - keep} bytes omitted to fit ${where}]`;
124
+ }
58
125
  size = jsonBytes(copy);
59
126
  }
60
- return size <= maxBytes ? copy : undefined;
127
+ return copy;
128
+ }
129
+
130
+ /**
131
+ * `event` cut down to `maxBytes`: its longest strings (usually a tool's
132
+ * output) are truncated with a visible marker until it fits, and an image or
133
+ * file it cannot keep whole is replaced by text saying what it was. `undefined`
134
+ * when only short strings remain. An event that already fits is returned as is.
135
+ */
136
+ export function fitEvent<T>(event: T, maxBytes = MAX_EVENT_BYTES): T | undefined {
137
+ const fitted = shrink(event, maxBytes, "the journal", true);
138
+ return jsonBytes(fitted) <= maxBytes ? fitted : undefined;
139
+ }
140
+
141
+ /**
142
+ * `value` with its largest images and files replaced by text saying what they
143
+ * were (as `fitEvent` replaces them) until it fits `maxBytes`, or until none
144
+ * is left. Nothing else is changed. A value that already fits is returned as is.
145
+ */
146
+ export function omitBinaries<T>(value: T, maxBytes: number, where: string): T {
147
+ return shrink(value, maxBytes, where, false);
61
148
  }
62
149
 
63
150
  /**
@@ -65,7 +152,7 @@ export function fitEvent<T>(event: T, maxBytes = MAX_EVENT_BYTES): T | undefined
65
152
  * every other session keep going. A turn or session end keeps its meaning;
66
153
  * anything else becomes a recoverable error notice naming what was lost.
67
154
  */
68
- export function unrecordedEvent(event: LifecycleEvent, reason: string): LifecycleEvent {
155
+ function unrecordedEvent(event: LifecycleEvent, reason: string): LifecycleEvent {
69
156
  const message = `agent-server could not record a ${event.type} event: ${reason.slice(0, 300)}`;
70
157
  const timestamp = Date.now();
71
158
  if (event.type === "turn.ended")
@@ -35,7 +35,7 @@ import {
35
35
  } from "../protocol/index.ts";
36
36
  import { type EventLog, type EventRow, sha256 } from "./event-log.ts";
37
37
  import { MAX_EVENT_BYTES, PAGE_SLACK_BYTES } from "./fit.ts";
38
- import { checkCheckpointBytes, projectionFold } from "./projection.ts";
38
+ import { checkCheckpointBytes, fitCheckpoint, projectionFold } from "./projection.ts";
39
39
  import type { Db } from "./sql.ts";
40
40
 
41
41
  const conflict = (message: string) => new HistoryError("historyConflict", message);
@@ -322,7 +322,11 @@ export class SqliteHistory implements HistoryStore {
322
322
  : emptyConversation();
323
323
  for (const row of this.log.records(ref, prior?.version.seq ?? 0, target.seq))
324
324
  conversation = fold(conversation, JSON.parse(row.body));
325
- const checkpoint = { version: target, format: CONVERSATION_CHECKPOINT_FORMAT, conversation };
325
+ const checkpoint = fitCheckpoint({
326
+ version: target,
327
+ format: CONVERSATION_CHECKPOINT_FORMAT,
328
+ conversation,
329
+ });
326
330
  checkCheckpointBytes(checkpoint);
327
331
  this.db.atomic(() =>
328
332
  this.db.run(
package/src/sync/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Storage/transport-neutral host contracts. SQLite is an optional subpath.
2
2
  export { JournalError, type SessionJournal } from "./journal.ts";
3
+ export { JOURNAL_SCHEMA_VERSION } from "./schema.ts";
3
4
  export {
4
5
  type FollowHistoryOptions,
5
6
  type HistoryTransfer,
@@ -2,6 +2,7 @@ import {
2
2
  type AgentHarness,
3
3
  type DurableSession,
4
4
  HISTORY_MAX_RECORDS,
5
+ type LastTurn,
5
6
  type LifecycleEvent,
6
7
  type MessagePartDeltaEvent,
7
8
  type RecoveryReason,
@@ -116,6 +117,18 @@ export class SqliteJournal implements SessionJournal {
116
117
  }
117
118
  );
118
119
  }
120
+ lastTurn(sessionId: string): LastTurn | undefined {
121
+ // An admitted turn has no terminal yet: it sorts first, then the latest ended.
122
+ const row = this.db.one<{ turn_id: string; terminal: string | null }>(
123
+ "SELECT t.turn_id, e.body AS terminal FROM turns t LEFT JOIN events e ON e.source_id=? AND e.session_id=t.session_id AND e.seq=t.terminal_seq WHERE t.session_id=? ORDER BY t.state='admitted' DESC, t.terminal_seq DESC LIMIT 1",
124
+ this.sourceId,
125
+ sessionId,
126
+ );
127
+ if (!row) return undefined;
128
+ if (row.terminal === null) return { turnId: row.turn_id };
129
+ const { stopReason, error } = JSON.parse(row.terminal) as TurnEndedEvent;
130
+ return { turnId: row.turn_id, stopReason, ...(error && { error }) };
131
+ }
119
132
  turn(sessionId: string, turnId: string): TurnReceipt | undefined {
120
133
  const row = this.db.one<{
121
134
  state: TurnReceipt["state"];
@@ -160,8 +173,13 @@ export class SqliteJournal implements SessionJournal {
160
173
  "History branch is not a native execution session; prepare provider context explicitly",
161
174
  );
162
175
  const input = canonical(request.input);
163
- if (Buffer.byteLength(input) > MAX_EVENT_BYTES)
164
- throw new JournalError("invalidParams", "Input exceeds durable record limit");
176
+ const bytes = Buffer.byteLength(input);
177
+ if (bytes > MAX_EVENT_BYTES)
178
+ // `invalidParams` carries no data on the wire (`WIRE_REFUSAL_DATA`): the words say it.
179
+ throw new JournalError(
180
+ "invalidParams",
181
+ `Input is ${bytes} bytes; the durable record limit is ${MAX_EVENT_BYTES} bytes`,
182
+ );
165
183
  return this.db.atomic(() => {
166
184
  if (this.admission(request) === "duplicate") return "duplicate";
167
185
  const state = this.session(sessionId);