@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,235 @@
1
+ import { nativePermissionRequests, permissionOutcome } from "../permissions/conversation.ts";
2
+ import { recordingPermissionHandlers } from "../permissions/policy.ts";
3
+ /**
4
+ * Phase 3 of a turn: the handlers that record and present what the provider streams (assistant
5
+ * messages, activity, permissions), wrapping the consumer's own handlers. Moved unchanged from
6
+ * `AgentSession.runPrompt` (controller-interface spec, Brief A2 step 1). Building them is
7
+ * synchronous; they only run once the provider call starts.
8
+ */
9
+ import { transcriptParts, type ResolvedPart } from "../media/parts.ts";
10
+ import { ResponseAccumulator } from "../response.ts";
11
+ import type { AgentSessionPromptResult } from "../agent-conversation-contracts.ts";
12
+ import type { PreparedTurn } from "../conversation-controller/contracts.ts";
13
+ import type { Logger } from "../logger.ts";
14
+ import type { PromptHandlers } from "../types.ts";
15
+ import type { TurnRunContext } from "./context.ts";
16
+ import {
17
+ toPersistenceJsonValue,
18
+ } from "./record-helpers.ts";
19
+
20
+ export type AssistantStatus = "in_progress" | "completed" | "cancelled" | "error";
21
+
22
+ export interface TurnRecording {
23
+ readonly chunks: string[];
24
+ readonly response: ResponseAccumulator;
25
+ /** When each message that ended before the turn did received its last text, in order. */
26
+ readonly messageEnds: string[];
27
+ /** How many assistant messages the turn has begun. */
28
+ readonly assistantOrdinal: number;
29
+ readonly handlers: PromptHandlers;
30
+ beginAssistantMessage(providerMessageId?: string): { text: string; dirty: boolean };
31
+ flushAssistantMessage(status: AssistantStatus, stopReason?: string, force?: boolean, ended?: boolean): void;
32
+ }
33
+
34
+ /** `consumer` are the handlers of the turn's messages, wrapped by the recording handlers. */
35
+ export function createTurnRecording(
36
+ ctx: TurnRunContext,
37
+ turnId: string,
38
+ consumer: PromptHandlers | undefined,
39
+ ): TurnRecording {
40
+ const chunks: string[] = [];
41
+ const response = new ResponseAccumulator();
42
+ let assistantOrdinal = 0;
43
+ let assistantMessage: {
44
+ readonly id: string;
45
+ providerMessageId?: string;
46
+ text: string;
47
+ parts?: readonly ResolvedPart[];
48
+ revision: number;
49
+ dirty: boolean;
50
+ } | null = null;
51
+ const beginAssistantMessage = (providerMessageId?: string) => {
52
+ assistantOrdinal++;
53
+ assistantMessage = {
54
+ id: `message:${turnId}:assistant:${assistantOrdinal}`,
55
+ ...(providerMessageId === undefined ? {} : { providerMessageId }),
56
+ text: "",
57
+ revision: 0,
58
+ dirty: false,
59
+ };
60
+ return assistantMessage;
61
+ };
62
+ // When each message that ended before the turn did received its last text, in order. The
63
+ // turn's commit records those messages as completed at these times; only the last message
64
+ // takes the turn's own outcome.
65
+ const messageEnds: string[] = [];
66
+ const flushAssistantMessage = (
67
+ status: AssistantStatus,
68
+ stopReason?: string,
69
+ force = false,
70
+ ended = false,
71
+ ) => {
72
+ if ((!ctx.persistence.v2Transcript && !ctx.owner.lifecycle) || !assistantMessage
73
+ || (!assistantMessage.dirty && !force)) return;
74
+ assistantMessage.revision++;
75
+ assistantMessage.dirty = false;
76
+ const message = assistantMessage;
77
+ const timestamp = new Date().toISOString();
78
+ if (ended) messageEnds.push(timestamp);
79
+ if (ctx.owner.agentSessionId && (status === "in_progress" || ended)) {
80
+ ctx.owner.queueRecord({
81
+ recordId: `${message.id}:snapshot:${message.revision}`,
82
+ agentSessionId: ctx.owner.agentSessionId,
83
+ agentConversationId: ctx.owner.agentConversationId,
84
+ kind: "message",
85
+ timestamp,
86
+ operationId: turnId,
87
+ role: "assistant",
88
+ logicalMessageId: message.id,
89
+ content: message.text,
90
+ status: ended ? "completed" : "in_progress",
91
+ metadata: JSON.stringify({ operationId: turnId,
92
+ ...(message.providerMessageId ? { providerMessageId: message.providerMessageId } : {}) }),
93
+ }, message.parts);
94
+ }
95
+ if (ctx.persistence.v2Transcript) ctx.presentation.queuePresentation({
96
+ kind: "message",
97
+ operationId: turnId,
98
+ role: "assistant",
99
+ text: message.parts ? transcriptParts(message.parts) : message.text,
100
+ ...(message.providerMessageId === undefined ? {} : { providerMessageId: message.providerMessageId }),
101
+ structured: {
102
+ version: 1,
103
+ messages: [message.providerMessageId === undefined
104
+ ? { text: message.text }
105
+ : { messageId: message.providerMessageId, text: message.text }],
106
+ },
107
+ status,
108
+ ...(stopReason === undefined ? {} : { stopReason }),
109
+ presentation: { id: message.id, revision: message.revision },
110
+ });
111
+ };
112
+ // A message receives no more text once the next message or a tool call begins. Record it
113
+ // completed then, rather than leaving it open until the turn ends.
114
+ const endAssistantMessage = () => {
115
+ flushAssistantMessage("completed", undefined, true, true);
116
+ assistantMessage = null;
117
+ };
118
+ const handlers: PromptHandlers = {
119
+ ...consumer,
120
+ // Fired from here, from the one aggregator this session owns — nothing below needs
121
+ // to know the handler exists, and two places firing it would be two folds.
122
+ onRecord: undefined,
123
+ onChunk: (chunk) => {
124
+ chunks.push(chunk);
125
+ consumer?.onChunk?.(chunk);
126
+ },
127
+ onResponseChunk: (chunk) => {
128
+ const settledReasoning = ctx.presentation.closeReasoningBoundary();
129
+ if (settledReasoning) {
130
+ ctx.turn.queueActivityRecords(turnId, [settledReasoning]);
131
+ consumer?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
132
+ }
133
+ response.append(chunk);
134
+ if (ctx.persistence.v2Transcript || ctx.owner.lifecycle) {
135
+ if (chunk.startsMessage) {
136
+ endAssistantMessage();
137
+ beginAssistantMessage(chunk.messageId);
138
+ }
139
+ const current = assistantMessage ?? beginAssistantMessage(chunk.messageId);
140
+ if (current.providerMessageId === undefined && chunk.messageId !== undefined) {
141
+ current.providerMessageId = chunk.messageId;
142
+ }
143
+ current.text += chunk.text;
144
+ current.parts = response.currentParts();
145
+ current.dirty = true;
146
+ // Persist the first usable snapshot. Later token chunks remain in memory until
147
+ // an interleaving item, a new message, or the operation boundary.
148
+ if (current.revision === 0) flushAssistantMessage("in_progress");
149
+ }
150
+ consumer?.onResponseChunk?.(chunk);
151
+ },
152
+ onActivity: (event) => {
153
+ // The message snapshot must enter the shared queue before an activity first seen
154
+ // after it. Later activity revisions keep their original presentation position.
155
+ if (event.kind === "tool") endAssistantMessage();
156
+ else flushAssistantMessage("in_progress");
157
+ if (!ctx.supervising) ctx.steering.observeActivity(turnId, event);
158
+ const result = ctx.presentation.applyActivity(event);
159
+ ctx.turn.queueActivityRecords(turnId, result.emitted);
160
+ consumer?.onRecord?.(result);
161
+ consumer?.onActivity?.(event);
162
+ },
163
+ onPermissionRequest: async (request, signal) => {
164
+ const permissionBase = `${turnId}:permission:${request.toolCallId}`;
165
+ const agentSessionId = nativePermissionRequests.get(request)?.hostHandled ? null : ctx.owner.agentSessionId;
166
+ const resolution = await ctx.permissions.request(turnId, request, ctx.session.permissionPolicy, consumer, signal,
167
+ agentSessionId ? () => ctx.owner.recordNow({
168
+ recordId: `${permissionBase}:requested`,
169
+ agentSessionId,
170
+ agentConversationId: ctx.owner.agentConversationId,
171
+ kind: "permission",
172
+ timestamp: new Date().toISOString(),
173
+ operationId: turnId,
174
+ permissionId: request.toolCallId,
175
+ state: "requested",
176
+ request: toPersistenceJsonValue({
177
+ toolCallId: request.toolCallId,
178
+ ...(request.title ? { title: request.title } : {}),
179
+ options: request.options,
180
+ raw: request.raw,
181
+ }),
182
+ }) : undefined);
183
+ if (agentSessionId) {
184
+ const recorded = ctx.owner.recordNow({
185
+ recordId: `${permissionBase}:resolved`,
186
+ agentSessionId,
187
+ agentConversationId: ctx.owner.agentConversationId,
188
+ kind: "permission",
189
+ timestamp: new Date().toISOString(),
190
+ operationId: turnId,
191
+ permissionId: request.toolCallId,
192
+ state: "resolved",
193
+ outcome: permissionOutcome(request, resolution),
194
+ });
195
+ // The owner tail keeps the record ordered. A timed-out refusal can reach the provider now.
196
+ if (resolution.by === "timeout") void recorded.catch(() => undefined);
197
+ else await recorded;
198
+ }
199
+ return resolution.outcome;
200
+ },
201
+ };
202
+
203
+ recordingPermissionHandlers.add(handlers.onPermissionRequest!);
204
+ return {
205
+ chunks,
206
+ response,
207
+ messageEnds,
208
+ get assistantOrdinal() { return assistantOrdinal; },
209
+ handlers,
210
+ beginAssistantMessage,
211
+ flushAssistantMessage,
212
+ };
213
+ }
214
+
215
+ /** Store recovered text without publishing it as part of the already-settled live result. */
216
+ export async function stoppedRepliesForPersistence(
217
+ log: Logger, recover: NonNullable<PreparedTurn["recoverStoppedReplies"]>,
218
+ result: AgentSessionPromptResult, recording: TurnRecording,
219
+ ) {
220
+ const messageEnds = [...recording.messageEnds];
221
+ let extra: Awaited<ReturnType<typeof recover>>;
222
+ try {
223
+ extra = await recover(result.messages);
224
+ const stoppedAt = new Date().toISOString();
225
+ for (let index = 0; index < (extra?.length ?? 0); index++) messageEnds[result.messages.length + index] = stoppedAt;
226
+ } catch (error) {
227
+ log.warn("native_stopped_reply_recovery_failed", { operationId: result.operationId, error: String(error) });
228
+ const seen = new Set(result.messages.map(message => message.messageId));
229
+ // Keep the draft as an incomplete reply if the authoritative read could not finish.
230
+ extra = recording.response.snapshot().filter(message => !seen.has(message.messageId));
231
+ }
232
+ if (!extra?.length) return { result, messageEnds };
233
+ const messages = [...result.messages, ...extra];
234
+ return { result: { ...result, messages, text: messages.map(message => message.text).join("\n\n") }, messageEnds };
235
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * One prompt turn, moved intact from `AgentSession.runPrompt` (controller-interface spec, Brief A2
3
+ * step 1). The phases run in today's order and stay in one async function: splitting the awaited
4
+ * phases into separate functions would add scheduling points between them, and the turn path's
5
+ * record writes are sensitive to interleaving. The synchronous recording handlers (phase 3) live
6
+ * in `recording.ts`.
7
+ *
8
+ * The session can replace members the turn reads (see `context.ts`), so they are read where the
9
+ * original read them, not cached.
10
+ *
11
+ * 1. prepare: Agent-owned `beforePrompt` (participants, media, identity, user record), the turn's
12
+ * bookkeeping;
13
+ * 2. user records and the metered operation, per persistence mode: managed opens the metered
14
+ * operation (preflight) before any durable record; detached appends the legacy user line
15
+ * first;
16
+ * 3. the recording handlers (`createTurnRecording`);
17
+ * 4. dispatch through the controller under the supervisor;
18
+ * 5. assistant records; metering closed before local persistence; transcript closed;
19
+ * 6. Agent-owned `afterPrompt` (identity delivery receipt, provider attachment);
20
+ * on failure: what was streamed is still recorded at its real status, metering closed once,
21
+ * and the error rethrown.
22
+ */
23
+ import type { AgentSessionPromptResult } from "../agent-conversation-contracts.ts";
24
+ import { OwnedPromptPostCommitError } from "../agent-conversation-owner.ts";
25
+ import { unresolvedParts } from "../media/parts.ts";
26
+ import type { PreparedTurn } from "../conversation-controller/contracts.ts";
27
+ import type { OpenOperation } from "../metering/engine.ts";
28
+ import { AgentSessionOperationError, type OperationMeteringRecord } from "../metering/record.ts";
29
+ import { OperationStalledError } from "../operations/errors.ts";
30
+ import {
31
+ acknowledgeProviderAttachment,
32
+ recordedProviderAttachment,
33
+ } from "../persistence/provider-attachment.ts";
34
+ import { mediaCapabilitiesOf } from "../conversation-controller/capabilities.ts";
35
+ import { isDegradedController } from "../conversation-controller/guards.ts";
36
+ import type { ResponseMessage } from "../types.ts";
37
+ import { backendTurnItem } from "./backend-turns.ts";
38
+ import type { TurnContext, TurnRunContext } from "./context.ts";
39
+ import { createTurnRecording, stoppedRepliesForPersistence } from "./recording.ts";
40
+ import { legacyTranscriptMessages, legacyTranscriptText, persistenceOperationKind } from "./record-helpers.ts";
41
+
42
+ export async function runTurn(ctx: TurnRunContext, turn: TurnContext): Promise<AgentSessionPromptResult> {
43
+ const { turnId } = turn;
44
+ // Today's preparation needs the turn's messages. A turn the backend started has none: it is metered and
45
+ // recorded like any turn, but has no user message, no ACP content and only the session's own handlers.
46
+ const sent = turn.messages !== undefined;
47
+ const item = turn.messages ?? backendTurnItem(turnId, turn.handlers);
48
+ // Phase 1: prepare.
49
+ const targetProviderContextId = ctx.owner.lifecycle
50
+ ? ctx.session.internalSessionId ?? `runtime:${ctx.owner.contextNonce()}`
51
+ : undefined;
52
+ const owned = ctx.owner.lifecycle && sent
53
+ ? await ctx.owner.lifecycle.beforePrompt({
54
+ operationId: turnId,
55
+ agentSessionId: ctx.owner.agentSessionId!,
56
+ agentConversationId: ctx.owner.agentConversationId,
57
+ targetProviderContextId,
58
+ ...(item.participantId ? { participantId: item.participantId } : {}),
59
+ ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
60
+ ...(item.parts ? { parts: item.parts } : {}),
61
+ text: item.text,
62
+ messageParts: item.messageParts,
63
+ attachments: item.attachments,
64
+ mediaContext: {
65
+ cwd: ctx.session.cwd ?? process.cwd(),
66
+ ...(isDegradedController(ctx.controller)
67
+ ? { degraded: true }
68
+ : { capabilities: mediaCapabilitiesOf(ctx.controller.conversationCapabilities.backend) }),
69
+ },
70
+ })
71
+ : undefined;
72
+ for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
73
+ ctx.session.learnParticipant(participant);
74
+ }
75
+ ctx.turn.begin(turnId);
76
+
77
+ // Phase 2: user records and the metered operation, per persistence mode.
78
+ let operation: OpenOperation;
79
+ if (ctx.persistence.v2Transcript) {
80
+ let transcriptStarted = false;
81
+ try {
82
+ // Metering preflight has no provider side effect. Run it before minting durable
83
+ // operation evidence so a strict pricing/policy rejection needs no abort record.
84
+ operation = await ctx.metering.open(item);
85
+ await ctx.persistence.v2Transcript!.beginOperation(turnId, persistenceOperationKind(item.operationKind));
86
+ transcriptStarted = true;
87
+ // A combined prompt shows each original message, as it was sent; a backend-started turn has none.
88
+ const userTexts = !sent ? [] : item.parts
89
+ ? item.parts.map((part) => legacyTranscriptText(part.text, part.messageParts, part.attachments))
90
+ : [legacyTranscriptText(item.text, item.messageParts, item.attachments)];
91
+ const userRecords = [];
92
+ for (const [index, text] of userTexts.entries()) {
93
+ userRecords.push(await ctx.persistence.v2Transcript!.appendPresentationEvent({
94
+ kind: "message",
95
+ operationId: turnId,
96
+ role: "user",
97
+ text,
98
+ status: "completed",
99
+ presentation: { id: `message:${turnId}:user${index === 0 ? "" : `:${index + 1}`}`, revision: 1 },
100
+ }));
101
+ }
102
+ await ctx.persistence.v2Transcript!.syncBeforeDispatch();
103
+ for (const userRecord of userRecords) ctx.presentation.emitPersistedRecord(userRecord);
104
+ } catch (error) {
105
+ ctx.turn.end(turnId, item.handlers);
106
+ if (transcriptStarted) {
107
+ await ctx.persistence.v2Transcript!.abortOperation("pre_dispatch_persistence_failure").catch(
108
+ (abortError) => ctx.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
109
+ );
110
+ }
111
+ throw error;
112
+ }
113
+ } else {
114
+ if (sent) {
115
+ await ctx.persistence.appendTranscript({
116
+ v: 1,
117
+ t: "msg",
118
+ role: "user",
119
+ text: legacyTranscriptText(item.text, item.messageParts, item.attachments),
120
+ ts: Date.now(),
121
+ });
122
+ }
123
+ operation = await ctx.metering.open(item);
124
+ }
125
+
126
+ // Phase 3: the recording handlers.
127
+ const recording = createTurnRecording(ctx, turnId, item.handlers);
128
+ const { chunks, response, messageEnds } = recording;
129
+
130
+ let closed: OperationMeteringRecord | null = null;
131
+ let transcriptClosed = false;
132
+ let providerSettled = false;
133
+ let hookInProgress = false;
134
+ let prepared: PreparedTurn | undefined;
135
+ try {
136
+ // Phase 4: dispatch under the supervisor.
137
+ if (sent) {
138
+ hookInProgress = true;
139
+ for (const message of item.parts ?? [item]) {
140
+ if (message.beforeDispatch) await message.beforeDispatch("id" in message ? message.id : item.turnId);
141
+ }
142
+ hookInProgress = false;
143
+ }
144
+ // A lazy thread acquires its provider session during dispatch.
145
+ const dispatchedAt = new Date().toISOString();
146
+ // The prepared turn starts nothing; the supervisor subscribes to its output, then calls its
147
+ // `prompt()` (the attachment barrier).
148
+ prepared = ctx.controller.prepareTurn(turnId, {
149
+ // An owned conversation already resolved the parts and wrapped them with the provider-only
150
+ // text (identity, out-of-band messages); otherwise the client resolves them.
151
+ ...(!sent ? {} : {
152
+ input: owned?.providerParts
153
+ ? { parts: unresolvedParts(owned.providerParts) }
154
+ : item.messageParts
155
+ ? { parts: item.messageParts, attachments: item.attachments }
156
+ : { text: item.text, attachments: item.attachments },
157
+ }),
158
+ handlers: recording.handlers,
159
+ });
160
+ let res = await ctx.supervisedPrompt(ctx.controller, turnId, "turn", prepared);
161
+ if (res.cancel === "forced") {
162
+ const messages = response.snapshot();
163
+ res = { ...res, messages, text: response.text || chunks.join("") };
164
+ }
165
+ providerSettled = true;
166
+
167
+ // Phase 5: assistant records, metering, transcript.
168
+ if (ctx.persistence.v2Transcript) {
169
+ if (recording.assistantOrdinal === 0) {
170
+ for (const message of res.messages) {
171
+ const current = recording.beginAssistantMessage(message.messageId);
172
+ current.text = message.text;
173
+ current.dirty = true;
174
+ recording.flushAssistantMessage(res.status, res.stopReason, true);
175
+ }
176
+ } else {
177
+ recording.flushAssistantMessage(res.status, res.stopReason, true);
178
+ }
179
+ }
180
+ // Before the assistant msg: `msg` delimits a turn, so anything still open has to
181
+ // land inside those fences.
182
+ ctx.turn.end(turnId, item.handlers);
183
+ if (!ctx.session.title && item.text.trim()) {
184
+ ctx.session.title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
185
+ }
186
+ // A session may have been created lazily on first prompt (degraded has none).
187
+ const observedInternalSessionId = ctx.controller.currentSessionId ?? ctx.session.internalSessionId;
188
+ if (observedInternalSessionId) {
189
+ if (
190
+ ctx.session.providerAttachment.kind === "absent"
191
+ || ctx.session.providerAttachment.descriptor.internalSessionId !== observedInternalSessionId
192
+ ) {
193
+ ctx.session.installProviderAttachment(observedInternalSessionId, "runtime_only", true, {
194
+ acquiredAt: dispatchedAt,
195
+ });
196
+ }
197
+ } else {
198
+ ctx.session.setInternalSessionId(observedInternalSessionId);
199
+ }
200
+ // Metering closes BEFORE local persistence. The provider has already been paid and
201
+ // has already told us what it charged; letting a transcript or catalog write failure
202
+ // send us down the catch path would discard usage we are holding and, in a strict
203
+ // mode, block the session over a local disk problem.
204
+ //
205
+ // `closed` then guards the catch path. Closing twice would accrue the operation
206
+ // twice and emit a second record for it — double-counting tokens and cost, which is
207
+ // a worse failure than the one closing early prevents.
208
+ const record = await ctx.metering.close(operation, res.status, res.usage, undefined, prepared.nativeMetering);
209
+ closed = record;
210
+ await ctx.owner.lifecycle?.meteringRecorded?.(record);
211
+ // The Agent-owned and transcript paths record the attachment inside their own
212
+ // commit. A catalog-backed conversation has one mutable row, so the completed turn
213
+ // is simply what makes the live thread the selected one.
214
+ const pending = ctx.session.providerAttachment;
215
+ if (res.status === "completed"
216
+ && !ctx.owner.lifecycle
217
+ && !ctx.persistence.v2Transcript
218
+ && pending.kind === "runtime_only") {
219
+ ctx.session.providerAttachment = recordedProviderAttachment(pending.descriptor);
220
+ ctx.session.lastRecordedInternalSessionId = pending.descriptor.internalSessionId;
221
+ }
222
+ await ctx.persistence.persist();
223
+ if (ctx.persistence.v2Transcript) {
224
+ await ctx.presentation.drain();
225
+ await ctx.persistence.finishV2Prompt(res.status, record);
226
+ transcriptClosed = true;
227
+ } else {
228
+ await ctx.persistence.appendTranscript({
229
+ v: 1,
230
+ t: "msg",
231
+ role: "assistant",
232
+ ...legacyTranscriptMessages(res.messages, res.text),
233
+ ts: Date.now(),
234
+ usage: res.usage,
235
+ stopReason: res.stopReason,
236
+ status: res.status,
237
+ });
238
+ }
239
+ const result = Object.freeze({
240
+ ...res,
241
+ operationId: turnId,
242
+ metering: record,
243
+ ...ctx.steering.resultFields(turnId, res.stopReason),
244
+ });
245
+
246
+ // Phase 6: Agent-owned afterPrompt.
247
+ await ctx.owner.recordWrite;
248
+ if (ctx.owner.lifecycle) {
249
+ const stored = res.status === "cancelled" && prepared.recoverStoppedReplies
250
+ ? await stoppedRepliesForPersistence(ctx.log, prepared.recoverStoppedReplies, result, recording)
251
+ : { result, messageEnds };
252
+ const completed = {
253
+ operationId: turnId,
254
+ messageIds: [...(turn.cause.messageIds ?? [])],
255
+ agentSessionId: ctx.owner.agentSessionId!,
256
+ agentConversationId: ctx.owner.agentConversationId,
257
+ targetProviderContextId,
258
+ ...(owned?.identityDeliveryReceipt
259
+ ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
260
+ : {}),
261
+ ...(item.participantId ? { participantId: item.participantId } : {}),
262
+ text: item.text,
263
+ ...stored,
264
+ providerAttachment: ctx.session.providerAttachment,
265
+ };
266
+ try {
267
+ const committed = await ctx.owner.lifecycle.afterPrompt(completed);
268
+ if (committed?.providerAttachment) {
269
+ ctx.session.providerAttachment = acknowledgeProviderAttachment(
270
+ ctx.session.providerAttachment,
271
+ committed.providerAttachment,
272
+ );
273
+ }
274
+ } catch (error) {
275
+ if (error instanceof OwnedPromptPostCommitError) {
276
+ if (error.commit.providerAttachment) {
277
+ ctx.session.providerAttachment = acknowledgeProviderAttachment(
278
+ ctx.session.providerAttachment,
279
+ error.commit.providerAttachment,
280
+ );
281
+ }
282
+ throw error.cause ?? error;
283
+ }
284
+ throw error;
285
+ }
286
+ }
287
+ await ctx.owner.recordWrite;
288
+ return result;
289
+ } catch (err) {
290
+ // Failure: easy to miss, and the whole point of R4: a turn that died mid-tool still records
291
+ // what it was doing, at its real status.
292
+ ctx.turn.end(turnId, item.handlers);
293
+ const structured = response.snapshot();
294
+ const text = structured.length > 0 ? response.text : chunks.join("");
295
+ const messages: readonly ResponseMessage[] = structured.length > 0
296
+ ? structured
297
+ : text
298
+ ? Object.freeze([{ text }])
299
+ : Object.freeze([]);
300
+ if (!providerSettled) {
301
+ await ctx.owner.recordWrite.catch((persistenceError) => {
302
+ ctx.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
303
+ });
304
+ await ctx.owner.lifecycle?.promptFailed({
305
+ operationId: turnId,
306
+ messageIds: [...(turn.cause.messageIds ?? [])],
307
+ agentSessionId: ctx.owner.agentSessionId!,
308
+ agentConversationId: ctx.owner.agentConversationId,
309
+ ...(item.participantId ? { participantId: item.participantId } : {}),
310
+ text: item.text,
311
+ messages,
312
+ messageEnds,
313
+ error: err,
314
+ }).catch((persistenceError) => {
315
+ ctx.log.warn("owned_prompt_failure_persistence_failed", { error: String(persistenceError) });
316
+ });
317
+ }
318
+ await ctx.owner.recordWrite.catch((persistenceError) => {
319
+ ctx.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
320
+ });
321
+ if (ctx.persistence.v2Transcript) {
322
+ if (!transcriptClosed && recording.assistantOrdinal === 0 && messages.length > 0) {
323
+ for (const message of messages) {
324
+ const current = recording.beginAssistantMessage(message.messageId);
325
+ current.text = message.text;
326
+ current.dirty = true;
327
+ recording.flushAssistantMessage("error", "error", true);
328
+ }
329
+ } else if (!transcriptClosed) {
330
+ recording.flushAssistantMessage("error", "error", true);
331
+ }
332
+ await ctx.presentation.drain().catch(() => undefined);
333
+ } else {
334
+ await ctx.persistence.appendTranscript({
335
+ v: 1,
336
+ t: "msg",
337
+ role: "assistant",
338
+ ...legacyTranscriptMessages(messages, text),
339
+ ts: Date.now(),
340
+ stopReason: "error",
341
+ status: "error",
342
+ });
343
+ }
344
+ // A failed operation may still have consumed tokens, so its record has to survive
345
+ // the rejection rather than only reaching event subscribers.
346
+ // Already metered: the failure happened after the operation closed (a transcript or
347
+ // catalog write), so the record stands and must not be minted a second time.
348
+ const outcome = err instanceof OperationStalledError ? "cancelled" : "error";
349
+ const record = closed ?? (await ctx.metering.close(operation, outcome, null, String(err), prepared?.nativeMetering));
350
+ await ctx.owner.lifecycle?.meteringRecorded?.(record);
351
+ if (ctx.persistence.v2Transcript && !transcriptClosed) {
352
+ await ctx.persistence.finishV2Prompt("error", record, "unknown").catch(
353
+ (persistenceError) => ctx.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
354
+ );
355
+ }
356
+ if (hookInProgress) throw err;
357
+ if (err instanceof OperationStalledError) {
358
+ err.messages = messages;
359
+ err.metering = record;
360
+ await ctx.owner.lifecycle?.operationFailed?.({ operationId: turnId, error: err }).catch((error) => {
361
+ ctx.log.warn("operation_failure_recording_failed", { error: String(error) });
362
+ });
363
+ throw err;
364
+ }
365
+ throw new AgentSessionOperationError(turnId, record, err);
366
+ }
367
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The run the session sends for a queued prompt (controller-interface spec, Ids). A run's turn id is
3
+ * its first message's id; `messageIds` lists every message it carries, in queue order: one, or each
4
+ * original message of a combined steer run (the list steering reports in `message_delivered`). No
5
+ * new ids are minted.
6
+ */
7
+ import type { TurnRun } from "../conversation-controller/contracts.ts";
8
+ import { partOf } from "../steering/combine.ts";
9
+ import type { PromptQueueItem } from "./context.ts";
10
+
11
+ export function turnRunOf(prompt: PromptQueueItem): TurnRun {
12
+ const messages = prompt.parts ?? [partOf(prompt)];
13
+ return Object.freeze({
14
+ turnId: prompt.turnId,
15
+ messageIds: Object.freeze(messages.map((message) => message.id)),
16
+ messages: Object.freeze([...messages]),
17
+ operationKind: prompt.operationKind,
18
+ });
19
+ }
20
+
21
+ /** What the session knows about one message named by a run. */
22
+ export interface RunMessageState {
23
+ /** Its position in acceptance order (the queue is first in, first out). */
24
+ readonly order: number;
25
+ /** Already taken into a run. */
26
+ readonly dispatched: boolean;
27
+ /** Still waiting in the session's queue. */
28
+ readonly queued: boolean;
29
+ }
30
+
31
+ /**
32
+ * A run must carry at least one message, each once, each one the session accepted and has not
33
+ * settled, taken out of the queue and into no other run, in queue order, the turn id being the
34
+ * first message's id. `lookup` answers from the session's own message state (undefined for an id
35
+ * it does not know). A violation is a bug in building the run: it throws rather than send.
36
+ */
37
+ export function checkTurnRun(run: TurnRun, lookup: (messageId: string) => RunMessageState | undefined): void {
38
+ if (run.messageIds.length === 0) throw new Error("a run carries at least one message id");
39
+ const seen = new Set<string>();
40
+ let previous = 0;
41
+ for (const id of run.messageIds) {
42
+ if (seen.has(id)) throw new Error(`a run repeats message id ${id}`);
43
+ seen.add(id);
44
+ const message = lookup(id);
45
+ if (!message) throw new Error(`a run names message id ${id}, which the session does not know`);
46
+ if (message.dispatched) throw new Error(`a run names message id ${id}, which another run already took`);
47
+ if (message.queued) throw new Error(`a run names message id ${id}, which is still queued`);
48
+ if (message.order <= previous) throw new Error(`a run names message id ${id} out of queue order`);
49
+ previous = message.order;
50
+ }
51
+ if (run.messages.length !== run.messageIds.length || run.messages.some((message, index) => message.id !== run.messageIds[index])) {
52
+ throw new Error("a run's messages are not the messages its ids name, in order");
53
+ }
54
+ if (run.turnId !== undefined && run.turnId !== run.messageIds[0]) {
55
+ throw new Error(`a run's turn id ${run.turnId} is not its first message's id ${run.messageIds[0]}`);
56
+ }
57
+ }