@qlairoslabs/acp-client 0.12.0 → 0.13.0-alpha.1

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 (467) hide show
  1. package/CHANGELOG-consumer-fixes.md +17 -3
  2. package/CHANGELOG-controller-interface.md +258 -0
  3. package/CHANGELOG-metering.md +29 -0
  4. package/CHANGELOG-operation-lifecycle.md +15 -1
  5. package/CONSUMER_GUIDE.md +847 -7
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +275 -0
  8. package/README.md +17 -16
  9. package/package.json +4 -2
  10. package/src/acp-client-handlers.ts +48 -0
  11. package/src/activity.ts +3 -0
  12. package/src/adapters.ts +30 -0
  13. package/src/agent/adoption/provider-attachment.ts +33 -0
  14. package/src/agent/adoption/provider-session-delete.ts +1 -1
  15. package/src/agent/adoption/provider-sessions.ts +3 -2
  16. package/src/agent/append-assistant-message.ts +91 -0
  17. package/src/agent/config.ts +54 -6
  18. package/src/agent/conversation-manager.ts +94 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/persisted-lifecycle.ts +44 -4
  22. package/src/agent/persistence-policy/context.ts +13 -0
  23. package/src/agent/persistence-policy/resolver.ts +7 -0
  24. package/src/agent/persistence-policy/types.ts +1 -0
  25. package/src/agent/record-capture.ts +1 -0
  26. package/src/agent-adapter-registry.ts +33 -7
  27. package/src/agent-conversation-contracts.ts +14 -1
  28. package/src/agent-conversation-errors.ts +8 -0
  29. package/src/agent-conversation-owner.ts +9 -4
  30. package/src/agent-session-config.ts +135 -0
  31. package/src/agent-session.ts +439 -934
  32. package/src/agent.ts +73 -0
  33. package/src/capabilities.ts +2 -0
  34. package/src/checkpointing/recovery.ts +10 -0
  35. package/src/cli/index.ts +3 -3
  36. package/src/cli/managed.ts +2 -2
  37. package/src/client.ts +68 -98
  38. package/src/connection-attempt.ts +95 -0
  39. package/src/controller-connection.ts +114 -0
  40. package/src/controller.ts +156 -148
  41. package/src/conversation-controller/capabilities.ts +88 -0
  42. package/src/conversation-controller/contracts.ts +208 -0
  43. package/src/conversation-controller/factory.ts +39 -0
  44. package/src/conversation-controller/guards.ts +98 -0
  45. package/src/conversation-controller/index.ts +20 -0
  46. package/src/conversation-startup.ts +35 -0
  47. package/src/conversation-turns/backend-turns.ts +373 -0
  48. package/src/conversation-turns/clear-operations.ts +37 -0
  49. package/src/conversation-turns/context.ts +135 -0
  50. package/src/conversation-turns/index.ts +4 -0
  51. package/src/conversation-turns/record-helpers.ts +75 -0
  52. package/src/conversation-turns/recording.ts +235 -0
  53. package/src/conversation-turns/run-turn.ts +367 -0
  54. package/src/conversation-turns/turn-run.ts +57 -0
  55. package/src/errors.ts +41 -0
  56. package/src/handoff-options.ts +81 -0
  57. package/src/identity/checkpoint-backed.ts +1 -1
  58. package/src/index.ts +58 -3
  59. package/src/internal-inference/coordination/manager.ts +11 -0
  60. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  61. package/src/launcher.ts +35 -2
  62. package/src/media/parts.ts +5 -0
  63. package/src/message-status.ts +83 -0
  64. package/src/metering/engine.ts +39 -64
  65. package/src/metering/measurement-provenance.ts +36 -0
  66. package/src/metering/native/durability.ts +115 -0
  67. package/src/metering/native/ledger.ts +104 -0
  68. package/src/metering/native/operation.ts +85 -0
  69. package/src/metering/native/projection.ts +114 -0
  70. package/src/metering/native/proof.ts +51 -0
  71. package/src/metering/native/requirements.ts +10 -0
  72. package/src/metering/native/retirement.ts +92 -0
  73. package/src/metering/native/source.ts +90 -0
  74. package/src/metering/record.ts +38 -1
  75. package/src/metering/state.ts +13 -3
  76. package/src/native/approvals.ts +169 -0
  77. package/src/native/capabilities.ts +17 -0
  78. package/src/native/channel-changes.ts +211 -0
  79. package/src/native/connection.ts +56 -0
  80. package/src/native/controller.ts +591 -0
  81. package/src/native/delegation-sender.ts +26 -0
  82. package/src/native/errors.ts +35 -0
  83. package/src/native/functions.ts +156 -0
  84. package/src/native/host-config.ts +59 -0
  85. package/src/native/host.ts +909 -0
  86. package/src/native/item-receipts.ts +15 -0
  87. package/src/native/metering.ts +12 -0
  88. package/src/native/records.ts +166 -0
  89. package/src/native/recovery.ts +186 -0
  90. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  91. package/src/native/reminders/idle.ts +70 -0
  92. package/src/native/reminders/limits.ts +19 -0
  93. package/src/native/reminders/notifications.ts +29 -0
  94. package/src/native/reminders/reminders.test.ts +553 -0
  95. package/src/native/reminders/routine-config.typecheck.ts +13 -0
  96. package/src/native/reminders/routine-guard.ts +66 -0
  97. package/src/native/reminders/routine-schedule.ts +25 -0
  98. package/src/native/reminders/routine-wire.ts +21 -0
  99. package/src/native/reminders/schedule.ts +97 -0
  100. package/src/native/reminders/service.ts +280 -0
  101. package/src/native/reminders/supervisor.ts +91 -0
  102. package/src/native/reminders/sync.ts +301 -0
  103. package/src/native/reminders/wire.ts +197 -0
  104. package/src/native/reminders/wire.typecheck.ts +13 -0
  105. package/src/native/submission-withdrawal.ts +65 -0
  106. package/src/native/usage.ts +15 -0
  107. package/src/native/worker-delivery.ts +61 -0
  108. package/src/native-harness/.res/README.md +1 -0
  109. package/src/native-harness/.res/architecture/README.md +21 -0
  110. package/src/native-harness/.res/architecture/context-and-data.md +31 -0
  111. package/src/native-harness/.res/architecture/execution.md +42 -0
  112. package/src/native-harness/.res/architecture/overview.md +44 -0
  113. package/src/native-harness/.res/architecture/persistence.md +56 -0
  114. package/src/native-harness/.res/architecture/suspend-and-resume.md +45 -0
  115. package/src/native-harness/.res/architecture/technical-architecture.md +50 -0
  116. package/src/native-harness/.res/decisions/0001-basic-loop.md +11 -0
  117. package/src/native-harness/.res/decisions/0002-channel-input.md +17 -0
  118. package/src/native-harness/.res/decisions/0003-inference-inspection.md +14 -0
  119. package/src/native-harness/.res/decisions/0004-shared-context.md +21 -0
  120. package/src/native-harness/.res/decisions/0005-notice-inbox.md +20 -0
  121. package/src/native-harness/.res/decisions/0006-explicit-notices.md +12 -0
  122. package/src/native-harness/.res/decisions/0007-channel-output.md +12 -0
  123. package/src/native-harness/.res/decisions/0008-browser-client.md +16 -0
  124. package/src/native-harness/.res/decisions/0009-scripted-model.md +18 -0
  125. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +19 -0
  126. package/src/native-harness/.res/decisions/0011-stdio-transport.md +21 -0
  127. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +37 -0
  128. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +64 -0
  129. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +73 -0
  130. package/src/native-harness/.res/decisions/0015-session-file-contract.md +72 -0
  131. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +159 -0
  132. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +69 -0
  133. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +78 -0
  134. package/src/native-harness/.res/decisions/0019-model-execution.md +188 -0
  135. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +71 -0
  136. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +100 -0
  137. package/src/native-harness/.res/decisions/0022-operator-controls.md +115 -0
  138. package/src/native-harness/.res/decisions/0023-long-running-mock.md +82 -0
  139. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +46 -0
  140. package/src/native-harness/.res/decisions/0025-external-notices.md +364 -0
  141. package/src/native-harness/.res/decisions/0026-bounded-context.md +81 -0
  142. package/src/native-harness/.res/decisions/0027-development-instructions.md +22 -0
  143. package/src/native-harness/.res/decisions/0028-debug-tools.md +16 -0
  144. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +37 -0
  145. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +145 -0
  146. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +173 -0
  147. package/src/native-harness/.res/docs/11-15.md +148 -0
  148. package/src/native-harness/.res/docs/BUSINESS_RULES.md +111 -0
  149. package/src/native-harness/.res/docs/WORK.md +65 -0
  150. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +312 -0
  151. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +77 -0
  152. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +313 -0
  153. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +160 -0
  154. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +89 -0
  155. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +135 -0
  156. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +143 -0
  157. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +93 -0
  158. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +181 -0
  159. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +433 -0
  160. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +60 -0
  161. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +141 -0
  162. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +168 -0
  163. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +111 -0
  164. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +129 -0
  165. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +135 -0
  166. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +437 -0
  167. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +127 -0
  168. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +203 -0
  169. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +292 -0
  170. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +91 -0
  171. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +187 -0
  172. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +148 -0
  173. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +95 -0
  174. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +200 -0
  175. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +80 -0
  176. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +206 -0
  177. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +106 -0
  178. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +297 -0
  179. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +41 -0
  180. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +36 -0
  181. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +84 -0
  182. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +147 -0
  183. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +15 -0
  184. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +107 -0
  185. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +114 -0
  186. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +24 -0
  187. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +23 -0
  188. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +103 -0
  189. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +50 -0
  190. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +337 -0
  191. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +76 -0
  192. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +204 -0
  193. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +73 -0
  194. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +64 -0
  195. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +58 -0
  196. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +45 -0
  197. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +108 -0
  198. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +169 -0
  199. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +128 -0
  200. package/src/native-harness/.res/marketing-draft.md +22 -0
  201. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +285 -0
  202. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +19 -0
  203. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +138 -0
  204. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +148 -0
  205. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +172 -0
  206. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +194 -0
  207. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +233 -0
  208. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +249 -0
  209. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +265 -0
  210. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +279 -0
  211. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +293 -0
  212. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +307 -0
  213. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +29 -0
  214. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +317 -0
  215. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +327 -0
  216. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +40 -0
  217. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +59 -0
  218. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +69 -0
  219. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +79 -0
  220. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +89 -0
  221. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +102 -0
  222. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +116 -0
  223. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +49 -0
  224. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +87 -0
  225. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +289 -0
  226. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +221 -0
  227. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +287 -0
  228. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +165 -0
  229. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +22 -0
  230. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +2 -0
  231. package/src/native-harness/AGENTS.md +70 -0
  232. package/src/native-harness/ARCHITECTURE.md +249 -0
  233. package/src/native-harness/README.md +726 -0
  234. package/src/native-harness/bun.lock +26 -0
  235. package/src/native-harness/package.json +24 -0
  236. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  237. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  238. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  239. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  240. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  241. package/src/native-harness/src/capabilities/context/session.ts +92 -0
  242. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  243. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  244. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  245. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  246. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  247. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  248. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  249. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  250. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  251. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  252. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  253. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  254. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  255. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  256. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  257. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  258. package/src/native-harness/src/capabilities/tools/reminders/index.ts +75 -0
  259. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  260. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  261. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  262. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  263. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  264. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  265. package/src/native-harness/src/client.ts +18 -0
  266. package/src/native-harness/src/contracts/agent.ts +105 -0
  267. package/src/native-harness/src/contracts/config-permissions.ts +47 -0
  268. package/src/native-harness/src/contracts/context.ts +112 -0
  269. package/src/native-harness/src/contracts/events.ts +47 -0
  270. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  271. package/src/native-harness/src/contracts/inspection.ts +22 -0
  272. package/src/native-harness/src/contracts/loop.ts +31 -0
  273. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  274. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  275. package/src/native-harness/src/contracts/output.ts +13 -0
  276. package/src/native-harness/src/contracts/protocol.ts +320 -0
  277. package/src/native-harness/src/contracts/reminders.ts +132 -0
  278. package/src/native-harness/src/contracts/scenario.ts +42 -0
  279. package/src/native-harness/src/contracts/session-file.ts +19 -0
  280. package/src/native-harness/src/contracts/session.ts +184 -0
  281. package/src/native-harness/src/contracts/storage.ts +596 -0
  282. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  283. package/src/native-harness/src/contracts/tools.ts +133 -0
  284. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  285. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  286. package/src/native-harness/src/index.ts +318 -0
  287. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  288. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  289. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  290. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  291. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  292. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  293. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  294. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  295. package/src/native-harness/src/interfaces/client.ts +225 -0
  296. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  297. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  298. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  299. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  300. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  301. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  302. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  303. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  304. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  305. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  306. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  307. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  308. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  309. package/src/native-harness/src/interfaces/protocol/server.ts +517 -0
  310. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +119 -0
  311. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  312. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  313. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  314. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  315. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  316. package/src/native-harness/src/kernel/channels.ts +405 -0
  317. package/src/native-harness/src/kernel/loop.ts +45 -0
  318. package/src/native-harness/src/runtime/config/development.ts +23 -0
  319. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  320. package/src/native-harness/src/runtime/config/paths.ts +27 -0
  321. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  322. package/src/native-harness/src/runtime/reminder-validation.ts +104 -0
  323. package/src/native-harness/src/runtime/reminders.ts +66 -0
  324. package/src/native-harness/src/state/storage/archive.ts +239 -0
  325. package/src/native-harness/src/state/storage/engine.ts +1013 -0
  326. package/src/native-harness/src/state/storage/inference.ts +124 -0
  327. package/src/native-harness/src/state/storage/memory-reminders.ts +78 -0
  328. package/src/native-harness/src/state/storage/memory.ts +341 -0
  329. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  330. package/src/native-harness/src/state/storage/reminder-archive.ts +63 -0
  331. package/src/native-harness/src/state/storage/reminder-change.ts +92 -0
  332. package/src/native-harness/src/state/storage/reminder-tables.ts +27 -0
  333. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  334. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  335. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  336. package/src/native-harness/src/state/storage/sqlite-reminders.ts +134 -0
  337. package/src/native-harness/src/state/storage/sqlite.ts +625 -0
  338. package/src/native-harness/src/testing.ts +190 -0
  339. package/src/native-harness/src/util/config.ts +58 -0
  340. package/src/native-harness/src/util/json.ts +41 -0
  341. package/src/native-harness/src/util/message-position.ts +3 -0
  342. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  343. package/src/native-harness/src/util/schema.ts +40 -0
  344. package/src/native-harness/src/util/timeline-text.ts +72 -0
  345. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  346. package/src/native-harness/test/agent.test.ts +130 -0
  347. package/src/native-harness/test/approval-gate.test.ts +255 -0
  348. package/src/native-harness/test/approval-protocol.test.ts +94 -0
  349. package/src/native-harness/test/boundaries.test.ts +18 -0
  350. package/src/native-harness/test/channel-controls.test.ts +322 -0
  351. package/src/native-harness/test/client-abort.test.ts +136 -0
  352. package/src/native-harness/test/config-policy.test.ts +301 -0
  353. package/src/native-harness/test/conformance/storage.ts +1141 -0
  354. package/src/native-harness/test/context.test.ts +177 -0
  355. package/src/native-harness/test/crash.test.ts +187 -0
  356. package/src/native-harness/test/debug-tools.test.ts +67 -0
  357. package/src/native-harness/test/development-cli.test.ts +67 -0
  358. package/src/native-harness/test/development.test.ts +171 -0
  359. package/src/native-harness/test/dispatch-evidence.test.ts +58 -0
  360. package/src/native-harness/test/e2e.test.ts +186 -0
  361. package/src/native-harness/test/external-notices.test.ts +101 -0
  362. package/src/native-harness/test/fixtures/approval-e2e.jsonl +4 -0
  363. package/src/native-harness/test/fixtures/crash-scenario.jsonl +5 -0
  364. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +10 -0
  365. package/src/native-harness/test/fixtures/echo-scenario.jsonl +3 -0
  366. package/src/native-harness/test/fixtures/format2-schema.ts +27 -0
  367. package/src/native-harness/test/fixtures/format3-schema.ts +16 -0
  368. package/src/native-harness/test/fixtures/hold-scenario.jsonl +4 -0
  369. package/src/native-harness/test/fixtures/model-e2e.jsonl +3 -0
  370. package/src/native-harness/test/fixtures/storage-owner.ts +20 -0
  371. package/src/native-harness/test/format-reply.test.ts +10 -0
  372. package/src/native-harness/test/helpers/operator-view.ts +41 -0
  373. package/src/native-harness/test/helpers/scenario.ts +9 -0
  374. package/src/native-harness/test/helpers/session.ts +38 -0
  375. package/src/native-harness/test/helpers/stdio.ts +46 -0
  376. package/src/native-harness/test/inspector.test.ts +77 -0
  377. package/src/native-harness/test/listeners.test.ts +49 -0
  378. package/src/native-harness/test/loop.test.ts +88 -0
  379. package/src/native-harness/test/model-channel-double.test.ts +87 -0
  380. package/src/native-harness/test/model-crash.test.ts +62 -0
  381. package/src/native-harness/test/model-delivery-regressions.test.ts +55 -0
  382. package/src/native-harness/test/model-e2e.test.ts +71 -0
  383. package/src/native-harness/test/model-final-filter.test.ts +30 -0
  384. package/src/native-harness/test/model-large-reply.test.ts +28 -0
  385. package/src/native-harness/test/model-live-queue.test.ts +33 -0
  386. package/src/native-harness/test/model-runner.test.ts +117 -0
  387. package/src/native-harness/test/model-storage.test.ts +99 -0
  388. package/src/native-harness/test/model-stream-adapter.test.ts +26 -0
  389. package/src/native-harness/test/model-stream-public.test.ts +77 -0
  390. package/src/native-harness/test/notices.test.ts +64 -0
  391. package/src/native-harness/test/openrouter-config.test.ts +218 -0
  392. package/src/native-harness/test/operator-controls.test.ts +132 -0
  393. package/src/native-harness/test/output.test.ts +44 -0
  394. package/src/native-harness/test/owner-config.test.ts +64 -0
  395. package/src/native-harness/test/permissions-e2e.test.ts +68 -0
  396. package/src/native-harness/test/persistence.test.ts +236 -0
  397. package/src/native-harness/test/portability.test.ts +337 -0
  398. package/src/native-harness/test/protocol.test.ts +160 -0
  399. package/src/native-harness/test/reminder-clock.test.ts +61 -0
  400. package/src/native-harness/test/reminder-stdio.test.ts +140 -0
  401. package/src/native-harness/test/reminder-storage.test.ts +124 -0
  402. package/src/native-harness/test/scenario-jsonl.test.ts +112 -0
  403. package/src/native-harness/test/scripted.test.ts +92 -0
  404. package/src/native-harness/test/session-file.test.ts +51 -0
  405. package/src/native-harness/test/startup-channel-changes.test.ts +256 -0
  406. package/src/native-harness/test/stdio.test.ts +132 -0
  407. package/src/native-harness/test/storage-memory.test.ts +4 -0
  408. package/src/native-harness/test/storage-sqlite.test.ts +420 -0
  409. package/src/native-harness/test/suspension.test.ts +430 -0
  410. package/src/native-harness/test/timeline-retrieval.test.ts +211 -0
  411. package/src/native-harness/test/tools-catalog.test.ts +468 -0
  412. package/src/native-harness/test/tools-protocol.test.ts +418 -0
  413. package/src/native-harness/test/transfers.test.ts +94 -0
  414. package/src/native-harness/test/web-chat.test.ts +35 -0
  415. package/src/native-harness/tsconfig.json +20 -0
  416. package/src/observation/agent-event-bus.ts +44 -18
  417. package/src/observation/index.ts +1 -0
  418. package/src/operations/contracts.ts +11 -3
  419. package/src/operations/errors.ts +5 -0
  420. package/src/operations/stale-policy.ts +1 -1
  421. package/src/operations/supervisor.ts +34 -10
  422. package/src/orchestrator/acp-delivery.ts +68 -0
  423. package/src/orchestrator/assignments.ts +27 -0
  424. package/src/orchestrator/busy.ts +15 -0
  425. package/src/orchestrator/config.ts +41 -0
  426. package/src/orchestrator/consumer-api.ts +24 -0
  427. package/src/orchestrator/contracts.ts +71 -0
  428. package/src/orchestrator/durable-assignments.ts +111 -0
  429. package/src/orchestrator/native-delegation.ts +103 -0
  430. package/src/orchestrator/orchestrator.ts +318 -0
  431. package/src/orchestrator/permissions.ts +25 -0
  432. package/src/orchestrator/policy.ts +44 -0
  433. package/src/orchestrator/pool.ts +123 -0
  434. package/src/orchestrator/tool-descriptions.ts +11 -0
  435. package/src/permissions/acp.ts +18 -0
  436. package/src/permissions/arrival.ts +13 -0
  437. package/src/permissions/consumer-config.ts +19 -0
  438. package/src/permissions/conversation.ts +280 -0
  439. package/src/permissions/matcher.ts +85 -0
  440. package/src/permissions/outcome.ts +15 -0
  441. package/src/permissions/policy.ts +81 -0
  442. package/src/permissions/request.ts +26 -0
  443. package/src/persistence/activity-projection.ts +1 -0
  444. package/src/persistence/backend.ts +34 -1
  445. package/src/persistence/channels.ts +23 -0
  446. package/src/persistence/index.ts +4 -0
  447. package/src/persistence/protocol-method.ts +5 -0
  448. package/src/persistence/reminder-wake.ts +49 -0
  449. package/src/persistence/reminders.ts +385 -0
  450. package/src/persistence/sqlite-backend.ts +84 -6
  451. package/src/persistence/sqlite-channels.ts +65 -0
  452. package/src/persistence/sqlite-reminders.ts +85 -0
  453. package/src/persistence/sqlite-schema.ts +108 -3
  454. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  455. package/src/persistence/sqlite-workers.ts +59 -0
  456. package/src/persistence/worker-delivery-contract.ts +104 -0
  457. package/src/persistence/worker-terminal-reason.ts +29 -0
  458. package/src/persistence/workers.ts +19 -0
  459. package/src/provider-notices.ts +137 -0
  460. package/src/repl/commands.ts +2 -2
  461. package/src/steering/combine.ts +3 -1
  462. package/src/steering/contracts.ts +11 -2
  463. package/src/steering/controller.ts +3 -2
  464. package/src/transport/acp-transport.ts +24 -14
  465. package/src/types.ts +15 -12
  466. package/src/updates.ts +14 -2
  467. package/src/wire-log.ts +1 -1
@@ -0,0 +1,125 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { LoadedScenario, ScenarioModelRecord, ScenarioSend } from "../../contracts/scenario.ts";
3
+ import { parseUniqueJson } from "../../util/json.ts";
4
+ import { ScriptedModelError } from "./scripted-error.ts";
5
+
6
+ const hash = (data: string | Uint8Array) => createHash("sha256").update(data).digest("hex");
7
+ export const scriptedCompatibilityKey = (digest: string, system: string) =>
8
+ `scripted-jsonl-v1:${digest}:${hash(JSON.stringify(system))}`;
9
+
10
+ function object(value: unknown): Record<string, unknown> {
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected an object");
12
+ return value as Record<string, unknown>;
13
+ }
14
+ function fields(value: Record<string, unknown>, names: readonly string[]) {
15
+ for (const key of Object.keys(value)) if (!names.includes(key)) throw new Error(`Unknown field ${key}`);
16
+ }
17
+ function text(value: unknown, name: string): string {
18
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${name} must be a nonblank string`);
19
+ return value;
20
+ }
21
+ function count(value: unknown, name: string): number {
22
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${name} must be a nonnegative safe integer`);
23
+ return value;
24
+ }
25
+ function list(value: unknown, name: string): unknown[] {
26
+ if (value === undefined) return [];
27
+ if (!Array.isArray(value)) throw new Error(`${name} must be an array`);
28
+ return value;
29
+ }
30
+ function canonical(value: unknown): unknown {
31
+ if (Array.isArray(value)) return value.map(canonical);
32
+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error("Non-finite JSON number");
33
+ if (value === null || typeof value !== "object") return value;
34
+ const record = object(value);
35
+ return Object.fromEntries(Object.keys(record).sort().map(key => [key, canonical(record[key])]));
36
+ }
37
+ function model(raw: Record<string, unknown>): ScenarioModelRecord {
38
+ fields(raw, ["type", "channelId", "delayMs", "chunks", "usage", "content", "calls", "failure", "wait"]);
39
+ const channelId = raw.channelId === undefined ? undefined : text(raw.channelId, "channelId");
40
+ const delayMs = raw.delayMs === undefined ? 0 : count(raw.delayMs, "delayMs");
41
+ const chunks = list(raw.chunks, "chunks").map(value => {
42
+ const chunk = object(value); fields(chunk, ["afterMs", "text"]);
43
+ if (typeof chunk.text !== "string" || chunk.text.length === 0) throw new Error("chunk.text must be nonempty");
44
+ return { afterMs: count(chunk.afterMs, "afterMs"), text: chunk.text };
45
+ });
46
+ const usage = raw.usage === undefined ? undefined : object(raw.usage);
47
+ if (usage) {
48
+ fields(usage, ["inputTokens", "outputTokens", "totalTokens"]);
49
+ for (const [key, value] of Object.entries(usage)) count(value, key);
50
+ }
51
+ const common = { type: "model" as const, channelId, delayMs, chunks, usage };
52
+ if (["content", "failure", "wait"].filter(key => Object.hasOwn(raw, key)).length !== 1)
53
+ throw new Error("Expected exactly one of content, failure or wait");
54
+ if (Object.hasOwn(raw, "content")) {
55
+ if (raw.content !== null && typeof raw.content !== "string") throw new Error("content must be a string or null");
56
+ if (chunks.length && (raw.content === null || chunks.map(chunk => chunk.text).join("") !== raw.content))
57
+ throw new Error("chunks must equal the final content");
58
+ const ids = new Set<string>();
59
+ const calls = list(raw.calls, "calls").map(value => {
60
+ const call = object(value); fields(call, ["id", "name", "arguments"]);
61
+ const id = text(call.id, "call.id");
62
+ if (ids.has(id)) throw new Error(`Duplicate call ID ${id}`);
63
+ ids.add(id);
64
+ return { id, name: text(call.name, "call.name"), arguments: canonical(object(call.arguments)) as Record<string, unknown> };
65
+ });
66
+ return { ...common, content: raw.content, calls };
67
+ }
68
+ if (Object.hasOwn(raw, "calls")) throw new Error("calls requires content");
69
+ if (Object.hasOwn(raw, "wait")) {
70
+ if (raw.wait !== "cancel") throw new Error("wait must be cancel");
71
+ return { ...common, wait: raw.wait };
72
+ }
73
+ const failure = object(raw.failure); fields(failure, ["kind", "message"]);
74
+ const kind = failure.kind;
75
+ if (kind !== "transient" && kind !== "provider" && kind !== "invalid_request" && kind !== "invalid_config") throw new Error("Unknown failure kind");
76
+ return { ...common, failure: { kind, message: text(failure.message, "failure.message") } };
77
+ }
78
+
79
+ export function parseScenario(bytes: Uint8Array, path = "<scenario>"): LoadedScenario {
80
+ const source = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
81
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
82
+ const defaultModels: ScenarioModelRecord[] = [], channelModels = new Map<string, ScenarioModelRecord[]>();
83
+ const sends: ScenarioSend[] = [], inputIds = new Set<string>();
84
+ let name = "", line = 0;
85
+ try {
86
+ for (let start = 0; start < source.length;) {
87
+ const newline = source.indexOf(10, start), end = newline < 0 ? source.length : newline;
88
+ line++;
89
+ const raw = object(parseUniqueJson(decoder.decode(source.subarray(start, end))));
90
+ start = end + 1;
91
+ if (line === 1) {
92
+ fields(raw, ["type", "version", "name"]);
93
+ if (raw.type !== "scenario" || raw.version !== 1) throw new Error("Expected scenario version 1");
94
+ name = text(raw.name, "name");
95
+ } else if (raw.type === "model") {
96
+ const record = model(raw);
97
+ if (record.channelId === undefined) defaultModels.push(record);
98
+ else {
99
+ const sequence = channelModels.get(record.channelId) ?? [];
100
+ sequence.push(record); channelModels.set(record.channelId, sequence);
101
+ }
102
+ } else if (raw.type === "send") {
103
+ fields(raw, ["type", "atMs", "channelId", "participantId", "inputId", "text"]);
104
+ const inputId = text(raw.inputId, "inputId");
105
+ if (inputIds.has(inputId)) throw new Error(`Duplicate input ID ${inputId}`);
106
+ inputIds.add(inputId);
107
+ sends.push({ type: "send", inputId, atMs: count(raw.atMs, "atMs"), channelId: text(raw.channelId, "channelId"),
108
+ participantId: text(raw.participantId, "participantId"), text: text(raw.text, "text") });
109
+ } else throw new Error("Unexpected record type");
110
+ }
111
+ if (!defaultModels.length && !channelModels.size) throw new Error("Expected at least one model record");
112
+ } catch (error) {
113
+ throw new ScriptedModelError("invalid_script", `${path}:${Math.max(1, line)}: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
115
+ const sequence = (records: ScenarioModelRecord[]) => records.map(({ type: _type, channelId: _channel, ...record }) => canonical(record));
116
+ const pairs = [...channelModels.keys()].sort().map(channel => [channel, sequence(channelModels.get(channel)!)]);
117
+ return { name, defaultModels, channelModels, sends, fileDigest: hash(source), modelDigest: hash(JSON.stringify([sequence(defaultModels), pairs])) };
118
+ }
119
+
120
+ export async function loadScenario(path: string): Promise<LoadedScenario> {
121
+ let data: ArrayBuffer;
122
+ try { data = await Bun.file(path).arrayBuffer(); }
123
+ catch (error) { throw new ScriptedModelError("script_load_failed", `Cannot read script ${path}: ${String(error)}`); }
124
+ return parseScenario(new Uint8Array(data), path);
125
+ }
@@ -0,0 +1,6 @@
1
+ export class ScriptedModelError extends Error {
2
+ constructor(public readonly code: "invalid_script" | "script_load_failed" | "script_exhausted", message: string) {
3
+ super(message);
4
+ this.name = "ScriptedModelError";
5
+ }
6
+ }
@@ -0,0 +1,81 @@
1
+ import { ScriptedModelError } from "./scripted-error.ts";
2
+ export { ScriptedModelError } from "./scripted-error.ts";
3
+ import type { Message, Model, ToolDefinition } from "../../contracts/loop.ts";
4
+
5
+ type Answer = Extract<Message, { role: "assistant" }>;
6
+ export interface CapturedRequest {
7
+ messages: Message[];
8
+ tools: ToolDefinition[];
9
+ }
10
+
11
+ function invalid(message: string): never { throw new ScriptedModelError("invalid_script", message); }
12
+ function object(value: unknown): value is Record<string, unknown> {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function fields(value: Record<string, unknown>, allowed: string[], path: string) {
16
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) invalid(`${path}: unknown field ${key}`);
17
+ }
18
+
19
+ function parseScript(value: unknown): Answer[] {
20
+ if (!object(value)) invalid("Script must be an object");
21
+ fields(value, ["version", "responses"], "script");
22
+ if (value.version !== 1) invalid("Expected script version 1");
23
+ if (!Array.isArray(value.responses) || !value.responses.length) invalid("responses must be a nonempty array");
24
+ return value.responses.map((response: unknown, index: number) => {
25
+ const path = `responses[${index}]`;
26
+ if (!object(response)) invalid(`${path} must be an object`);
27
+ fields(response, ["content", "calls"], path);
28
+ if (response.content !== null && typeof response.content !== "string") invalid(`${path}.content must be a string or null`);
29
+ const rawCalls = response.calls === undefined ? [] : response.calls;
30
+ if (!Array.isArray(rawCalls)) invalid(`${path}.calls must be an array`);
31
+ const ids = new Set<string>();
32
+ const calls = rawCalls.map((call: unknown, callIndex: number) => {
33
+ const location = `${path}.calls[${callIndex}]`;
34
+ if (!object(call)) invalid(`${location} must be an object`);
35
+ fields(call, ["id", "name", "arguments"], location);
36
+ if (typeof call.id !== "string" || !call.id.trim() || ids.has(call.id)) invalid(`${location}.id must be nonempty and unique within the response`);
37
+ if (typeof call.name !== "string" || !call.name.trim()) invalid(`${location}.name must be nonempty`);
38
+ if (!object(call.arguments)) invalid(`${location}.arguments must be a JSON object`);
39
+ ids.add(call.id);
40
+ return { id: call.id, name: call.name, arguments: JSON.stringify(call.arguments) };
41
+ });
42
+ return { role: "assistant", content: response.content, calls };
43
+ });
44
+ }
45
+
46
+ /** Consume one response per invocation, independently of all other instances.
47
+ * `startAt` skips responses already consumed by an earlier process, so a
48
+ * reopened session continues its script instead of replaying it. */
49
+ export function createScriptedModel(script: unknown, startAt = 0) {
50
+ // The JSON round trip enforces file-equivalent data and detaches input objects.
51
+ let answers: Answer[];
52
+ try { answers = parseScript(JSON.parse(JSON.stringify(script))); }
53
+ catch (error) {
54
+ if (error instanceof ScriptedModelError) throw error;
55
+ invalid(`Script must be JSON-serializable: ${String(error)}`);
56
+ }
57
+ const requests: CapturedRequest[] = [];
58
+ let position = startAt;
59
+ const modelAt = (step: number): Model => async (messages, tools) => {
60
+ requests.push(structuredClone({ messages: [...messages], tools: [...tools] }));
61
+ const answer = answers[step];
62
+ if (!answer) throw new ScriptedModelError("script_exhausted", `Script exhausted at model call ${requests.length}; ${answers.length} responses configured`);
63
+ position = step + 1;
64
+ return structuredClone(answer);
65
+ };
66
+ const model: Model = (messages, tools, signal) => modelAt(position)(messages, tools, signal);
67
+ return { model, modelAt, requests: () => structuredClone(requests), remaining: () => answers.length - position };
68
+ }
69
+
70
+ /** Run the step reserved by storage. Attempts never derive position from replies. */
71
+ export function scriptedAttempt(script: unknown, step: number): import("../../contracts/model-execution.ts").ModelAttempt {
72
+ const scripted = createScriptedModel(script, step);
73
+ return async function* (request, signal) {
74
+ try {
75
+ const answer = await scripted.model(request.messages, request.tools, signal);
76
+ if (!signal.aborted) yield { type: "response", response: { ...answer, stopReason: answer.calls.length ? "tool_calls" : "complete" } };
77
+ } catch (error) {
78
+ if (!signal.aborted) yield { type: "failure", kind: "invalid_request", message: String(error) };
79
+ }
80
+ };
81
+ }
@@ -0,0 +1,15 @@
1
+ import type { ModelAttemptSummary, ModelUsage } from "../../contracts/model-execution.ts";
2
+
3
+ /** Sum each attempt's latest absolute report once. Unknown fields stay absent;
4
+ * total is provider-reported and is never inferred from input plus output. */
5
+ export function aggregateUsage(attempts: readonly ModelAttemptSummary[]): ModelUsage {
6
+ const result: ModelUsage = {};
7
+ for (const attempt of attempts) for (const key of ["inputTokens", "outputTokens", "totalTokens"] as const) {
8
+ const value = attempt.usage?.[key];
9
+ if (value === undefined) continue;
10
+ const sum = (result[key] ?? 0) + value;
11
+ if (!Number.isSafeInteger(sum)) throw new RangeError("Aggregated usage exceeds safe integer range");
12
+ result[key] = sum;
13
+ }
14
+ return result;
15
+ }
@@ -0,0 +1,28 @@
1
+ import type { ExecuteTool, ToolDefinition } from "../../../contracts/loop.ts";
2
+
3
+ export const currentTimeDefinition: ToolDefinition = {
4
+ name: "current_time",
5
+ description: "Get the current UTC date and time.",
6
+ parameters: { type: "object", properties: {}, additionalProperties: false },
7
+ };
8
+
9
+ export const executeCurrentTime: ExecuteTool = async (call) => {
10
+ console.log(`[tool] ${call.name} ${call.arguments}`);
11
+ try {
12
+ // The advertised schema is not an execution gate: reject unknown tools and
13
+ // invalid arguments here even if the model was only shown this definition.
14
+ if (call.name !== "current_time") throw new Error(`Tool not allowed: ${call.name}`);
15
+ const args = JSON.parse(call.arguments);
16
+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).length) {
17
+ throw new Error("current_time requires an empty object");
18
+ }
19
+ const result = JSON.stringify({ ok: true, time: new Date().toISOString() });
20
+ console.log(`[result] ${result}`);
21
+ return result;
22
+ } catch (error) {
23
+ // Expected tool failures go back to the model so it can choose what to do.
24
+ const result = JSON.stringify({ ok: false, error: String(error) });
25
+ console.log(`[result] ${result}`);
26
+ return result;
27
+ }
28
+ };
@@ -0,0 +1,17 @@
1
+ import type { SessionAgent } from "../../../contracts/agent.ts";
2
+ import type { ToolDefinition } from "../../../contracts/loop.ts";
3
+
4
+ export const notifyChannelDefinition: ToolDefinition = {
5
+ name: "notify_channel",
6
+ description: "Deliver important information to an existing channel. Acceptance does not mean the target has acted.",
7
+ parameters: { type: "object", properties: { channelId: { type: "string" }, text: { type: "string" } },
8
+ required: ["channelId", "text"], additionalProperties: false },
9
+ };
10
+
11
+ export function executeNotice(args: Record<string, unknown>, notify: (channel: string, text: string) => ReturnType<SessionAgent["notify"]>) {
12
+ if (!args || Array.isArray(args) || Object.keys(args).some(key => !["channelId", "text"].includes(key))
13
+ || typeof args.channelId !== "string" || !args.channelId.trim() || typeof args.text !== "string" || !args.text.trim())
14
+ throw new Error("notify_channel requires channelId and text");
15
+ const receipt = notify(args.channelId, args.text);
16
+ return receipt.accepted ? { accepted: true } : { accepted: false, error: receipt.error };
17
+ }
@@ -0,0 +1,13 @@
1
+ import { testEcho, testEchoDefinition } from "./test-echo.ts";
2
+ import { testWait, testWaitDefinition } from "./test-wait.ts";
3
+ import { testFail, testFailDefinition } from "./test-fail.ts";
4
+
5
+ export const debugToolDefinitions = [testEchoDefinition, testWaitDefinition, testFailDefinition];
6
+
7
+ export const debugToolHandlers = new Map([
8
+ [testEchoDefinition.name, testEcho],
9
+ [testWaitDefinition.name, testWait],
10
+ [testFailDefinition.name, testFail],
11
+ ]);
12
+
13
+ export { testEcho, testEchoDefinition, testWait, testWaitDefinition, testFail, testFailDefinition };
@@ -0,0 +1,12 @@
1
+ import type { ToolExecutionResult } from "../../../contracts/loop.ts";
2
+
3
+ export function debugFailure(code: "invalid_arguments" | "debug_failure", message: string): ToolExecutionResult {
4
+ return { content: JSON.stringify({ ok: false, error: { code, message } }), outcome: { status: "failed", code } };
5
+ }
6
+
7
+ export function debugArguments(raw: string): Record<string, unknown> | undefined {
8
+ try {
9
+ const value: unknown = JSON.parse(raw);
10
+ if (value && typeof value === "object" && !Array.isArray(value)) return value as Record<string, unknown>;
11
+ } catch { /* The executor reports a typed argument error. */ }
12
+ }
@@ -0,0 +1,16 @@
1
+ import type { ExecuteTool, ToolExecutionResult, ToolDefinition } from "../../../contracts/loop.ts";
2
+ import { debugArguments, debugFailure } from "./result.ts";
3
+
4
+ const maxBytes = 1024;
5
+ export const testEchoDefinition: ToolDefinition = {
6
+ name: "test_echo",
7
+ description: "Debug only. Return the supplied text exactly, up to 1024 UTF-8 bytes.",
8
+ parameters: { type: "object", properties: { text: { type: "string", maxLength: maxBytes } },
9
+ required: ["text"], additionalProperties: false },
10
+ };
11
+ export const testEcho: ExecuteTool<string | ToolExecutionResult> = async ({ arguments: raw }) => {
12
+ const args = debugArguments(raw);
13
+ if (!args || typeof args.text !== "string" || Object.keys(args).length !== 1 || Buffer.byteLength(args.text) > maxBytes)
14
+ return debugFailure("invalid_arguments", "Expected only text, up to 1024 UTF-8 bytes.");
15
+ return JSON.stringify({ ok: true, text: args.text });
16
+ };
@@ -0,0 +1,14 @@
1
+ import type { ExecuteTool, ToolExecutionResult, ToolDefinition } from "../../../contracts/loop.ts";
2
+ import { debugArguments, debugFailure } from "./result.ts";
3
+
4
+ export const testFailDefinition: ToolDefinition = {
5
+ name: "test_fail",
6
+ description: "Debug only. Return an intentional typed failure and let the turn continue.",
7
+ parameters: { type: "object", properties: {}, additionalProperties: false },
8
+ };
9
+ export const testFail: ExecuteTool<ToolExecutionResult> = async ({ arguments: raw }) => {
10
+ const args = debugArguments(raw);
11
+ if (!args || Object.keys(args).length)
12
+ return debugFailure("invalid_arguments", "Expected an empty object.");
13
+ return debugFailure("debug_failure", "Intentional test failure.");
14
+ };
@@ -0,0 +1,19 @@
1
+ import { setTimeout } from "node:timers/promises";
2
+ import type { ExecuteTool, ToolExecutionResult, ToolDefinition } from "../../../contracts/loop.ts";
3
+ import { debugArguments, debugFailure } from "./result.ts";
4
+
5
+ export const testWaitDefinition: ToolDefinition = {
6
+ name: "test_wait",
7
+ description: "Debug only. Hold this tool call for the requested duration so another channel can send input or the operator can interrupt. Performs no external work.",
8
+ parameters: { type: "object", properties: { durationMs: { type: "integer", minimum: 1, maximum: 30_000 } },
9
+ required: ["durationMs"], additionalProperties: false },
10
+ };
11
+ export const testWait: ExecuteTool<string | ToolExecutionResult> = async ({ arguments: raw }, signal) => {
12
+ const args = debugArguments(raw);
13
+ const durationMs = args?.durationMs;
14
+ if (!args || typeof durationMs !== "number" || !Number.isSafeInteger(durationMs) || durationMs < 1 || durationMs > 30_000 || Object.keys(args).length !== 1)
15
+ return debugFailure("invalid_arguments", "Expected only durationMs, an integer between 1 and 30000.");
16
+ signal?.throwIfAborted();
17
+ await setTimeout(durationMs, undefined, { signal });
18
+ return JSON.stringify({ ok: true, durationMs });
19
+ };
@@ -0,0 +1,75 @@
1
+ import type { ToolDefinition } from "../../../contracts/loop.ts";
2
+ import type { AgentReminderSchedule } from "../../../contracts/reminders.ts";
3
+ import { SESSION_INPUT_MAX_BYTES } from "../../../contracts/input-limits.ts";
4
+ import { REMINDER_LIMITS, reminderInstant } from "../../../util/reminder-schedule.ts";
5
+ import type { ReminderStorage } from "../../../contracts/storage.ts";
6
+ import type { ReminderChannelEvent } from "../../../contracts/reminders.ts";
7
+
8
+ const names = ["schedule_reminder", "list_reminders", "cancel_reminder"] as const;
9
+ export const isReminderTool = (name: string) => names.some(candidate => candidate === name);
10
+ const string = { type: "string" };
11
+ const grace = { type: ["integer", "null"] };
12
+ export const reminderDefinitions: ToolDefinition[] = [
13
+ { name: "schedule_reminder", description: "Schedule a one-off reminder in the current channel. Use UTC at or a relative duration such as 5m.",
14
+ parameters: { type: "object", properties: { schedule: { type: "object", properties: { at: string, in: string }, additionalProperties: false }, text: string, expiresAfter: grace },
15
+ required: ["schedule", "text"], additionalProperties: false } },
16
+ { name: "list_reminders", description: "List reminders in the current channel.", parameters: {
17
+ type: "object", properties: { after: string, limit: { type: "integer" } }, additionalProperties: false } },
18
+ { name: "cancel_reminder", description: "Cancel a reminder in the current channel.", parameters: {
19
+ type: "object", properties: { id: string }, required: ["id"], additionalProperties: false } },
20
+ ];
21
+
22
+ const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
23
+ const allowed = (value: Record<string, unknown>, keys: string[]) => Object.keys(value).every(key => keys.includes(key));
24
+ const text = (value: unknown): value is string => typeof value === "string" && !!value.trim() && Buffer.byteLength(value) <= SESSION_INPUT_MAX_BYTES;
25
+
26
+ export type ReminderAction =
27
+ | { kind: "schedule"; schedule: AgentReminderSchedule; text: string; expiresAfter?: number | null }
28
+ | { kind: "list"; after?: string; limit?: number }
29
+ | { kind: "cancel"; id: string };
30
+
31
+ export function reminderAction(tool: string, input: unknown): ReminderAction | undefined {
32
+ if (!object(input)) return;
33
+ if (tool === "cancel_reminder") {
34
+ if (allowed(input, ["id"]) && text(input.id)) return { kind: "cancel", id: input.id };
35
+ return;
36
+ }
37
+ if (tool === "list_reminders") {
38
+ if (!allowed(input, ["after", "limit"])) return;
39
+ const { after, limit } = input;
40
+ if (after !== undefined && !text(after)) return;
41
+ if (limit !== undefined && (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > 100)) return;
42
+ return { kind: "list", ...(after === undefined ? {} : { after }), ...(limit === undefined ? {} : { limit }) };
43
+ }
44
+ if (!allowed(input, ["schedule", "text", "expiresAfter"]) || !text(input.text)) return;
45
+ const { schedule, expiresAfter } = input;
46
+ if (expiresAfter !== undefined && expiresAfter !== null && (typeof expiresAfter !== "number" || !Number.isSafeInteger(expiresAfter)
47
+ || expiresAfter < REMINDER_LIMITS.minExpiryGraceMs || expiresAfter > REMINDER_LIMITS.maxExpiryGraceMs)) return;
48
+ if (!object(schedule) || Object.keys(schedule).length !== 1) return;
49
+ const payload = { kind: "schedule" as const, text: input.text, ...(expiresAfter === undefined ? {} : { expiresAfter }) };
50
+ if (text(schedule.at) && reminderInstant(schedule.at) !== undefined) return { ...payload, schedule: { at: schedule.at } };
51
+ if (text(schedule.in) && /^[1-9]\d*[mhd]$/.test(schedule.in)) return { ...payload, schedule: { in: schedule.in } };
52
+ }
53
+
54
+
55
+ export function executeReminderTool(
56
+ storage: ReminderStorage, action: ReminderAction, channel: string, turnId: number, invocationId: string,
57
+ policies: readonly string[], now: number, publish: (event: ReminderChannelEvent, revision: number) => void,
58
+ ): string {
59
+ if (action.kind === "list") {
60
+ const result = storage.listReminders({ channel, after: action.after, limit: action.limit });
61
+ return JSON.stringify(result.ok ? result.value : { error: result.error.code });
62
+ }
63
+ if (action.kind === "cancel") {
64
+ const result = storage.cancelAgentReminder(turnId, action.id);
65
+ if (!result.ok) return JSON.stringify({ error: result.error.code });
66
+ const { changed, ...value } = result.value;
67
+ if (changed) publish({ type: "reminder_cancelled", reminderId: value.id, by: "agent" }, result.revision);
68
+ return JSON.stringify(value);
69
+ }
70
+ const result = storage.scheduleAgentReminder(turnId, invocationId, action.schedule, action.text, policies, action.expiresAfter, now);
71
+ if (!result.ok) return JSON.stringify({ error: result.error.code });
72
+ const { reminder, created } = result.value;
73
+ if (created) publish({ type: "reminder_changed", reminder }, result.revision);
74
+ return JSON.stringify({ id: reminder.id, nextRunAt: reminder.nextRunAt });
75
+ }
@@ -0,0 +1,103 @@
1
+ import { timelineToolNames } from "../../../util/timeline-tool-names.ts";
2
+ import type { ToolDefinition } from "../../../contracts/loop.ts";
3
+ import type { ToolAvailability, ToolCatalogInput, ToolRegistration } from "../../../contracts/tools.ts";
4
+
5
+ /** A catalog the open must refuse, or a runtime operation on the wrong entry. */
6
+ export class CatalogError extends Error {
7
+ constructor(readonly code: "invalid_params" | "not_found" | "invalid_state", message: string) { super(message); }
8
+ }
9
+ const invalid = (message: string): never => { throw new CatalogError("invalid_params", message); };
10
+ const word = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
11
+ const duration = (value: unknown) => Number.isSafeInteger(value) && (value as number) > 0;
12
+
13
+ /** The scoped reader for results held by their producer. Offered whenever a
14
+ * catalog exists; its name is reserved. */
15
+ export const READ_TOOL_RESULT = "read_tool_result";
16
+ export const readToolResultDefinition: ToolDefinition = {
17
+ name: READ_TOOL_RESULT,
18
+ description: "Read part of a tool result that was too large to show in full. Use the result_id from that result. Only results produced in this conversation can be read.",
19
+ parameters: { type: "object", properties: { result_id: { type: "string" }, offset: { type: "integer", minimum: 0 }, length: { type: "integer", minimum: 1 } },
20
+ required: ["result_id"], additionalProperties: false },
21
+ };
22
+
23
+ /** Validate the whole catalog before anything is opened (decision 0021).
24
+ * `reserved` are the names of tools the session already has. */
25
+ export function parseCatalog(raw: unknown, reserved: readonly string[]): ToolCatalogInput {
26
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid("tools must be an object");
27
+ const input = raw as Record<string, unknown>;
28
+ for (const key of Object.keys(input)) if (!["catalog", "enabled", "defaultDeadlineMs"].includes(key)) invalid(`tools: unsupported field ${key}`);
29
+ if (!Array.isArray(input.catalog)) return invalid("tools.catalog must be an array");
30
+ const names = new Set<string>([...reserved, ...timelineToolNames, READ_TOOL_RESULT, "notify_channel"]);
31
+ const catalog = input.catalog.map((value, index): ToolRegistration => {
32
+ const at = `tools.catalog[${index}]`;
33
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid(`${at} must be an object`);
34
+ const entry = value as Record<string, unknown>;
35
+ for (const key of Object.keys(entry)) if (!["name", "description", "parameters", "handler", "group", "deadlineMs"].includes(key)) invalid(`${at}: unsupported field ${key}`);
36
+ if (!word(entry.name)) return invalid(`${at}.name must be a nonempty string`);
37
+ if (names.has(entry.name)) invalid(`${at}: tool name ${entry.name} is already used`);
38
+ names.add(entry.name);
39
+ if (typeof entry.description !== "string") invalid(`${at}.description must be a string`);
40
+ if (!entry.parameters || typeof entry.parameters !== "object" || Array.isArray(entry.parameters)) invalid(`${at}.parameters must be a JSON schema object`);
41
+ if (!word(entry.handler)) invalid(`${at}.handler must be a nonempty string`);
42
+ if (entry.group !== "fixed" && entry.group !== "revocable" && entry.group !== "runtime") invalid(`${at}.group must be fixed, revocable or runtime`);
43
+ if (entry.deadlineMs !== undefined && !duration(entry.deadlineMs)) invalid(`${at}.deadlineMs must be a positive integer`);
44
+ return { name: entry.name, description: entry.description as string, parameters: structuredClone(entry.parameters) as Record<string, unknown>,
45
+ handler: entry.handler as string, group: entry.group as ToolRegistration["group"], ...(entry.deadlineMs === undefined ? {} : { deadlineMs: entry.deadlineMs as number }) };
46
+ });
47
+ const runtime = new Set(catalog.filter(entry => entry.group === "runtime").map(entry => entry.name));
48
+ if (input.enabled !== undefined && (!Array.isArray(input.enabled) || input.enabled.some(name => !word(name) || !runtime.has(name)) || new Set(input.enabled).size !== input.enabled.length))
49
+ invalid("tools.enabled must list distinct runtime tool names");
50
+ if (input.defaultDeadlineMs !== undefined && !duration(input.defaultDeadlineMs)) invalid("tools.defaultDeadlineMs must be a positive integer");
51
+ return { catalog, ...(input.enabled === undefined ? {} : { enabled: [...input.enabled as string[]] }),
52
+ ...(input.defaultDeadlineMs === undefined ? {} : { defaultDeadlineMs: input.defaultDeadlineMs as number }) };
53
+ }
54
+
55
+ /** Two catalog inputs ask for the same thing (a repeated load must). */
56
+ export const sameCatalog = (left: ToolCatalogInput, right: ToolCatalogInput) => JSON.stringify(canonical(left)) === JSON.stringify(canonical(right));
57
+ const canonical = (input: ToolCatalogInput) => [input.catalog.map(entry => [entry.name, entry.description, JSON.stringify(entry.parameters), entry.handler, entry.group, entry.deadlineMs ?? null]),
58
+ [...input.enabled ?? []].sort(), input.defaultDeadlineMs ?? null];
59
+
60
+ export interface ToolCatalog {
61
+ readonly entries: readonly ToolRegistration[];
62
+ readonly defaultDeadlineMs?: number;
63
+ get(name: string): ToolRegistration | undefined;
64
+ /** Why the entry cannot run now, or undefined if it can. Policy is not consulted. */
65
+ unavailable(name: string): ToolAvailability["reason"] | "unknown" | undefined;
66
+ availability(entry: ToolRegistration): ToolAvailability;
67
+ /** The handler names the current connection serves. */
68
+ serve(handlers: readonly string[]): void;
69
+ setRevoked(names: readonly string[]): void;
70
+ setEnabled(name: string, enabled: boolean): void;
71
+ /** Available entries, fixed group first, then by name: a stable order for the model. */
72
+ offered(): { fixed: ToolRegistration[]; changeable: ToolRegistration[] };
73
+ }
74
+
75
+ /** The catalog's state. Definitions come from the open; the revoked set mirrors
76
+ * storage; the enabled set and the served handlers are process state. */
77
+ export function createToolCatalog(input: ToolCatalogInput, revoked: readonly string[]): ToolCatalog {
78
+ const entries = input.catalog.map(entry => structuredClone(entry));
79
+ const byName = new Map(entries.map(entry => [entry.name, entry]));
80
+ let revokedNames = new Set(revoked), served = new Set<string>();
81
+ const enabled = new Set(input.enabled ?? []);
82
+ const reason = (entry: ToolRegistration): ToolAvailability["reason"] | undefined =>
83
+ entry.group === "revocable" && revokedNames.has(entry.name) ? "revoked"
84
+ : entry.group === "runtime" && !enabled.has(entry.name) ? "not_enabled"
85
+ : !served.has(entry.handler) ? "handler_missing" : undefined;
86
+ const byNameOrder = (left: ToolRegistration, right: ToolRegistration) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
87
+ return {
88
+ entries, ...(input.defaultDeadlineMs === undefined ? {} : { defaultDeadlineMs: input.defaultDeadlineMs }),
89
+ get: name => byName.get(name),
90
+ unavailable(name) { const entry = byName.get(name); return entry ? reason(entry) : "unknown"; },
91
+ availability(entry) {
92
+ const why = reason(entry);
93
+ return { name: entry.name, group: entry.group, handler: entry.handler, available: why === undefined, ...(why === undefined ? {} : { reason: why }) };
94
+ },
95
+ serve(handlers) { served = new Set(handlers); },
96
+ setRevoked(names) { revokedNames = new Set(names); },
97
+ setEnabled(name, on) { if (on) enabled.add(name); else enabled.delete(name); },
98
+ offered() {
99
+ const available = entries.filter(entry => reason(entry) === undefined);
100
+ return { fixed: available.filter(entry => entry.group === "fixed").sort(byNameOrder), changeable: available.filter(entry => entry.group !== "fixed").sort(byNameOrder) };
101
+ },
102
+ };
103
+ }