@qlairoslabs/acp-client 0.12.1 → 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 -10
  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 +845 -6
  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 +25 -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 +3 -0
  35. package/src/cli/index.ts +3 -3
  36. package/src/cli/managed.ts +2 -2
  37. package/src/client.ts +52 -94
  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
@@ -1,9 +1,11 @@
1
+ import { protocolMethod } from "./persistence/protocol-method.ts";
2
+ import { ReminderError } from "./native/reminders/schedule.ts";
1
3
  // AgentConversation — one durable conversation and the library's compatibility front
2
4
  // face. Existing consumers still import this constructor as `AgentSession`; both names
3
5
  // refer to the same class while the new agent-level owner is introduced.
4
6
  //
5
7
  // It owns identity (our `agentSessionId`, adapter, mode, internalSessionId, title) and persistence, and
6
- // HOLDS an AgentController for the live connection (the control plane). It implements
8
+ // HOLDS a ConversationController (today a HarnessController) for the live connection. It implements
7
9
  // AgentClient, so the REPL and any caller can prompt it directly.
8
10
  //
9
11
  // Adapter ownership remains here during the compatibility tranche. The later Agent owner
@@ -11,14 +13,23 @@
11
13
 
12
14
  import { isMissingProviderSessionError } from "./checkpointing/recovery.ts";
13
15
  import type { CancelOutcome, CancelReason, OperationLifecycleConfig } from "./operations/contracts.ts";
16
+ import { ConnectionCancelledError, UnsupportedError } from "./errors.ts";
17
+ import type { AgentSessionConfig, AgentSessionOpenConfig } from "./agent-session-config.ts";
18
+ import { withStartupCancellation } from "./conversation-startup.ts";
19
+ export type { AgentSessionConfig, AgentSessionOpenConfig } from "./agent-session-config.ts";
20
+ import { SubscriptionHub } from "./observation/subscription-hub.ts";
21
+ import { validatePermissionConsumerConfig } from "./permissions/consumer-config.ts";
22
+ import { ConversationPermissions } from "./permissions/conversation.ts";
23
+ import { ownPermissions } from "./permissions/policy.ts";
14
24
  import { OperationStalledError } from "./operations/errors.ts";
15
- import { OperationSupervisor } from "./operations/supervisor.ts";
25
+ import { OperationSupervisor, type SupervisedProvider } from "./operations/supervisor.ts";
26
+ import type { HarnessController, AgentControllerConfig, ControllerStartEvent, AgentMode } from "./controller.ts";
27
+ import { normalizeHandoffContinuation, ownHandoffOptions } from "./handoff-options.ts";
16
28
  import {
17
- AgentController,
18
- type AgentControllerConfig,
19
- type AgentControllerStartEvent,
20
- type AgentMode,
21
- } from "./controller.ts";
29
+ acpCapabilitiesOf, availableCommandsOf, createController, harnessControllerOf, isDegradedController, listAgentSessions,
30
+ reloadProviderSession, requireFreshContext, requireMember, stallLimitsFor,
31
+ type ConversationCapabilities, type ConversationController,
32
+ } from "./conversation-controller/index.ts";
22
33
  import type * as schema from "@agentclientprotocol/sdk";
23
34
  import { join } from "node:path";
24
35
  import type { ActivitySnapshot, AggregatedRecord } from "./activity.ts";
@@ -36,7 +47,6 @@ import type {
36
47
  PersistenceJsonValue,
37
48
  } from "./persistence/backend.ts";
38
49
  import {
39
- OwnedPromptPostCommitError,
40
50
  type AgentConversationOwnerLifecycle,
41
51
  } from "./agent-conversation-owner.ts";
42
52
  import {
@@ -52,11 +62,11 @@ import type { Capabilities } from "./capabilities.ts";
52
62
  import type { ConfigOption, ConfigOptions } from "./config-options.ts";
53
63
  import type { ConnectResult } from "./client.ts";
54
64
  import { noopLogger, type Logger } from "./logger.ts";
55
- import { formatResponseMessages, ResponseAccumulator } from "./response.ts";
56
- import { MeteringEngine, type OpenDetachedOperation, type OpenOperation } from "./metering/engine.ts";
65
+ import { formatResponseMessages } from "./response.ts";
66
+ import { recoverNativeClose, withNativeAccounting } from "./metering/native/durability.ts";
67
+ import { MeteringEngine, type CloseOperationInput, type OpenDetachedOperation, type OpenOperation } from "./metering/engine.ts";
57
68
  import {
58
69
  AgentSessionHandoffError,
59
- AgentSessionOperationError,
60
70
  type AgentSessionMeteringSnapshot,
61
71
  type MeteredOperationKind,
62
72
  type MeteringConfig,
@@ -85,16 +95,12 @@ import type {
85
95
  Attachment,
86
96
  PromptHandlers,
87
97
  PromptResult,
88
- PermissionOutcome,
89
- PermissionRequest,
90
- ResponseMessage,
91
98
  SessionListEntry,
92
99
  TokenUsage,
93
100
  WireEntry,
94
101
  } from "./types.ts";
95
102
  import {
96
103
  resolveDirectPersistence,
97
- type AgentSessionPersistenceOptions,
98
104
  type ResolvedAgentSessionPersistence,
99
105
  } from "./persistence/config.ts";
100
106
  import { resolveSessionLogPaths } from "./persistence/paths.ts";
@@ -111,9 +117,9 @@ import type {
111
117
  InternalSessionHistoryEntry,
112
118
  InternalSessionDescriptor,
113
119
  TranscriptHeaderRecord,
114
- OperationKind,
115
120
  } from "./persistence/records.ts";
116
121
  import { TranscriptPersistenceRuntime } from "./persistence/transcript-runtime.ts";
122
+ import { MessageStatusTracker } from "./message-status.ts";
117
123
  import {
118
124
  RegistryPersistenceRuntime,
119
125
  type PersistenceStateRuntime,
@@ -166,6 +172,8 @@ import type {
166
172
  TranscriptContinuationBuilder,
167
173
  TranscriptContinuationBuilderContext,
168
174
  } from "./agent-conversation-contracts.ts";
175
+ import { withdrawBackendInput } from "./conversation-turns/backend-turns.ts";
176
+ import { captureStopFailure, dropClearedOperations } from "./conversation-turns/clear-operations.ts";
169
177
  import { AgentConversationQueue } from "./agent-conversation-queue.ts";
170
178
  import type { ImportedTurn } from "./agent/adoption/replay.ts";
171
179
  import {
@@ -174,11 +182,9 @@ import {
174
182
  type PendingMessageId,
175
183
  type PromptDelivery,
176
184
  type PromptHandle,
177
- type SteeringPrompt,
178
185
  } from "./steering/index.ts";
179
186
  import { AgentConversationPresentation } from "./agent-conversation-presentation.ts";
180
187
  import {
181
- HANDOFF_SUMMARY_PROMPT,
182
188
  buildContinuationPrompt,
183
189
  createContinuationReport,
184
190
  descriptorFromCheckpoint,
@@ -186,44 +192,20 @@ import {
186
192
  normalizeContinuationStrategies,
187
193
  stageOpeningContinuation,
188
194
  } from "./agent-conversation-continuation.ts";
189
- import { attachmentParts } from "./media/acp.ts";
190
195
  import {
191
- partsText,
192
- promptParts,
193
- transcriptParts,
194
- unresolvedParts,
195
- type MessagePart,
196
- type ResolvedPart,
197
- } from "./media/parts.ts";
196
+ BackendTurns, checkTurnRun, reportBackendTurn, reportTurnTook, runBackendTurn, runTurn, sendToBackend, settleClearedBackendTurns, steerIntoRunningTurn, turnRunOf, withdrawWaiting,
197
+ type BackendTurnHost, type BackendTurnItem, type PromptQueueItem, type TurnContext, type TurnRunContext,
198
+ } from "./conversation-turns/index.ts";
199
+ import type { TurnCause, TurnEvent, TurnRun } from "./conversation-controller/contracts.ts";
200
+ import {
201
+ copyPromptResult,
202
+ persistenceOperationKind,
203
+ toPersistenceJsonValue,
204
+ snapshotConsumerMetadata,
205
+ } from "./conversation-turns/record-helpers.ts";
206
+ import { promptInputText, promptParts, type MessagePart, type ResolvedPart } from "./media/parts.ts";
198
207
  import { redactMedia } from "./media/redact.ts";
199
208
 
200
- /** The text of an object-form prompt: its leading text plus its text parts. */
201
- function promptInputText(input: { readonly text?: string; readonly parts?: readonly MessagePart[] }): string {
202
- return partsText(promptParts(input) ?? [{ kind: "text", text: input.text ?? "" }]);
203
- }
204
-
205
- /** The older JSONL transcript has no media store: a message with parts keeps a line per part. */
206
- function legacyTranscriptText(
207
- text: string,
208
- parts?: readonly MessagePart[],
209
- attachments?: readonly Attachment[],
210
- ): string {
211
- if (!parts && !attachments?.length) return text;
212
- return transcriptParts([...(parts ?? [{ kind: "text", text }]), ...attachmentParts(attachments)]);
213
- }
214
-
215
- /** The older JSONL transcript's view of response messages, with a line per media part. */
216
- function legacyTranscriptMessages(messages: readonly ResponseMessage[], text: string) {
217
- const messageText = (message: ResponseMessage) => (message.parts ? transcriptParts(message.parts) : message.text);
218
- return {
219
- text: messages.some((message) => message.parts) ? messages.map(messageText).join("\n\n") : text,
220
- messages: messages.map((message) => ({
221
- ...(message.messageId ? { messageId: message.messageId } : {}),
222
- text: messageText(message),
223
- })),
224
- };
225
- }
226
-
227
209
  export {
228
210
  AdapterMismatchError,
229
211
  AgentSessionPromptBlockedError,
@@ -269,11 +251,6 @@ export type {
269
251
  TranscriptContinuationBuilderContext,
270
252
  } from "./agent-conversation-contracts.ts";
271
253
 
272
- interface PromptQueueItem extends SteeringPrompt {
273
- /** How this operation is classified in its metering record. */
274
- operationKind: MeteredOperationKind;
275
- }
276
-
277
254
  /** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
278
255
  export interface AgentConversationPromptInput {
279
256
  readonly text?: string;
@@ -283,6 +260,8 @@ export interface AgentConversationPromptInput {
283
260
  readonly attachments?: Attachment[];
284
261
  /** How this prompt waits if a turn is running. Defaults to the conversation's `busyDelivery`. */
285
262
  readonly delivery?: PromptDelivery;
263
+ /** Awaited before dispatch with this prompt's message ID. A rejection prevents dispatch. */
264
+ readonly beforeDispatch?: (messageId: string) => Promise<void>;
286
265
  }
287
266
 
288
267
  export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
@@ -305,7 +284,7 @@ interface HandoffQueueItem {
305
284
  * source until the seed confirms the target.
306
285
  */
307
286
  interface InternalPromptTarget {
308
- readonly controller: AgentController;
287
+ readonly controller: ConversationController;
309
288
  readonly metering: MeteringEngine;
310
289
  readonly adapterId: string;
311
290
  }
@@ -341,7 +320,7 @@ interface RecoveryResolutionQueueItem {
341
320
  reject: (error: unknown) => void;
342
321
  }
343
322
 
344
- type QueueItem = PromptQueueItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
323
+ type QueueItem = PromptQueueItem | BackendTurnItem | HandoffQueueItem | ConfigQueueItem | ModeQueueItem | ConfigResolutionQueueItem | RecoveryResolutionQueueItem;
345
324
 
346
325
  export interface AgentSessionOpenResult {
347
326
  readonly session: AgentConversation;
@@ -352,112 +331,6 @@ export interface AgentSessionOpenResult {
352
331
  readonly repairs: readonly PersistenceRepair[];
353
332
  }
354
333
 
355
- export interface AgentSessionConfig {
356
- /** The resolved adapter this conversation talks to. */
357
- adapter: Adapter;
358
- /** Stable adapter id for the catalog/display (e.g. "codex"). */
359
- adapterId: string;
360
- /** Talk over ACP ("normal") or scrape a pty ("degraded"). Default "normal". */
361
- mode?: AgentMode;
362
- /** Runtime-specific launcher shared by normal ACP and degraded PTY modes. */
363
- launcher?: AgentControllerConfig["launcher"];
364
- /** @deprecated Use launcher. */
365
- execPrefix?: string[];
366
- /** @deprecated Use launcher and its exact spawnEnv. */
367
- env?: Record<string, string>;
368
- cwd?: string;
369
- /** Additional absolute directories declared to the provider. */
370
- additionalDirectories?: string[];
371
- /** Default MCP servers bound at session creation/switch, unless a call overrides them. */
372
- mcpServers?: schema.McpServer[];
373
- defaultPermission?: "approve" | "cancel";
374
- /**
375
- * How a prompt sent while a turn is running waits when the prompt does not say. `queue` runs it after
376
- * the turn ends; `steer` delivers it at the next tool boundary. Default `steer`.
377
- */
378
- busyDelivery?: PromptDelivery;
379
- clientInfo?: { name: string; title?: string; version?: string };
380
- /** What we let the agent do through us (terminals, filesystem). All on by default. */
381
- clientCapabilities?: AgentControllerConfig["clientCapabilities"];
382
- /** Client-side ACP implementations; their presence determines advertisement. */
383
- clientHandlers?: AgentControllerConfig["clientHandlers"];
384
- logger?: Logger;
385
- /** Raw protocol traffic for debugging — see `AcpClientConfig.wire`. */
386
- wire?: (entry: WireEntry) => void;
387
- /** Optional catalog. When present, the session records itself here. */
388
- sessions?: SessionManager;
389
- /** New v2 persistence. Direct sessions remain persistence-free when omitted. */
390
- persistence?: false | AgentSessionPersistenceOptions;
391
- /** Stable creation transaction/incarnation ID; required by direct v2 persistence. */
392
- creationId?: string;
393
- /**
394
- * Absolute path to an append-only transcript file. This selects history storage only;
395
- * file existence never selects the provider thread. Omitted means no transcript.
396
- */
397
- transcriptPath?: string;
398
- /**
399
- * Directory for `<encoded-agentSessionId>.jsonl`. This selects history storage only;
400
- * the directory is not a session catalog and is not scanned during creation.
401
- */
402
- transcriptDir?: string;
403
- /**
404
- * Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
405
- * lines. Off by default — it makes transcripts larger, and `readTranscript()` ignores
406
- * them either way; read them with `readTranscriptLines()`.
407
- *
408
- * Lines are SETTLED records, not raw deltas: the session folds the delta stream and
409
- * writes checkpoints (announced → input → settled), typically 2–3 lines per tool call
410
- * instead of one per notification. Fold them back with `foldRecords()`, last-wins on
411
- * `recordId`. `true` selects the defaults below.
412
- */
413
- transcriptActivity?: boolean | TranscriptActivityConfig;
414
- /** Stable logical identity. Minted if omitted; always available on the created object. */
415
- agentSessionId?: string;
416
- /** Provider-thread startup intent. Default `{ kind: "new" }`. */
417
- providerSession?: ProviderSession;
418
- /** Stale limits per operation kind (turns, internal inference, recap). */
419
- operationLifecycle?: OperationLifecycleConfig;
420
- /**
421
- * Token/cost metering policy. Optional: omitting it selects best-effort enforcement
422
- * with the pinned models.dev catalog and no restored state. Metering is not something a
423
- * consumer must turn on merely to see protocol facts.
424
- */
425
- metering?: MeteringConfig;
426
- /**
427
- * @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
428
- * Retains the historical fallback-to-new behavior for compatibility.
429
- */
430
- internalSessionId?: string;
431
- title?: string;
432
- /** Stable conversation identity when this runtime is owned by an Agent. */
433
- agentConversationId?: AgentConversationId;
434
- /** Stable owning agent identity. Omitted for detached compatibility conversations. */
435
- ownerAgentSessionId?: AgentSessionId;
436
- /** Other sides of this conversation. The owning agent is implied. */
437
- participants?: readonly ParticipantRef[];
438
- /** @internal Installed by AgentConversationManager. */
439
- ownerLifecycle?: AgentConversationOwnerLifecycle;
440
- }
441
-
442
- /** Direct restoration input. Phase 5A intentionally supports the safe recorded-thread path. */
443
- export interface AgentSessionOpenConfig extends Omit<
444
- AgentSessionConfig,
445
- | "agentSessionId"
446
- | "creationId"
447
- | "providerSession"
448
- | "internalSessionId"
449
- | "mode"
450
- | "persistence"
451
- | "sessions"
452
- > {
453
- /** Required for directory/default path resolution; exact-file inference is a later slice. */
454
- agentSessionId: string;
455
- persistence: AgentSessionPersistenceOptions;
456
- /** Optional consumer copy must exactly match transcript authority in this first slice. */
457
- checkpoint?: AgentSessionCheckpoint;
458
- continuation?: OpenContinuationOptions;
459
- }
460
-
461
334
  interface AgentSessionOpenBootstrap {
462
335
  readonly transcript: PersistenceStateRuntime;
463
336
  readonly transcriptPath: string;
@@ -488,13 +361,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
488
361
  private _adapterId: string;
489
362
  private activeAdapter: Adapter;
490
363
 
491
- private controller: AgentController;
364
+ private controller: ConversationController;
492
365
  private readonly controllerDefaults: Omit<
493
366
  AgentControllerConfig,
494
367
  "adapter" | "adapterId" | "mode" | "sessionId" | "sessionLoadFailure"
495
- >;
368
+ > & Pick<AgentConversationConfig, "native" | "isNativeAdapter" | "answersPermissions" | "permissionTimeoutMs">;
496
369
  private detachControllerCommands: (() => void) | null = null;
497
370
  private detachControllerUsage: (() => void) | null = null;
371
+ private detachControllerTurns: (() => void) | null = null;
372
+ /**
373
+ * Runs the session sent and whose turn is running or about to (registered before `send`, since
374
+ * a session-scheduled controller reports `turn_started` inside the call). Keyed by turn id.
375
+ */
376
+ private readonly sentRuns = new Map<string, { readonly run: TurnRun; cause?: TurnCause }>();
377
+ /** Ids of the messages (queued prompts) the session accepted and has not settled yet. */
378
+ private readonly backendTurns = new BackendTurns();
379
+ private readonly messageStatus = new MessageStatusTracker((event) => this.emit(event));
380
+ private readonly acceptedMessages = new Map<string, { readonly order: number; dispatched: boolean }>();
381
+ private acceptedMessageCount = 0;
498
382
  private readonly sessions?: SessionManager;
499
383
  private readonly _transcriptPath?: string;
500
384
  private readonly persistence: false | ResolvedAgentSessionPersistence;
@@ -509,7 +393,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
509
393
  private stopPromise: Promise<void> | null = null;
510
394
  private phase: AgentSessionPhase = "idle";
511
395
  private notificationSeq = 0;
512
- private readonly listeners = new Set<AgentSessionListener>();
396
+ private readonly listeners = new SubscriptionHub<AgentSessionNotification>(({ event, error }) =>
397
+ this.log.warn("agent_session_listener_failed", { kind: event.event.kind, error: String(error) }));
513
398
  private lastStateKey = "";
514
399
  private _internalSessionId: string | null;
515
400
  private providerAttachment: ProviderAttachmentState = Object.freeze({ kind: "absent" });
@@ -555,6 +440,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
555
440
  private managedInitializationReported = false;
556
441
  private readonly operationLifecycle: OperationLifecycleConfig;
557
442
  private reconnecting = false;
443
+ private deferredProviderStart: boolean;
444
+ private connecting = 0;
445
+ private handoffTarget?: ConversationController;
558
446
  private detachControllerConnection: (() => void) | null = null;
559
447
  private activeSupervisor: OperationSupervisor | null = null;
560
448
  /**
@@ -570,8 +458,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
570
458
  private providerFailedTurnId: string | null = null;
571
459
  private readonly ownerLifecycle?: AgentConversationOwnerLifecycle;
572
460
  private _participants: ParticipantRef[];
461
+ private readonly permissions = new ConversationPermissions(event => this.emit(event), () => this.log, this, () => this.controllerDefaults);
573
462
  private ownerRecordWrite: Promise<void> = Promise.resolve();
574
- private readonly defaultPermission: "approve" | "cancel";
575
463
 
576
464
  private constructor(
577
465
  config: AgentSessionConfig,
@@ -622,7 +510,6 @@ export class AgentConversation implements AgentClient, Bridgeable {
622
510
  ?? (isAgentSessionId(this.agentSessionId) ? this.agentSessionId : null);
623
511
  this.operationLifecycle = config.operationLifecycle ?? {};
624
512
  this.ownerLifecycle = config.ownerLifecycle;
625
- this.defaultPermission = config.defaultPermission ?? "cancel";
626
513
  this.steering = new SteeringController<QueueItem>(
627
514
  {
628
515
  queue: this.operations,
@@ -671,10 +558,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
671
558
  this._cwd = config.cwd;
672
559
  this._title = config.title;
673
560
  this._internalSessionId = requestedInternalSessionId ?? null;
561
+ this.deferredProviderStart = config.deferProviderStart === true && this.ownerAgentSessionId !== undefined &&
562
+ !config.native && this._mode === "normal" && this.persistence === false;
674
563
  this.meteringConfig = Object.freeze({ ...(config.metering ?? {}) });
675
564
  this.metering = new MeteringEngine({
676
565
  agentSessionId: this.agentSessionId,
677
566
  adapterId: config.adapterId,
567
+ native: config.native !== undefined,
678
568
  enforcement: config.metering?.enforcement ?? "best_effort",
679
569
  // Absence selects the pinned catalog; `false` is how a consumer says "no rating".
680
570
  pricing: config.metering?.pricing ?? createModelsDevResolver(),
@@ -682,22 +572,26 @@ export class AgentConversation implements AgentClient, Bridgeable {
682
572
  ...(config.metering?.counterInterpretation
683
573
  ? { counterInterpretation: config.metering.counterInterpretation }
684
574
  : {}),
685
- ...(config.metering?.inferenceSource
575
+ ...(config.metering?.inferenceSource && !config.native
686
576
  ? { inferenceSource: config.metering.inferenceSource }
687
577
  : {}),
688
578
  // A thread we are about to create has counters starting at zero; one we load does
689
579
  // not, and needs restored state to be attributable.
690
580
  createdActiveThread: providerSession.kind === "new",
691
581
  });
582
+ validatePermissionConsumerConfig(config);
692
583
  this.controllerDefaults = {
584
+ answersPermissions: config.answersPermissions, permissionTimeoutMs: config.permissionTimeoutMs,
693
585
  operationLifecycle: this.operationLifecycle,
586
+ isNativeAdapter: config.isNativeAdapter,
587
+ ...(config.native ? { native: { ...config.native, idleStopWindowMs: config.idleStopWindowMs, onReminderEvent: event => this.emit(event) } } : {}),
694
588
  launcher: config.launcher,
695
589
  execPrefix: config.execPrefix,
696
590
  env: config.env,
697
591
  cwd: config.cwd,
698
592
  additionalDirectories: config.additionalDirectories,
699
593
  mcpServers: config.mcpServers,
700
- defaultPermission: config.defaultPermission,
594
+ permissions: ownPermissions(config.permissions), permissionRule: config.permissionRule,
701
595
  clientInfo: config.clientInfo,
702
596
  clientCapabilities: config.clientCapabilities,
703
597
  clientHandlers: config.clientHandlers,
@@ -714,6 +608,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
714
608
  if (providerSession.kind === "load") this.sessionLoadFailure = providerSession.onFailure ?? "error";
715
609
  this.controller = this.createController(config.adapter, config.adapterId, this._mode, {
716
610
  sessionId: requestedInternalSessionId,
611
+ requireStartupSession: this.deferredProviderStart,
717
612
  sessionLoadFailure: providerSession.kind === "load"
718
613
  ? providerSession.onFailure ?? "error"
719
614
  : undefined,
@@ -728,9 +623,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
728
623
  adapter: Adapter,
729
624
  adapterId: string,
730
625
  mode: AgentMode,
731
- startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure" | "onSessionReplay"> = {},
732
- ): AgentController {
733
- return new AgentController({
626
+ startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure" | "onSessionReplay" | "requireStartupSession"> = {},
627
+ ): ConversationController {
628
+ return createController({
734
629
  ...this.controllerDefaults,
735
630
  adapter,
736
631
  adapterId,
@@ -739,19 +634,60 @@ export class AgentConversation implements AgentClient, Bridgeable {
739
634
  });
740
635
  }
741
636
 
742
- private bindController(controller: AgentController): void {
637
+ private bindController(controller: ConversationController): void {
743
638
  this.detachControllerConnection?.();
744
639
  this.detachControllerConnection = controller.subscribeConnection(() => this.emitStateIfChanged());
745
640
  this.detachControllerCommands?.();
746
641
  this.detachControllerUsage?.();
747
- this.detachControllerCommands = controller.subscribeAvailableCommands((commands) => {
642
+ this.detachControllerCommands = controller.subscribeAvailableCommands?.((commands) => {
748
643
  if (this.controller === controller) {
749
644
  this.emit({ kind: "internal_session_commands_changed", commands });
750
645
  }
751
- });
646
+ }) ?? null;
752
647
  this.detachControllerUsage = controller.subscribeUsageUpdate((update, sessionId) => {
753
648
  if (this.controller === controller) this.applyUsageUpdate(update, sessionId);
754
649
  });
650
+ this.detachControllerTurns?.();
651
+ this.detachControllerTurns = controller.subscribeTurns((event) => {
652
+ if (this.controller === controller) this.onControllerTurnEvent(controller, event);
653
+ });
654
+ }
655
+
656
+ private backendTurnHost(): BackendTurnHost {
657
+ const session = this;
658
+ return {
659
+ turns: this.backendTurns,
660
+ log: this.log,
661
+ markSent: (id) => { const message = this.acceptedMessages.get(id); if (message) message.dispatched = true; },
662
+ received: (id) => this.messageStatus.advance(id, "received"),
663
+ get stopped() { return session.stopPromise !== null; }, // `phase` is rewritten by each queue item
664
+ emit: (event) => this.emit(event),
665
+ enqueue: (item) => { this.operations.enqueue(item); this.emitStateIfChanged(); void this.pump(); },
666
+ run: (turn) => this.runPrompt(turn),
667
+ };
668
+ }
669
+
670
+ private onNativeWithdrawal(messageId: string): void {
671
+ if (!this.stopPromise) this.backendTurns.confirmWithdrawal(messageId, messages => this.steering.dropped(messages));
672
+ }
673
+ /** A turn the controller reports. The session announces it; completion stays the session's. */
674
+ private onControllerTurnEvent(controller: ConversationController, event: TurnEvent): void {
675
+ if (event.kind === "input_withdrawn") return this.onNativeWithdrawal(event.messageId);
676
+ if (event.kind === "items_receipt") { if (!this.stopPromise) this.emit(event); return; }
677
+ if (event.kind === "turn_took") {
678
+ const ids = event.cause.messageIds ?? [];
679
+ this.messageStatus.link(event.turnId, ids);
680
+ for (const id of ids) this.messageStatus.advance(id, "taken");
681
+ return reportTurnTook(this.backendTurnHost(), event);
682
+ }
683
+ if (!event.sentBySession) return reportBackendTurn(this.backendTurnHost(), controller, event);
684
+ const sent = this.sentRuns.get(event.turnId);
685
+ if (!sent) {
686
+ this.log.warn("controller_turn_unknown", { turnId: event.turnId });
687
+ return;
688
+ }
689
+ sent.cause = event.cause;
690
+ this.emit({ kind: "turn_started", turnId: event.turnId, cause: event.cause });
755
691
  }
756
692
 
757
693
  private queueOwnedRecord(record: NewConversationRecord, parts?: readonly ResolvedPart[]): void {
@@ -766,14 +702,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
766
702
 
767
703
  private async recordOwned(record: NewConversationRecord): Promise<void> {
768
704
  if (!this.ownerLifecycle?.record) return;
769
- const write = this.ownerRecordWrite
770
- .then(() => this.ownerLifecycle!.record!(record))
771
- .catch((error) => {
772
- this.markManagedPersistenceUnhealthy();
773
- throw error;
774
- });
775
- this.ownerRecordWrite = write;
776
- await write;
705
+ this.queueOwnedRecord(record);
706
+ await this.ownerRecordWrite;
777
707
  }
778
708
 
779
709
  private markManagedPersistenceUnhealthy(): void {
@@ -839,7 +769,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
839
769
  });
840
770
  }
841
771
 
842
- private reportManagedControllerProgress(event: AgentControllerStartEvent): void {
772
+ private reportManagedControllerProgress(event: ControllerStartEvent): void {
843
773
  if (!this.managedOpenProgress) return;
844
774
  // A continuation policy may restart the same adapter after a failed load. The
845
775
  // managed lifecycle reports capability discovery once, while the successful
@@ -864,7 +794,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
864
794
  }
865
795
  const session = new AgentConversation(config);
866
796
  try {
867
- await session.start();
797
+ await withStartupCancellation(config.signal, () => session.stop(), () => session.start());
868
798
  return session;
869
799
  } catch (error) {
870
800
  await session.stop().catch(() => {});
@@ -886,7 +816,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
886
816
  throw error;
887
817
  }
888
818
  try {
889
- await session.start();
819
+ await withStartupCancellation(config.signal, () => session.stop(), () => session.start());
890
820
  return session;
891
821
  } catch (error) {
892
822
  await session.stop().catch(() => undefined);
@@ -954,7 +884,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
954
884
  session.v2Transcript = audit ? new AuditedPersistenceRuntime(primary, audit) : primary;
955
885
  session.managedAuditLog = audit?.identity ?? null;
956
886
  try {
957
- const result = await session.controller.start((event) => session.reportManagedControllerProgress(event));
887
+ const result = await withStartupCancellation(config.signal, () => session.stop(), () => session.startController());
958
888
  if (!result.resumed || !result.sessionId) {
959
889
  throw new Error("adapter did not confirm loading the recorded internal session");
960
890
  }
@@ -1058,22 +988,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
1058
988
  session.managedAuditLog = audit?.identity ?? null;
1059
989
 
1060
990
  try {
1061
- const continuation = await session.acquireOpeningContinuation(checkpoint, strategies);
1062
- if (continuation.outcome.kind === "unavailable") {
1063
- throw new ContinuationUnavailableError(continuation);
1064
- }
1065
- const configuration = continuation.outcome.kind === "loaded"
1066
- ? await session.restoreOpeningConfiguration()
1067
- : session._configurationRestore;
1068
- session._configurationRestore = configuration;
1069
- session.emitStateIfChanged();
1070
- return Object.freeze({
1071
- session,
1072
- continuation,
1073
- recovery: structuredClone(session._recovery),
1074
- configuration: structuredClone(configuration),
1075
- promptability: session.promptability,
1076
- repairs: transcript.openingRepairs,
991
+ return await withStartupCancellation(config.signal, () => session.stop(), async () => {
992
+ const continuation = await session.acquireOpeningContinuation(checkpoint, strategies);
993
+ if (continuation.outcome.kind === "unavailable") {
994
+ throw new ContinuationUnavailableError(continuation);
995
+ }
996
+ const configuration = continuation.outcome.kind === "loaded"
997
+ ? await session.restoreOpeningConfiguration()
998
+ : session._configurationRestore;
999
+ session._configurationRestore = configuration;
1000
+ session.emitStateIfChanged();
1001
+ return Object.freeze({
1002
+ session,
1003
+ continuation,
1004
+ recovery: structuredClone(session._recovery),
1005
+ configuration: structuredClone(configuration),
1006
+ promptability: session.promptability,
1007
+ repairs: transcript.openingRepairs,
1008
+ });
1077
1009
  });
1078
1010
  } catch (error) {
1079
1011
  await session.stop().catch(() => undefined);
@@ -1085,12 +1017,37 @@ export class AgentConversation implements AgentClient, Bridgeable {
1085
1017
  }
1086
1018
  }
1087
1019
 
1020
+ private async connectProvider<T>(connect: () => Promise<T>): Promise<T> {
1021
+ this.assertConnectionOpen();
1022
+ this.connecting++;
1023
+ try {
1024
+ const result = await connect();
1025
+ this.assertConnectionOpen();
1026
+ return result;
1027
+ } finally {
1028
+ this.connecting--;
1029
+ }
1030
+ }
1031
+
1032
+ private assertConnectionOpen(): void {
1033
+ if (this.phase === "stopped") throw new ConnectionCancelledError();
1034
+ }
1035
+
1036
+ private startController(fresh = false): Promise<ConnectResult> {
1037
+ const progress = (event: ControllerStartEvent) => this.reportManagedControllerProgress(event);
1038
+ return this.connectProvider(() => fresh ? this.controller.startFresh(progress) : this.controller.start(progress));
1039
+ }
1040
+
1088
1041
  private async start(): Promise<void> {
1089
1042
  if (this.persistence !== false) {
1090
1043
  await this.startPersistent();
1091
1044
  return;
1092
1045
  }
1093
- const result = await this.controller.start();
1046
+ if (this.deferredProviderStart) {
1047
+ if (this._internalSessionId) this.installProviderAttachment(this._internalSessionId, "recorded", false);
1048
+ return;
1049
+ }
1050
+ const result = await this.startController();
1094
1051
  // A resumed thread's counters did not start at zero, so it needs restored state to
1095
1052
  // be attributable.
1096
1053
  const internalSessionId = result.sessionId || this._internalSessionId;
@@ -1123,7 +1080,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1123
1080
  this.v2Transcript = this.openBootstrap.transcript;
1124
1081
  this.v2TranscriptPath = this.openBootstrap.transcriptPath;
1125
1082
  this._recovery = this.v2Transcript.recovery;
1126
- const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
1083
+ const result = await this.startController();
1127
1084
  if (!result.resumed || !result.sessionId) {
1128
1085
  throw new Error("adapter did not confirm loading the recorded internal session");
1129
1086
  }
@@ -1161,7 +1118,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1161
1118
  }
1162
1119
  if (!paths.transcriptPath || persistence.transcript === false) {
1163
1120
  try {
1164
- const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
1121
+ const result = await this.startController();
1165
1122
  this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
1166
1123
  if (this.managedCreation) {
1167
1124
  const now = new Date().toISOString();
@@ -1177,7 +1134,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1177
1134
  policy: persistence.sessionConfiguration,
1178
1135
  observedAt: now,
1179
1136
  }),
1180
- protocol: this.controller.isDegraded ? { name: "pty" } : { name: "acp", version: 1 },
1137
+ protocol: isDegradedController(this.controller) ? { name: "pty" } : { name: "acp", version: 1 },
1181
1138
  };
1182
1139
  const staged = await this.managedCreation.stageContinuation(observed);
1183
1140
  const primary = new RegistryPersistenceRuntime(createAgentSessionCheckpoint({
@@ -1232,7 +1189,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1232
1189
  header,
1233
1190
  writerLock: this.managedCreation?.transcriptLock,
1234
1191
  initializeCheckpoint: async () => {
1235
- const result = await this.controller.start((event) => this.reportManagedControllerProgress(event));
1192
+ const result = await this.startController();
1236
1193
  this.setInternalSessionId(result.sessionId || this._internalSessionId, !result.resumed);
1237
1194
  if (this._internalSessionId) {
1238
1195
  this.installProviderAttachment(
@@ -1255,7 +1212,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1255
1212
  internalSessionActivatedAt: this._internalSessionId ? now : null,
1256
1213
  model: this.model,
1257
1214
  sessionConfiguration,
1258
- protocol: this.controller.isDegraded ? { name: "pty" } : { name: "acp", version: 1 },
1215
+ protocol: isDegradedController(this.controller) ? { name: "pty" } : { name: "acp", version: 1 },
1259
1216
  };
1260
1217
  const stagedContinuation = this.managedCreation
1261
1218
  ? await this.managedCreation.stageContinuation(observedContinuation)
@@ -1363,14 +1320,14 @@ export class AgentConversation implements AgentClient, Bridgeable {
1363
1320
  continue;
1364
1321
  }
1365
1322
  try {
1366
- const loaded = await this.controller.start((event) => this.reportManagedControllerProgress(event));
1323
+ const loaded = await this.startController();
1367
1324
  if (!loaded.resumed || !loaded.sessionId) {
1368
1325
  throw new Error("adapter did not confirm loading the recorded internal session");
1369
1326
  }
1370
1327
  if (loaded.sessionId !== checkpoint.internalSessionId) {
1371
1328
  throw new Error("adapter loaded a different internal session than requested");
1372
1329
  }
1373
- this._mode = this.controller.currentMode;
1330
+ this._mode = this.controller.currentMode ?? this._mode;
1374
1331
  this.installProviderAttachment(loaded.sessionId, "recorded", false);
1375
1332
  await stageOpeningContinuation(
1376
1333
  this.openBootstrap.stageContinuation,
@@ -1385,6 +1342,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1385
1342
  activeInternalSessionId: loaded.sessionId,
1386
1343
  });
1387
1344
  } catch (error) {
1345
+ if (error instanceof ConnectionCancelledError) throw error;
1388
1346
  recordedThreadAvailability = "unavailable";
1389
1347
  attempts.push(Object.freeze({
1390
1348
  strategy: strategy.kind,
@@ -1445,7 +1403,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1445
1403
  reasonCode: "continuation_reconstruction",
1446
1404
  });
1447
1405
  try {
1448
- const created = await this.controller.startFresh((event) => this.reportManagedControllerProgress(event));
1406
+ const created = await this.startController(true);
1449
1407
  if (!created.sessionId) throw new Error("harness returned no session id for reconstructed continuation");
1450
1408
  if (created.sessionId === checkpoint.internalSessionId && checkpoint.adapterId === this.adapterId) {
1451
1409
  throw new Error("harness did not create a replacement internal session");
@@ -1560,6 +1518,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1560
1518
  }).catch((persistenceError) => {
1561
1519
  this.log.warn("continuation_failure_transcript_failed", { error: String(persistenceError) });
1562
1520
  });
1521
+ if (error instanceof ConnectionCancelledError) throw error;
1563
1522
  attempts.push(Object.freeze({
1564
1523
  strategy: strategy.kind,
1565
1524
  status: "failed",
@@ -1576,13 +1535,11 @@ export class AgentConversation implements AgentClient, Bridgeable {
1576
1535
  // Nothing was ever selected to continue, so there is nothing a reconstruction could
1577
1536
  // rebuild from. Starting fresh is the whole continuation, and the new thread stays
1578
1537
  // runtime-only until a completed turn earns it a place in the checkpoint.
1579
- const created = await this.controller.startFresh(
1580
- (event) => this.reportManagedControllerProgress(event),
1581
- );
1538
+ const created = await this.startController(true);
1582
1539
  if (!created.sessionId) {
1583
1540
  throw new Error("harness returned no session id for an unattached conversation");
1584
1541
  }
1585
- this._mode = this.controller.currentMode;
1542
+ this._mode = this.controller.currentMode ?? this._mode;
1586
1543
  this.installProviderAttachment(created.sessionId, "runtime_only", true);
1587
1544
  this._configurationRestore = this.snapshotReconstructedConfiguration([]).status;
1588
1545
  this.continuationAcquired = true;
@@ -1890,13 +1847,18 @@ export class AgentConversation implements AgentClient, Bridgeable {
1890
1847
  }
1891
1848
  /** Subscribe to future lifecycle changes. The current snapshot is available via state. */
1892
1849
  subscribe(listener: AgentSessionListener): () => void {
1893
- this.listeners.add(listener);
1894
- return () => this.listeners.delete(listener);
1850
+ return this.listeners.subscribe(listener);
1851
+ }
1852
+ /** Answer an open event-driven permission request. */
1853
+ answerPermission(id: string, optionId: string): Promise<{ accepted: boolean }> {
1854
+ return this.permissions.answer(id, optionId);
1895
1855
  }
1896
1856
  /** Escape hatch to the live control plane (config, caps, getCommands, login, …). */
1897
- get connection(): AgentController {
1857
+ get connection(): ConversationController {
1898
1858
  return this.controller;
1899
1859
  }
1860
+ /** The live controller as a `HarnessController` (an external harness over ACP or a PTY), or null for any other backend. */
1861
+ harnessConnection(): HarnessController | null { return harnessControllerOf(this.controller); }
1900
1862
 
1901
1863
  // --- AgentClient -------------------------------------------------------------
1902
1864
  prompt(input: AgentConversationPromptInput): PromptHandle;
@@ -1914,7 +1876,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1914
1876
  ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1915
1877
  : this.enqueuePrompt(
1916
1878
  promptInputText(input), "prompt", input.handlers, input.attachments,
1917
- undefined, input.consumerMetadata, input.delivery, promptParts(input),
1879
+ undefined, input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch,
1918
1880
  );
1919
1881
  }
1920
1882
 
@@ -1925,7 +1887,13 @@ export class AgentConversation implements AgentClient, Bridgeable {
1925
1887
 
1926
1888
  /** Take back a message that has not been sent yet. Returns whether it was still pending. */
1927
1889
  withdraw(id: PendingMessageId): boolean {
1928
- return this.steering.withdraw(id);
1890
+ return this.steering.withdraw(id) || (this.controller.withdrawInput !== undefined &&
1891
+ this.backendTurns.withdrawable(id) === "local" && this.backendTurns.confirmWithdrawal(id, messages => this.steering.dropped(messages)));
1892
+ }
1893
+
1894
+ /** Also requests confirmed withdrawal of a native input already submitted. */
1895
+ async withdrawAsync(id: PendingMessageId): Promise<boolean> {
1896
+ return this.withdraw(id) || withdrawBackendInput(this.backendTurns, this.controller, id, messages => this.steering.dropped(messages), () => !this.stopPromise);
1929
1897
  }
1930
1898
 
1931
1899
  /** Prompt while attributing the caller to a stable participant identity. */
@@ -1946,7 +1914,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1946
1914
  if (!input.participantId.trim()) return this.rejectedPrompt(new Error("participant id cannot be blank"));
1947
1915
  return this.enqueuePrompt(
1948
1916
  promptInputText(input), "prompt", input.handlers, input.attachments,
1949
- input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input),
1917
+ input.participantId.trim(), input.consumerMetadata, input.delivery, promptParts(input), input.beforeDispatch,
1950
1918
  );
1951
1919
  }
1952
1920
  const participantId = input;
@@ -1957,7 +1925,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1957
1925
  private rejectedPrompt(error: Error): PromptHandle {
1958
1926
  const id = this.mintTurnId();
1959
1927
  const rejected = Promise.reject<AgentSessionPromptResult>(error);
1960
- return Object.assign(rejected, { id, withdraw: () => false });
1928
+ return Object.assign(rejected, { id, status: "failed" as const, withdraw: () => false, withdrawAsync: async () => false });
1961
1929
  }
1962
1930
 
1963
1931
  private enqueuePrompt(
@@ -1969,6 +1937,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1969
1937
  consumerMetadata?: PersistenceJsonValue,
1970
1938
  delivery?: PromptDelivery,
1971
1939
  messageParts?: readonly MessagePart[],
1940
+ beforeDispatch?: AgentConversationPromptInput["beforeDispatch"],
1972
1941
  ): PromptHandle {
1973
1942
  const id = this.mintTurnId();
1974
1943
  const promise = new Promise<AgentSessionPromptResult>((resolve, reject) => {
@@ -1979,14 +1948,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1979
1948
  let stableConsumerMetadata: PersistenceJsonValue | undefined;
1980
1949
  try {
1981
1950
  this.assertPromptable();
1982
- if (consumerMetadata !== undefined && !this.ownerLifecycle) {
1983
- throw new Error("consumerMetadata requires an Agent-owned conversation");
1984
- }
1985
- if (consumerMetadata !== undefined) {
1986
- const serialized = JSON.stringify(consumerMetadata);
1987
- if (serialized === undefined) throw new Error("consumerMetadata must be a JSON value");
1988
- stableConsumerMetadata = JSON.parse(serialized) as PersistenceJsonValue;
1989
- }
1951
+ stableConsumerMetadata = snapshotConsumerMetadata(consumerMetadata, Boolean(this.ownerLifecycle));
1990
1952
  } catch (error) {
1991
1953
  reject(error);
1992
1954
  return;
@@ -2005,15 +1967,30 @@ export class AgentConversation implements AgentClient, Bridgeable {
2005
1967
  handlers,
2006
1968
  attachments,
2007
1969
  messageParts,
2008
- resolve,
2009
- reject,
1970
+ beforeDispatch,
1971
+ resolve: (result) => {
1972
+ this.acceptedMessages.delete(id);
1973
+ // Settled as cancelled before any turn took it: withdrawn (the tracker ignores it once taken).
1974
+ if (result.status === "cancelled") this.messageStatus.end(id, "withdrawn");
1975
+ resolve(result);
1976
+ },
1977
+ reject: (error) => {
1978
+ this.acceptedMessages.delete(id);
1979
+ this.messageStatus.end(id, "failed");
1980
+ reject(error);
1981
+ },
2010
1982
  };
1983
+ this.acceptedMessages.set(id, { order: ++this.acceptedMessageCount, dispatched: false });
1984
+ this.messageStatus.accept(id);
1985
+ if (steerIntoRunningTurn(this.backendTurnHost(), this.controller, item)) return;
2011
1986
  this.operations.enqueue(item);
2012
1987
  this.steering.accepted(item);
2013
1988
  this.emitStateIfChanged();
2014
1989
  void this.pump();
2015
1990
  });
2016
- return Object.assign(promise, { id, withdraw: () => this.steering.withdraw(id) });
1991
+ const handle = Object.assign(promise, { id, withdraw: () => this.withdraw(id) || (!this.controller.withdrawInput && withdrawWaiting(this.backendTurns, id, messages => this.steering.dropped(messages))), withdrawAsync: () => this.withdrawAsync(id) });
1992
+ const statusOf = this.messageStatus;
1993
+ return Object.defineProperty(handle, "status", { get: () => statusOf.statusOf(id) ?? "failed", enumerable: true }) as PromptHandle;
2017
1994
  }
2018
1995
 
2019
1996
  /**
@@ -2254,7 +2231,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2254
2231
  if (this.operations.isDraining) return;
2255
2232
  try {
2256
2233
  await this.operations.drain(async (item) => {
2257
- this.phase = item.kind === "prompt"
2234
+ this.phase = item.kind === "prompt" || item.kind === "backend_turn"
2258
2235
  ? "prompting"
2259
2236
  : item.kind === "handoff"
2260
2237
  ? "handoff"
@@ -2264,12 +2241,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
2264
2241
  ? "recovering"
2265
2242
  : "switching_mode";
2266
2243
  this.emitStateIfChanged();
2267
- this.runningOperationId = item.kind === "prompt" ? item.turnId
2244
+ this.runningOperationId = item.kind === "prompt" || item.kind === "backend_turn" ? item.turnId
2268
2245
  : item.kind === "handoff" ? item.handoffId
2269
2246
  : item.kind === "set_config" ? item.operationId
2270
2247
  : item.kind === "set_mode" ? item.transitionId
2271
2248
  : null;
2272
- if (item.kind === "prompt") {
2249
+ if (item.kind === "prompt" && this.controller.conversationCapabilities.nativeSteering) {
2250
+ // Backend-scheduled: the session never combines or cancels to steer; the message settles with the turn that takes it.
2251
+ const message = this.steering.prepareRun({ ...item, delivery: "queue" }) as PromptQueueItem;
2252
+ this.backendTurnHost().markSent(message.turnId);
2253
+ await sendToBackend(this.backendTurnHost(), this.controller, message);
2254
+ } else if (item.kind === "prompt") {
2273
2255
  // A run of steer messages at the head of the queue goes out as one prompt.
2274
2256
  let reportDelivery: (() => void) | undefined;
2275
2257
  const prompt = this.steering.prepareRun(item, (event) => {
@@ -2277,12 +2259,46 @@ export class AgentConversation implements AgentClient, Bridgeable {
2277
2259
  }) as PromptQueueItem;
2278
2260
  this.runningOperationId = prompt.turnId;
2279
2261
  this.steering.turnStarted(prompt);
2280
- this.emit({ kind: "turn_started", turnId: prompt.turnId });
2262
+ const run = turnRunOf(prompt);
2263
+ const controller = this.controller;
2281
2264
  let stopReason: string | undefined;
2265
+ /** This turn's provider readiness while it is still running (null once settled). */
2266
+ let readiness: Promise<void> | null = null;
2282
2267
  try {
2283
- await this.ensureProvider();
2268
+ // Checked against the session's own message state, independent of how the run was
2269
+ // built: each id a message it accepted and has not settled, taken out of the queue,
2270
+ // in no other run, in queue (acceptance) order, the turn id being the first.
2271
+ const queued = new Set(this.operations.snapshot().flatMap((queuedItem) =>
2272
+ queuedItem.kind === "prompt" ? [queuedItem.turnId] : []));
2273
+ checkTurnRun(run, (id) => {
2274
+ const message = this.acceptedMessages.get(id);
2275
+ return message && { ...message, queued: queued.has(id) };
2276
+ });
2277
+ for (const id of run.messageIds) this.acceptedMessages.get(id)!.dispatched = true;
2278
+ // Registered before `send`: this controller reports `turn_started` inside the call, and
2279
+ // the session emits it then (with its cause), at the same moment as before.
2280
+ this.sentRuns.set(prompt.turnId, { run });
2281
+ const accepted = controller.send(run);
2282
+ // Observed now so a rejection is never unhandled; it is rethrown below, before dispatch.
2283
+ accepted.catch(() => undefined);
2284
+ let cause = this.sentRuns.get(prompt.turnId)?.cause;
2285
+ if (!cause) {
2286
+ // Not reported inside `send` (a backend-scheduled controller; Brief B2).
2287
+ await accepted;
2288
+ cause = this.sentRuns.get(prompt.turnId)?.cause;
2289
+ }
2290
+ if (!cause) throw new Error(`the controller did not report turn ${prompt.turnId}`);
2291
+ // Provider readiness starts at once after the report, as before the refactor: no
2292
+ // scheduling point between them. The acceptance must still hold before the turn is
2293
+ // dispatched, and a rejection is acted on at once, even while readiness is pending: the
2294
+ // turn fails (abandoned below, no completion). Readiness that is still running then is
2295
+ // waited for after the turn settles (below), so no second reconnect overlaps it.
2296
+ const ready = this.ensureProvider();
2297
+ const settled = ready.then(() => { readiness = null; }, () => { readiness = null; });
2298
+ readiness = settled;
2299
+ await Promise.all([ready, accepted]);
2284
2300
  reportDelivery?.();
2285
- const result = await this.runPrompt(prompt);
2301
+ const result = await this.runPrompt({ turnId: prompt.turnId, cause, messages: prompt });
2286
2302
  stopReason = result.stopReason;
2287
2303
  this.emit({
2288
2304
  kind: "turn_completed",
@@ -2291,6 +2307,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
2291
2307
  });
2292
2308
  prompt.resolve(result);
2293
2309
  } catch (err) {
2310
+ // A turn that never reached its prepared turn's `prompt()` is released; for one that did,
2311
+ // this does nothing (abandonTurn is idempotent and never stops provider work).
2312
+ controller.abandonTurn(prompt.turnId, err);
2294
2313
  // A prompt that never reached the provider (blocked, rejected, no provider) holds nothing.
2295
2314
  const failure = err instanceof OperationStalledError ? "stalled" : "error";
2296
2315
  const providerFailed = this.providerFailedTurnId === prompt.turnId;
@@ -2303,9 +2322,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
2303
2322
  this.emit({ kind: "turn_failed", turnId: prompt.turnId, error: String(err) });
2304
2323
  prompt.reject(err);
2305
2324
  } finally {
2325
+ this.sentRuns.delete(prompt.turnId);
2306
2326
  this.steering.turnEnded(stopReason);
2307
2327
  this.providerFailedTurnId = null;
2308
2328
  }
2329
+ // A turn that failed while its readiness was still running (a rejected acceptance during
2330
+ // a reconnect) has settled; the queue operation still waits for that readiness, as it
2331
+ // would have without the failure, so the next operation does not start a second one.
2332
+ // Bounded like any reconnect: by the provider answering or the process ending.
2333
+ if (readiness) await readiness;
2334
+ } else if (item.kind === "backend_turn") {
2335
+ await runBackendTurn(this.backendTurnHost(), this.controller, item);
2309
2336
  } else if (item.kind === "handoff") {
2310
2337
  try {
2311
2338
  item.resolve(await this.runHandoff(item));
@@ -2438,10 +2465,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
2438
2465
  }
2439
2466
 
2440
2467
  private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
2441
- await this.ensureProvider();
2442
- const fromInternalSessionId = this._internalSessionId;
2443
2468
  const fromAdapterId = this.adapterId;
2444
2469
  const targetAdapterId = item.options.target?.adapterId ?? fromAdapterId;
2470
+ const native = this.controllerDefaults.native !== undefined;
2471
+ if (native ? targetAdapterId !== fromAdapterId : this.controllerDefaults.isNativeAdapter?.(targetAdapterId)) {
2472
+ throw new UnsupportedError("switching to or from a native controller is unsupported");
2473
+ }
2474
+ if (targetAdapterId === fromAdapterId) requireFreshContext(this.controller, "a same-adapter handoff");
2475
+ await this.ensureProvider();
2476
+ const fromInternalSessionId = this._internalSessionId;
2445
2477
  const targetMode = item.options.target?.mode ?? this._mode;
2446
2478
  const continuation = normalizeHandoffContinuation(item.options);
2447
2479
  const transitionKind = targetAdapterId === fromAdapterId ? "handoff" as const : "switch" as const;
@@ -2457,7 +2489,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2457
2489
  let toDescriptor: InternalSessionDescriptor | undefined;
2458
2490
  let summary: string | undefined;
2459
2491
  let targetResult: PromptResult | undefined;
2460
- let targetController: AgentController | null = null;
2492
+ let targetController: ConversationController | null = null;
2461
2493
  let resolvedTargetAdapter: Adapter | null = null;
2462
2494
  let targetMetering: MeteringEngine | null = null;
2463
2495
  let targetActivated = false;
@@ -2501,7 +2533,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2501
2533
  }
2502
2534
 
2503
2535
  try {
2504
- if (continuation.kind !== "none" && this.controller.isDegraded) {
2536
+ if (continuation.kind !== "none" && isDegradedController(this.controller)) {
2505
2537
  throw new Error("handoff continuation requires ACP (normal) mode");
2506
2538
  }
2507
2539
 
@@ -2509,7 +2541,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2509
2541
  // A supplied summary removes the generation operation entirely, so no
2510
2542
  // `:summary` record is ever minted for it.
2511
2543
  summary = continuation.content;
2512
- } else if (continuation.kind === "generated") {
2544
+ } else if (continuation.kind === "generated" && this.controller.prepareInternalPrompt) {
2513
2545
  const generated = await this.meteredInternalPrompt(
2514
2546
  `${item.handoffId}:summary`,
2515
2547
  "handoff_summary",
@@ -2543,7 +2575,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
2543
2575
  }
2544
2576
  resolvedTargetAdapter = adapter;
2545
2577
  targetController = this.createController(adapter, targetAdapterId, targetMode);
2546
- const created = await targetController.startFresh();
2578
+ const candidate = this.handoffTarget = targetController;
2579
+ const created = await this.connectProvider(() => candidate.startFresh());
2547
2580
  if (!created.sessionId) throw new Error("harness returned no session id for handoff");
2548
2581
  toInternalSessionId = created.sessionId;
2549
2582
  // A target naming the source's thread cannot supersede it: the provider mapping and
@@ -2681,6 +2714,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2681
2714
  throw error;
2682
2715
  }
2683
2716
 
2717
+ this.assertConnectionOpen();
2684
2718
  const previousController = this.controller;
2685
2719
  this.controller = targetController;
2686
2720
  this.activeAdapter = resolvedTargetAdapter;
@@ -2833,6 +2867,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2833
2867
  });
2834
2868
  // A rejected handoff cannot return a HandoffResult, but the summary/seed prompts it
2835
2869
  // already ran consumed real tokens; their records travel on the error.
2870
+ if (err instanceof ConnectionCancelledError && records.length === 0) throw err;
2836
2871
  throw new AgentSessionHandoffError(item.handoffId, records, err, {
2837
2872
  fromInternalSessionId,
2838
2873
  ...(toInternalSessionId ? { toInternalSessionId } : {}),
@@ -2841,6 +2876,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
2841
2876
  ...(summary !== undefined ? { summary } : {}),
2842
2877
  ...(targetResult ? { targetResult } : {}),
2843
2878
  });
2879
+ } finally {
2880
+ this.handoffTarget = undefined;
2844
2881
  }
2845
2882
  }
2846
2883
 
@@ -3217,10 +3254,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
3217
3254
 
3218
3255
  private async runSetMode(item: ModeQueueItem): Promise<ConnectResult> {
3219
3256
  await this.ensureProvider();
3220
- if (item.mode === this._mode) return await this.controller.setMode(item.mode);
3257
+ if (item.mode === this._mode) return await this.connectProvider(() => requireMember(this.controller, "setMode", "switching modes")(item.mode));
3221
3258
  if (!this.v2Transcript) {
3222
- const result = await this.controller.setMode(item.mode);
3223
- this._mode = this.controller.currentMode;
3259
+ const result = await this.connectProvider(() => requireMember(this.controller, "setMode", "switching modes")(item.mode));
3260
+ this._mode = this.controller.currentMode ?? this._mode;
3224
3261
  const nextInternalSessionId = result.sessionId || null;
3225
3262
  if (nextInternalSessionId) {
3226
3263
  if (
@@ -3252,8 +3289,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
3252
3289
  reasonCode: "mode_change",
3253
3290
  });
3254
3291
  try {
3255
- const result = await this.controller.setMode(item.mode);
3256
- const targetMode = this.controller.currentMode;
3292
+ const result = await this.connectProvider(() => requireMember(this.controller, "setMode", "switching modes")(item.mode));
3293
+ const targetMode = this.controller.currentMode ?? item.mode;
3257
3294
  const targetInternalSessionId = result.sessionId || null;
3258
3295
  const transitionAt = new Date().toISOString();
3259
3296
  to = this.v2Descriptor(targetInternalSessionId, transitionAt, targetMode);
@@ -3334,457 +3371,68 @@ export class AgentConversation implements AgentClient, Bridgeable {
3334
3371
  }
3335
3372
  }
3336
3373
 
3337
- private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
3338
- const targetProviderContextId = this.ownerLifecycle
3339
- ? this._internalSessionId ?? `runtime:${this.ownerContextNonce ??= crypto.randomUUID()}`
3340
- : undefined;
3341
- const owned = this.ownerLifecycle
3342
- ? await this.ownerLifecycle.beforePrompt({
3343
- operationId: item.turnId,
3344
- agentSessionId: this.ownerAgentSessionId!,
3345
- agentConversationId: this.agentConversationId,
3346
- targetProviderContextId,
3347
- ...(item.participantId ? { participantId: item.participantId } : {}),
3348
- ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
3349
- ...(item.parts ? { parts: item.parts } : {}),
3350
- text: item.text,
3351
- messageParts: item.messageParts,
3352
- attachments: item.attachments,
3353
- mediaContext: {
3354
- cwd: this.controllerDefaults.cwd ?? process.cwd(),
3355
- ...(this.controller.isDegraded
3356
- ? { degraded: true }
3357
- : { capabilities: this.controller.capabilities.agent.promptCapabilities }),
3358
- },
3359
- })
3360
- : undefined;
3361
- for (const participant of owned?.participants ?? (owned?.participant ? [owned.participant] : [])) {
3362
- if (!this._participants.some((known) => known.id === participant.id)) {
3363
- this._participants = [...this._participants, Object.freeze({ ...participant })];
3364
- }
3365
- }
3366
- this.beginTurn(item.turnId);
3367
- let operation: OpenOperation;
3368
- if (this.v2Transcript) {
3369
- let transcriptStarted = false;
3370
- try {
3371
- // Metering preflight has no provider side effect. Run it before minting durable
3372
- // operation evidence so a strict pricing/policy rejection needs no abort record.
3373
- operation = await this.openMeteredOperation(item);
3374
- await this.v2Transcript.beginOperation(item.turnId, persistenceOperationKind(item.operationKind));
3375
- transcriptStarted = true;
3376
- // A combined prompt shows each original message, as it was sent.
3377
- const userTexts = item.parts
3378
- ? item.parts.map((part) => legacyTranscriptText(part.text, part.messageParts, part.attachments))
3379
- : [legacyTranscriptText(item.text, item.messageParts, item.attachments)];
3380
- const userRecords = [];
3381
- for (const [index, text] of userTexts.entries()) {
3382
- userRecords.push(await this.v2Transcript.appendPresentationEvent({
3383
- kind: "message",
3384
- operationId: item.turnId,
3385
- role: "user",
3386
- text,
3387
- status: "completed",
3388
- presentation: { id: `message:${item.turnId}:user${index === 0 ? "" : `:${index + 1}`}`, revision: 1 },
3389
- }));
3390
- }
3391
- await this.v2Transcript.syncBeforeDispatch();
3392
- for (const userRecord of userRecords) this.presentation.emitPersistedRecord(userRecord);
3393
- } catch (error) {
3394
- this.endTurn(item.turnId, item.handlers);
3395
- if (transcriptStarted) {
3396
- await this.v2Transcript.abortOperation("pre_dispatch_persistence_failure").catch(
3397
- (abortError) => this.log.warn("transcript_predispatch_abort_failed", { error: String(abortError) }),
3398
- );
3399
- }
3400
- throw error;
3401
- }
3402
- } else {
3403
- await this.appendTranscript({
3404
- v: 1,
3405
- t: "msg",
3406
- role: "user",
3407
- text: legacyTranscriptText(item.text, item.messageParts, item.attachments),
3408
- ts: Date.now(),
3409
- });
3410
- operation = await this.openMeteredOperation(item);
3411
- }
3374
+ /** Runs one prompt turn; the turn itself lives in `src/conversation-turns/run-turn.ts`. */
3375
+ private runPrompt(turn: TurnContext): Promise<AgentSessionPromptResult> {
3376
+ return runTurn(this.turnRunContext(), turn);
3377
+ }
3412
3378
 
3413
- const chunks: string[] = [];
3414
- const response = new ResponseAccumulator();
3415
- let assistantOrdinal = 0;
3416
- let assistantMessage: {
3417
- readonly id: string;
3418
- providerMessageId?: string;
3419
- text: string;
3420
- parts?: readonly ResolvedPart[];
3421
- revision: number;
3422
- dirty: boolean;
3423
- } | null = null;
3424
- const beginAssistantMessage = (providerMessageId?: string) => {
3425
- assistantOrdinal++;
3426
- assistantMessage = {
3427
- id: `message:${item.turnId}:assistant:${assistantOrdinal}`,
3428
- ...(providerMessageId === undefined ? {} : { providerMessageId }),
3429
- text: "",
3430
- revision: 0,
3431
- dirty: false,
3432
- };
3433
- return assistantMessage;
3434
- };
3435
- // When each message that ended before the turn did received its last text, in order. The
3436
- // turn's commit records those messages as completed at these times; only the last message
3437
- // takes the turn's own outcome.
3438
- const messageEnds: string[] = [];
3439
- const flushAssistantMessage = (
3440
- status: "in_progress" | "completed" | "cancelled" | "error",
3441
- stopReason?: string,
3442
- force = false,
3443
- ended = false,
3444
- ) => {
3445
- if ((!this.v2Transcript && !this.ownerLifecycle) || !assistantMessage
3446
- || (!assistantMessage.dirty && !force)) return;
3447
- assistantMessage.revision++;
3448
- assistantMessage.dirty = false;
3449
- const message = assistantMessage;
3450
- const timestamp = new Date().toISOString();
3451
- if (ended) messageEnds.push(timestamp);
3452
- if (this.ownerAgentSessionId && (status === "in_progress" || ended)) {
3453
- this.queueOwnedRecord({
3454
- recordId: `${message.id}:snapshot:${message.revision}`,
3455
- agentSessionId: this.ownerAgentSessionId,
3456
- agentConversationId: this.agentConversationId,
3457
- kind: "message",
3458
- timestamp,
3459
- operationId: item.turnId,
3460
- role: "assistant",
3461
- logicalMessageId: message.id,
3462
- content: message.text,
3463
- status: ended ? "completed" : "in_progress",
3464
- metadata: JSON.stringify({ operationId: item.turnId,
3465
- ...(message.providerMessageId ? { providerMessageId: message.providerMessageId } : {}) }),
3466
- }, message.parts);
3467
- }
3468
- if (this.v2Transcript) this.presentation.queuePresentation({
3469
- kind: "message",
3470
- operationId: item.turnId,
3471
- role: "assistant",
3472
- text: message.parts ? transcriptParts(message.parts) : message.text,
3473
- ...(message.providerMessageId === undefined ? {} : { providerMessageId: message.providerMessageId }),
3474
- structured: {
3475
- version: 1,
3476
- messages: [message.providerMessageId === undefined
3477
- ? { text: message.text }
3478
- : { messageId: message.providerMessageId, text: message.text }],
3479
- },
3480
- status,
3481
- ...(stopReason === undefined ? {} : { stopReason }),
3482
- presentation: { id: message.id, revision: message.revision },
3483
- });
3484
- };
3485
- // A message receives no more text once the next message or a tool call begins. Record it
3486
- // completed then, rather than leaving it open until the turn ends.
3487
- const endAssistantMessage = () => {
3488
- flushAssistantMessage("completed", undefined, true, true);
3489
- assistantMessage = null;
3490
- };
3491
- const wrappedHandlers: PromptHandlers = {
3492
- ...item.handlers,
3493
- // Fired from here, from the one aggregator this session owns — nothing below needs
3494
- // to know the handler exists, and two places firing it would be two folds.
3495
- onRecord: undefined,
3496
- onChunk: (chunk) => {
3497
- chunks.push(chunk);
3498
- item.handlers?.onChunk?.(chunk);
3379
+ /** What a turn reads and changes in this session (`TurnRunContext`), read live through getters. */
3380
+ private turnRunContext(): TurnRunContext {
3381
+ const session = this;
3382
+ return {
3383
+ log: this.log,
3384
+ get controller() { return session.controller; },
3385
+ supervisedPrompt: (controller, operationId, kind, provider) =>
3386
+ this.supervisedPrompt(controller, operationId, kind, provider),
3387
+ get supervising() { return session.activeSupervisor !== null; },
3388
+ persistence: {
3389
+ get v2Transcript() { return session.v2Transcript; },
3390
+ appendTranscript: (line) => this.appendTranscript(line),
3391
+ persist: () => this.persist(),
3392
+ finishV2Prompt: (status, record, errorCode) => this.finishV2Prompt(status, record, errorCode),
3499
3393
  },
3500
- onResponseChunk: (chunk) => {
3501
- const settledReasoning = this.presentation.closeReasoningBoundary();
3502
- if (settledReasoning) {
3503
- this.queueActivityRecords(item.turnId, [settledReasoning]);
3504
- item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
3505
- }
3506
- response.append(chunk);
3507
- if (this.v2Transcript || this.ownerLifecycle) {
3508
- if (chunk.startsMessage) {
3509
- endAssistantMessage();
3510
- beginAssistantMessage(chunk.messageId);
3511
- }
3512
- const current = assistantMessage ?? beginAssistantMessage(chunk.messageId);
3513
- if (current.providerMessageId === undefined && chunk.messageId !== undefined) {
3514
- current.providerMessageId = chunk.messageId;
3515
- }
3516
- current.text += chunk.text;
3517
- current.parts = response.currentParts();
3518
- current.dirty = true;
3519
- // Persist the first usable snapshot. Later token chunks remain in memory until
3520
- // an interleaving item, a new message, or the operation boundary.
3521
- if (current.revision === 0) flushAssistantMessage("in_progress");
3522
- }
3523
- item.handlers?.onResponseChunk?.(chunk);
3394
+ permissions: this.permissions,
3395
+ presentation: this.presentation,
3396
+ metering: {
3397
+ open: (item) => this.openMeteredOperation(item),
3398
+ close: (operation, outcome, reportedCumulative, usageFailureReason, nativeMetering) =>
3399
+ this.closeOperation(operation, outcome, reportedCumulative, usageFailureReason, this.metering, nativeMetering),
3524
3400
  },
3525
- onActivity: (event) => {
3526
- // The message snapshot must enter the shared queue before an activity first seen
3527
- // after it. Later activity revisions keep their original presentation position.
3528
- if (event.kind === "tool") endAssistantMessage();
3529
- else flushAssistantMessage("in_progress");
3530
- if (!this.activeSupervisor) this.steering.observeActivity(item.turnId, event);
3531
- const result = this.presentation.applyActivity(event);
3532
- this.queueActivityRecords(item.turnId, result.emitted);
3533
- item.handlers?.onRecord?.(result);
3534
- item.handlers?.onActivity?.(event);
3401
+ steering: this.steering,
3402
+ owner: {
3403
+ get lifecycle() { return session.ownerLifecycle; },
3404
+ get agentSessionId() { return session.ownerAgentSessionId; },
3405
+ get agentConversationId() { return session.agentConversationId; },
3406
+ contextNonce: () => this.ownerContextNonce ??= crypto.randomUUID(),
3407
+ queueRecord: (record, parts) => this.queueOwnedRecord(record, parts),
3408
+ recordNow: (record) => this.recordOwned(record),
3409
+ get recordWrite() { return session.ownerRecordWrite; },
3535
3410
  },
3536
- onPermissionRequest: async (request, signal) => {
3537
- const permissionBase = `${item.turnId}:permission:${request.toolCallId}`;
3538
- if (this.ownerAgentSessionId) {
3539
- await this.recordOwned({
3540
- recordId: `${permissionBase}:requested`,
3541
- agentSessionId: this.ownerAgentSessionId,
3542
- agentConversationId: this.agentConversationId,
3543
- kind: "permission",
3544
- timestamp: new Date().toISOString(),
3545
- operationId: item.turnId,
3546
- permissionId: request.toolCallId,
3547
- state: "requested",
3548
- request: toPersistenceJsonValue({
3549
- toolCallId: request.toolCallId,
3550
- ...(request.title ? { title: request.title } : {}),
3551
- options: request.options,
3552
- raw: request.raw,
3553
- }),
3554
- });
3555
- }
3556
- const outcome = item.handlers?.onPermissionRequest
3557
- ? await permissionWithAbort(() => item.handlers!.onPermissionRequest!(request, signal), signal)
3558
- : defaultPermissionOutcome(request, this.defaultPermission);
3559
- if (this.ownerAgentSessionId) {
3560
- await this.recordOwned({
3561
- recordId: `${permissionBase}:resolved`,
3562
- agentSessionId: this.ownerAgentSessionId,
3563
- agentConversationId: this.agentConversationId,
3564
- kind: "permission",
3565
- timestamp: new Date().toISOString(),
3566
- operationId: item.turnId,
3567
- permissionId: request.toolCallId,
3568
- state: "resolved",
3569
- outcome: permissionRecordOutcome(request, outcome),
3570
- });
3571
- }
3572
- return outcome;
3411
+ turn: {
3412
+ begin: (turnId) => this.beginTurn(turnId),
3413
+ end: (turnId, handlers) => this.endTurn(turnId, handlers),
3414
+ queueActivityRecords: (turnId, records) => this.queueActivityRecords(turnId, records),
3573
3415
  },
3574
- };
3575
-
3576
- let closed: OperationMeteringRecord | null = null;
3577
- let transcriptClosed = false;
3578
- let providerSettled = false;
3579
- // A lazily created thread acquires its provider session during dispatch, so this is the
3580
- // closest observable acquisition time when `session/new` happens inside `prompt()`.
3581
- const dispatchedAt = new Date().toISOString();
3582
- try {
3583
- let res = await this.supervisedPrompt(this.controller, item.turnId, "turn",
3584
- // An owned conversation already resolved the parts and wrapped them with the provider-only
3585
- // text (identity, out-of-band messages); otherwise the client resolves them.
3586
- () => this.controller.prompt(owned?.providerParts
3587
- ? { parts: unresolvedParts(owned.providerParts), handlers: wrappedHandlers }
3588
- : item.messageParts
3589
- ? { parts: item.messageParts, attachments: item.attachments, handlers: wrappedHandlers }
3590
- : { text: item.text, attachments: item.attachments, handlers: wrappedHandlers }));
3591
- if (res.cancel === "forced") {
3592
- const messages = response.snapshot();
3593
- res = { ...res, messages, text: response.text || chunks.join("") };
3594
- }
3595
- providerSettled = true;
3596
- if (this.v2Transcript) {
3597
- if (assistantOrdinal === 0) {
3598
- for (const message of res.messages) {
3599
- const current = beginAssistantMessage(message.messageId);
3600
- current.text = message.text;
3601
- current.dirty = true;
3602
- flushAssistantMessage(res.status, res.stopReason, true);
3603
- }
3604
- } else {
3605
- flushAssistantMessage(res.status, res.stopReason, true);
3606
- }
3607
- }
3608
- // Before the assistant msg: `msg` delimits a turn, so anything still open has to
3609
- // land inside those fences.
3610
- this.endTurn(item.turnId, item.handlers);
3611
- if (!this._title && item.text.trim()) {
3612
- this._title = item.text.trim().replace(/\s+/g, " ").slice(0, 60);
3613
- }
3614
- // A session may have been created lazily on first prompt (degraded has none).
3615
- const observedInternalSessionId = this.controller.currentSessionId ?? this._internalSessionId;
3616
- if (observedInternalSessionId) {
3617
- if (
3618
- this.providerAttachment.kind === "absent"
3619
- || this.providerAttachment.descriptor.internalSessionId !== observedInternalSessionId
3620
- ) {
3621
- this.installProviderAttachment(observedInternalSessionId, "runtime_only", true, {
3622
- acquiredAt: dispatchedAt,
3623
- });
3624
- }
3625
- } else {
3626
- this.setInternalSessionId(observedInternalSessionId);
3627
- }
3628
- // Metering closes BEFORE local persistence. The provider has already been paid and
3629
- // has already told us what it charged; letting a transcript or catalog write failure
3630
- // send us down the catch path would discard usage we are holding and, in a strict
3631
- // mode, block the session over a local disk problem.
3632
- //
3633
- // `closed` then guards the catch path. Closing twice would accrue the operation
3634
- // twice and emit a second record for it — double-counting tokens and cost, which is
3635
- // a worse failure than the one closing early prevents.
3636
- const record = await this.closeOperation(operation, res.status, res.usage);
3637
- closed = record;
3638
- await this.ownerLifecycle?.meteringRecorded?.(record);
3639
- // The Agent-owned and transcript paths record the attachment inside their own
3640
- // commit. A catalog-backed conversation has one mutable row, so the completed turn
3641
- // is simply what makes the live thread the selected one.
3642
- const pending = this.providerAttachment;
3643
- if (res.status === "completed"
3644
- && !this.ownerLifecycle
3645
- && !this.v2Transcript
3646
- && pending.kind === "runtime_only") {
3647
- this.providerAttachment = recordedProviderAttachment(pending.descriptor);
3648
- this.lastRecordedInternalSessionId = pending.descriptor.internalSessionId;
3649
- }
3650
- await this.persist();
3651
- if (this.v2Transcript) {
3652
- await this.presentation.drain();
3653
- await this.finishV2Prompt(res.status, record);
3654
- transcriptClosed = true;
3655
- } else {
3656
- await this.appendTranscript({
3657
- v: 1,
3658
- t: "msg",
3659
- role: "assistant",
3660
- ...legacyTranscriptMessages(res.messages, res.text),
3661
- ts: Date.now(),
3662
- usage: res.usage,
3663
- stopReason: res.stopReason,
3664
- status: res.status,
3665
- });
3666
- }
3667
- const result = Object.freeze({
3668
- ...res,
3669
- operationId: item.turnId,
3670
- metering: record,
3671
- ...this.steering.resultFields(item.turnId, res.stopReason),
3672
- });
3673
- await this.ownerRecordWrite;
3674
- if (this.ownerLifecycle) {
3675
- const completed = {
3676
- operationId: item.turnId,
3677
- agentSessionId: this.ownerAgentSessionId!,
3678
- agentConversationId: this.agentConversationId,
3679
- targetProviderContextId,
3680
- ...(owned?.identityDeliveryReceipt
3681
- ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3682
- : {}),
3683
- ...(item.participantId ? { participantId: item.participantId } : {}),
3684
- text: item.text,
3685
- result,
3686
- messageEnds,
3687
- providerAttachment: this.providerAttachment,
3688
- };
3689
- try {
3690
- const committed = await this.ownerLifecycle.afterPrompt(completed);
3691
- if (committed?.providerAttachment) {
3692
- this.providerAttachment = acknowledgeProviderAttachment(
3693
- this.providerAttachment,
3694
- committed.providerAttachment,
3695
- );
3416
+ session: {
3417
+ get cwd() { return session.controllerDefaults.cwd; },
3418
+ permissionPolicy: this.controllerDefaults,
3419
+ get internalSessionId() { return session._internalSessionId; },
3420
+ setInternalSessionId: (next) => this.setInternalSessionId(next),
3421
+ get title() { return session._title; },
3422
+ set title(value) { session._title = value; },
3423
+ learnParticipant: (participant) => {
3424
+ if (!this._participants.some((known) => known.id === participant.id)) {
3425
+ this._participants = [...this._participants, Object.freeze({ ...participant })];
3696
3426
  }
3697
- } catch (error) {
3698
- if (error instanceof OwnedPromptPostCommitError) {
3699
- if (error.commit.providerAttachment) {
3700
- this.providerAttachment = acknowledgeProviderAttachment(
3701
- this.providerAttachment,
3702
- error.commit.providerAttachment,
3703
- );
3704
- }
3705
- throw error.cause ?? error;
3706
- }
3707
- throw error;
3708
- }
3709
- }
3710
- await this.ownerRecordWrite;
3711
- return result;
3712
- } catch (err) {
3713
- // Easy to miss, and the whole point of R4: a turn that died mid-tool still records
3714
- // what it was doing, at its real status.
3715
- this.endTurn(item.turnId, item.handlers);
3716
- const structured = response.snapshot();
3717
- const text = structured.length > 0 ? response.text : chunks.join("");
3718
- const messages: readonly ResponseMessage[] = structured.length > 0
3719
- ? structured
3720
- : text
3721
- ? Object.freeze([{ text }])
3722
- : Object.freeze([]);
3723
- if (!providerSettled) {
3724
- await this.ownerRecordWrite.catch((persistenceError) => {
3725
- this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
3726
- });
3727
- await this.ownerLifecycle?.promptFailed({
3728
- operationId: item.turnId,
3729
- agentSessionId: this.ownerAgentSessionId!,
3730
- agentConversationId: this.agentConversationId,
3731
- ...(item.participantId ? { participantId: item.participantId } : {}),
3732
- text: item.text,
3733
- messages,
3734
- messageEnds,
3735
- error: err,
3736
- }).catch((persistenceError) => {
3737
- this.log.warn("owned_prompt_failure_persistence_failed", { error: String(persistenceError) });
3738
- });
3739
- }
3740
- await this.ownerRecordWrite.catch((persistenceError) => {
3741
- this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
3742
- });
3743
- if (this.v2Transcript) {
3744
- if (!transcriptClosed && assistantOrdinal === 0 && messages.length > 0) {
3745
- for (const message of messages) {
3746
- const current = beginAssistantMessage(message.messageId);
3747
- current.text = message.text;
3748
- current.dirty = true;
3749
- flushAssistantMessage("error", "error", true);
3750
- }
3751
- } else if (!transcriptClosed) {
3752
- flushAssistantMessage("error", "error", true);
3753
- }
3754
- await this.presentation.drain().catch(() => undefined);
3755
- } else {
3756
- await this.appendTranscript({
3757
- v: 1,
3758
- t: "msg",
3759
- role: "assistant",
3760
- ...legacyTranscriptMessages(messages, text),
3761
- ts: Date.now(),
3762
- stopReason: "error",
3763
- status: "error",
3764
- });
3765
- }
3766
- // A failed operation may still have consumed tokens, so its record has to survive
3767
- // the rejection rather than only reaching event subscribers.
3768
- // Already metered: the failure happened after the operation closed (a transcript or
3769
- // catalog write), so the record stands and must not be minted a second time.
3770
- const outcome = err instanceof OperationStalledError ? "cancelled" : "error";
3771
- const record = closed ?? (await this.closeOperation(operation, outcome, null, String(err)));
3772
- await this.ownerLifecycle?.meteringRecorded?.(record);
3773
- if (this.v2Transcript && !transcriptClosed) {
3774
- await this.finishV2Prompt("error", record, "unknown").catch(
3775
- (persistenceError) => this.log.warn("transcript_terminal_write_failed", { error: String(persistenceError) }),
3776
- );
3777
- }
3778
- if (err instanceof OperationStalledError) {
3779
- err.messages = messages;
3780
- err.metering = record;
3781
- await this.ownerLifecycle?.operationFailed?.({ operationId: item.turnId, error: err }).catch((error) => {
3782
- this.log.warn("operation_failure_recording_failed", { error: String(error) });
3783
- });
3784
- throw err;
3785
- }
3786
- throw new AgentSessionOperationError(item.turnId, record, err);
3787
- }
3427
+ },
3428
+ get providerAttachment() { return session.providerAttachment; },
3429
+ set providerAttachment(value) { session.providerAttachment = value; },
3430
+ installProviderAttachment: (internalSessionId, kind, created, options) =>
3431
+ this.installProviderAttachment(internalSessionId, kind, created, options),
3432
+ get lastRecordedInternalSessionId() { return session.lastRecordedInternalSessionId; },
3433
+ set lastRecordedInternalSessionId(value) { session.lastRecordedInternalSessionId = value; },
3434
+ },
3435
+ };
3788
3436
  }
3789
3437
 
3790
3438
  private openMeteredOperation(item: PromptQueueItem): Promise<OpenOperation> {
@@ -3794,7 +3442,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
3794
3442
  internalSessionId: this._internalSessionId,
3795
3443
  providerId: this.providerId,
3796
3444
  model: this.model,
3797
- degraded: this.controller.isDegraded,
3445
+ native: this.controllerDefaults.native,
3446
+ degraded: isDegradedController(this.controller),
3798
3447
  });
3799
3448
  }
3800
3449
 
@@ -3902,12 +3551,20 @@ export class AgentConversation implements AgentClient, Bridgeable {
3902
3551
 
3903
3552
  /** @internal Acquire a fresh leaf for checkpoint recovery without replacing this conversation. */
3904
3553
  async restartProviderFresh(): Promise<void> {
3554
+ requireFreshContext(this.controller, "restarting on a fresh provider session");
3905
3555
  await this.controller.forceStop();
3906
- const result = await this.controller.startFresh();
3556
+ const result = await this.startController(true);
3907
3557
  if (!result.sessionId) throw new Error("provider returned no fresh session");
3908
3558
  this.installProviderAttachment(result.sessionId, "runtime_only", true);
3909
3559
  }
3910
3560
 
3561
+ /** Observe an existing backend channel without changing its lifecycle. */
3562
+ async attachObservation(): Promise<{ dispose(): void }> {
3563
+ const controller = this.controller;
3564
+ if (!controller.attachObservation) throw new UnsupportedError("The controller does not support observation-only attachment");
3565
+ return controller.attachObservation();
3566
+ }
3567
+
3911
3568
  private async ensureProvider(): Promise<void> {
3912
3569
  if (this.controller.isConnected) return;
3913
3570
  if (this.phase === "stopped") throw new Error("conversation is stopped");
@@ -3919,20 +3576,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
3919
3576
  let via: "loaded" | "recovered" | "fresh" = "loaded";
3920
3577
  try {
3921
3578
  try {
3922
- if (sessionId) await this.controller.reconnect(sessionId);
3923
- else await this.controller.startFresh();
3579
+ if (!sessionId) await this.startController(true);
3580
+ else await this.connectProvider(() => reloadProviderSession(this.controller, sessionId)); // no reconnect: recovery decides
3924
3581
  } catch (error) {
3925
- if (!sessionId) throw error;
3582
+ if (!sessionId || error instanceof ConnectionCancelledError) throw error;
3926
3583
  via = await this.continueWithoutProviderSession(sessionId, error);
3927
3584
  }
3928
3585
  if (this.state.phase === "stopped") {
3929
3586
  await this.controller.forceStop();
3930
- throw new Error("conversation stopped during reconnect");
3587
+ throw new ConnectionCancelledError();
3931
3588
  }
3932
3589
  const loadedId = this.controller.currentSessionId;
3933
3590
  if (via === "loaded" && loadedId && loadedId !== this._internalSessionId) {
3934
3591
  this.installProviderAttachment(loadedId, "runtime_only", !sessionId);
3935
3592
  }
3593
+ if (this.deferredProviderStart && !sessionId) via = "fresh";
3594
+ this.deferredProviderStart = false;
3936
3595
  this.emit({ kind: "provider_reconnected", via, internalSessionId: this._internalSessionId! });
3937
3596
  } catch (error) {
3938
3597
  await this.controller.forceStop().catch(() => {});
@@ -3989,7 +3648,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3989
3648
  return "recovered";
3990
3649
  }
3991
3650
  if (this.sessionLoadFailure === "error") unavailable(loadFailed("provider_session_missing"));
3992
- const created = await this.controller.startFresh();
3651
+ const created = await this.startController(true);
3993
3652
  if (!created.sessionId) throw new Error("harness returned no session id for a replacement session");
3994
3653
  this.installProviderAttachment(created.sessionId, "runtime_only", true);
3995
3654
  return "fresh";
@@ -4034,26 +3693,22 @@ export class AgentConversation implements AgentClient, Bridgeable {
4034
3693
 
4035
3694
  /** Run one provider request under its own supervisor: stage, stale conditions, cancel escalation. */
4036
3695
  private async supervisedPrompt(
4037
- controller: AgentController,
3696
+ controller: ConversationController,
4038
3697
  operationId: string,
4039
3698
  kind: "turn" | "internal_inference" | "recap",
4040
- prompt: () => Promise<PromptResult>,
3699
+ provider: SupervisedProvider,
4041
3700
  ): Promise<PromptResult> {
4042
3701
  const limits = kind === "turn"
4043
3702
  ? this.operationLifecycle.turns
4044
3703
  : kind === "recap" ? this.operationLifecycle.recap : this.operationLifecycle.internalInference;
4045
- const supervisor = new OperationSupervisor({
4046
- prompt,
4047
- subscribeOutput: (listener) => controller.subscribeOutput(listener),
4048
- cancel: () => controller.cancel(),
4049
- forceStop: () => controller.forceStop(),
4050
- }, {
3704
+ const supervisor = new OperationSupervisor(provider, {
4051
3705
  operationId,
4052
3706
  kind,
4053
3707
  sessionId: controller.currentSessionId,
4054
3708
  cancelGraceMs: controller.cancelGraceMs,
4055
3709
  // A screen-scraped harness cannot report tools or permissions, so silence explains nothing.
4056
- limits: controller.isDegraded ? { firstOutputMs: false, nextOutputMs: false, ...limits } : limits,
3710
+ limits: stallLimitsFor(controller, limits),
3711
+ isReplaying: () => (provider as { live?: boolean }).live === false,
4057
3712
  onStageChanged: (activity) => {
4058
3713
  this.emit({ kind: "operation_stage_changed", activity });
4059
3714
  this.emitStateIfChanged();
@@ -4092,6 +3747,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
4092
3747
  target?: InternalPromptTarget,
4093
3748
  ): Promise<PromptResult> {
4094
3749
  const controller = target?.controller ?? this.controller;
3750
+ const prepareInternalPrompt = requireMember(controller, "prepareInternalPrompt", "internal prompts"); // before any operation is opened
4095
3751
  if (!target && !this.reconnecting) await this.ensureProvider();
4096
3752
  const metering = target?.metering ?? this.metering;
4097
3753
  const advertised = target ? activeModel(target.controller.configOptions) : this.advertisedModel;
@@ -4102,7 +3758,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
4102
3758
  internalSessionId: target ? controller.currentSessionId : this._internalSessionId,
4103
3759
  providerId: target ? reference?.providerId ?? null : this.providerId,
4104
3760
  model: target ? reference?.modelId ?? advertised : this.model,
4105
- degraded: controller.isDegraded,
3761
+ degraded: isDegradedController(controller),
4106
3762
  });
4107
3763
  let transcriptStarted = false;
4108
3764
  if (this.v2Transcript) {
@@ -4131,7 +3787,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
4131
3787
  this.runningOperationId = operationId;
4132
3788
  try {
4133
3789
  const kind = operationKind === "conversation_checkpoint" ? "recap" : "internal_inference";
4134
- const result = await this.supervisedPrompt(controller, operationId, kind, () => controller.prompt(text));
3790
+ const result = await this.supervisedPrompt(controller, operationId, kind,
3791
+ prepareInternalPrompt({ input: { text }, handlers: this.permissions.internalHandler(operationId, this.controllerDefaults) }));
4135
3792
  const record = await this.closeOperation(
4136
3793
  operation,
4137
3794
  result.status,
@@ -4188,6 +3845,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
4188
3845
  }
4189
3846
  throw err;
4190
3847
  } finally {
3848
+ this.permissions.end(operationId);
4191
3849
  this.runningOperationId = enclosingOperationId;
4192
3850
  }
4193
3851
  }
@@ -4220,38 +3878,32 @@ export class AgentConversation implements AgentClient, Bridgeable {
4220
3878
  : internalSessionId
4221
3879
  ? observedAt
4222
3880
  : null,
4223
- protocol: this.controller.isDegraded ? { name: "pty" } : { name: "acp", version: 1 },
3881
+ protocol: isDegradedController(this.controller) ? { name: "pty" } : { name: "acp", version: 1 },
4224
3882
  };
4225
3883
  }
4226
3884
 
4227
- /**
4228
- * Close a rating unit, emit its record, and surface a strict-mode block.
4229
- *
4230
- * `contextAfter`/`providerCostAfter` are the latest observations seen by completion.
4231
- * ACP gives no ordering guarantee, so neither is asserted to describe THIS operation.
4232
- */
4233
3885
  private async closeOperation(
4234
3886
  operation: OpenOperation,
4235
3887
  outcome: "completed" | "cancelled" | "error",
4236
3888
  reportedCumulative: TokenUsage | null,
4237
3889
  usageFailureReason?: string,
4238
3890
  engine: MeteringEngine = this.metering,
3891
+ nativeMetering?: CloseOperationInput["nativeMetering"],
4239
3892
  ): Promise<OperationMeteringRecord> {
4240
- const wasBlocked = engine.blocked;
4241
- const live = engine === this.metering;
3893
+ const wasBlocked = engine.blocked, live = engine === this.metering;
3894
+ const recovery = this.ownerLifecycle?.nativeMetering;
3895
+ const replay = operation.nativeChannel ? await recoverNativeClose(recovery, engine, operation) : null;
3896
+ if (replay) return replay;
4242
3897
  const record = await engine.close(operation, {
4243
3898
  outcome,
4244
3899
  reportedCumulative,
3900
+ nativeMetering: withNativeAccounting(nativeMetering, recovery),
4245
3901
  ...(usageFailureReason ? { usageFailureReason } : {}),
4246
- // Context and provider cost describe the live thread. An unconfirmed transition
4247
- // target has neither yet, and borrowing the source's would misreport it.
4248
3902
  contextAfter: live ? this._contextWindow : null,
4249
3903
  providerCostAfter: live ? this._providerCost : null,
4250
3904
  });
4251
3905
  this.emit({ kind: "metering_recorded", record });
4252
- if (!wasBlocked && engine.blocked) {
4253
- this.emit({ kind: "metering_blocked", reason: engine.blockedReason ?? "unknown" });
4254
- }
3906
+ if (!wasBlocked && engine.blocked) this.emit({ kind: "metering_blocked", reason: engine.blockedReason ?? "unknown" });
4255
3907
  return record;
4256
3908
  }
4257
3909
 
@@ -4275,6 +3927,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
4275
3927
  }
4276
3928
 
4277
3929
  private endTurn(turnId: string, handlers?: PromptHandlers): void {
3930
+ this.permissions.end(turnId);
4278
3931
  this.queueActivityRecords(turnId, this.presentation.endTurn(handlers));
4279
3932
  }
4280
3933
 
@@ -4304,21 +3957,11 @@ export class AgentConversation implements AgentClient, Bridgeable {
4304
3957
  // A stop closes the connection, so its turn fails and `endedBy` is never reported for it.
4305
3958
  this.steering.interrupted();
4306
3959
  if (options?.clearQueue) {
4307
- const dropped = this.operations.clear();
4308
- // Cancelled before dispatch: nothing was sent, so nothing was consumed and no
4309
- // metering record is minted (§16).
4310
- this.steering.dropped(dropped.filter((item): item is PromptQueueItem => item.kind === "prompt"));
4311
- for (const item of dropped) {
4312
- if (item.kind === "prompt") continue;
4313
- const label = item.kind === "handoff"
4314
- ? "handoff"
4315
- : item.kind === "set_config" || item.kind === "resolve_config"
4316
- ? "configuration change"
4317
- : item.kind === "resolve_recovery"
4318
- ? "recovery resolution"
4319
- : "mode change";
4320
- item.reject(new Error(`${label} cancelled before it started`));
4321
- }
3960
+ const cancellation = reason === "stop" && (this.reconnecting || this.connecting > 0)
3961
+ ? new ConnectionCancelledError() : undefined;
3962
+ const dropped = settleClearedBackendTurns(this.operations.clear(), reason === "stop", (turn) => { this.operations.enqueue(turn); void this.pump(); });
3963
+ const backend = this.backendTurns.clear(reason === "stop", Boolean(this.controller.withdrawInput));
3964
+ dropClearedOperations(dropped, backend, (messages, error) => this.steering.dropped(messages, error), cancellation, reason === "stop" && Boolean(this.controller.withdrawInput));
4322
3965
  this.emitStateIfChanged();
4323
3966
  }
4324
3967
  this.cancelOperation(reason);
@@ -4326,19 +3969,21 @@ export class AgentConversation implements AgentClient, Bridgeable {
4326
3969
 
4327
3970
  stop(): Promise<void> {
4328
3971
  if (this.stopPromise) return this.stopPromise;
4329
- // Publish the terminal state synchronously. All callers then share the same
4330
- // completion promise, including callers arriving while teardown is in progress.
3972
+ // Publish the terminal state synchronously and share teardown with later callers.
4331
3973
  this.phase = "stopped";
4332
3974
  const failures: unknown[] = [];
3975
+ const cancel = captureStopFailure(() => this.cancelRunning("stop", { clearQueue: true }), failures);
3976
+ const native = this.controller.withdrawInput !== undefined;
4333
3977
  const completion = Promise.resolve().then(async () => {
4334
- try {
4335
- await this.controller.stop();
4336
- } catch (error) {
4337
- failures.push(error);
3978
+ if (native) {
3979
+ await this.backendTurns.withdrawBeforeStop(this.controller);
3980
+ cancel();
3981
+ }
3982
+ const controllers = new Set([this.controller, this.handoffTarget]);
3983
+ for (const result of await Promise.allSettled([...controllers].map(async controller => controller?.stop()))) {
3984
+ if (result.status === "rejected") failures.push(result.reason);
4338
3985
  }
4339
- // Closing the provider can reject an active prompt. Its catch/finally path may
4340
- // enqueue final message and metering writes, so the pre-stop write tail is not
4341
- // sufficient evidence that persistence is quiescent.
3986
+ // Wait for the provider rejection and its finalization writes before draining persistence.
4342
3987
  try {
4343
3988
  await this.operations.waitForIdle();
4344
3989
  } catch (error) {
@@ -4368,11 +4013,8 @@ export class AgentConversation implements AgentClient, Bridgeable {
4368
4013
  if (failures.length > 1) throw new AggregateError(failures, "AgentSession shutdown failed");
4369
4014
  });
4370
4015
  this.stopPromise = completion;
4371
- try {
4372
- this.cancelRunning("stop", { clearQueue: true });
4373
- } catch (error) {
4374
- failures.push(error);
4375
- }
4016
+ this.permissions.stop();
4017
+ if (!native) cancel();
4376
4018
  this.emitStateIfChanged();
4377
4019
  return completion;
4378
4020
  }
@@ -4381,6 +4023,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
4381
4023
  async setMode(mode: AgentMode): Promise<ConnectResult> {
4382
4024
  if (this.phase === "stopped") throw new Error("AgentSession is stopped");
4383
4025
  this.assertPromptable();
4026
+ requireMember(this.controller, "setMode", "switching modes"); // refused before anything is queued
4384
4027
  return await new Promise<ConnectResult>((resolve, reject) => {
4385
4028
  this.operations.enqueue({
4386
4029
  kind: "set_mode",
@@ -4394,9 +4037,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
4394
4037
  });
4395
4038
  }
4396
4039
 
4397
- // --- thin proxies to the live connection -------------------------------------
4398
4040
  get capabilities(): Capabilities {
4399
- return this.controller.capabilities;
4041
+ return acpCapabilitiesOf(this.controller);
4042
+ }
4043
+ /** What the backend offers, in neutral terms; safe to read before connecting and in PTY mode. */
4044
+ get conversationCapabilities(): ConversationCapabilities { return this.controller.conversationCapabilities; }
4045
+ get reminders() {
4046
+ const service = this.ownerLifecycle?.reminders;
4047
+ if (!service) throw new ReminderError(this.conversationCapabilities.reminders ? "reminders_unavailable" : "reminders_unsupported", "Reminders require an owning Agent and a native conversation");
4048
+ return service.conversation(this.agentConversationId, this.conversationCapabilities.reminders === true, event => this.emit(event));
4400
4049
  }
4401
4050
  get configOptions(): ConfigOptions {
4402
4051
  return this.controller.configOptions;
@@ -4483,19 +4132,19 @@ export class AgentConversation implements AgentClient, Bridgeable {
4483
4132
  }
4484
4133
  /** Immutable snapshot of commands advertised by the active ACP harness. */
4485
4134
  get internalSessionCommands(): readonly InternalSessionCommand[] {
4486
- return this.controller.availableCommands;
4135
+ return availableCommandsOf(this.controller);
4487
4136
  }
4488
4137
  get isDegraded(): boolean {
4489
- return this.controller.isDegraded;
4138
+ return isDegradedController(this.controller);
4490
4139
  }
4491
4140
  bridge(options?: BridgeOptions): Promise<void> {
4492
- return this.controller.bridge(options);
4141
+ return requireMember(this.controller, "bridge", "a terminal bridge")(options);
4493
4142
  }
4494
4143
  authenticate(
4495
4144
  methodId: string,
4496
4145
  handlers?: { onOutput?: (line: string) => void },
4497
4146
  ): Promise<unknown> {
4498
- return this.controller.authenticate(methodId, handlers);
4147
+ return requireMember(this.controller, "authenticate", "authentication")(methodId, handlers);
4499
4148
  }
4500
4149
 
4501
4150
  // --- sessions (merged catalog + live) ----------------------------------------
@@ -4510,13 +4159,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
4510
4159
  * their owners.
4511
4160
  */
4512
4161
  async listSessions(): Promise<MergedSession[]> {
4513
- let agentEntries: SessionListEntry[] = [];
4514
- if (
4515
- !this.controller.isDegraded &&
4516
- this.controller.capabilities.agent.sessionCapabilities.list
4517
- ) {
4518
- agentEntries = (await this.controller.listSessions()).sessions;
4519
- }
4162
+ const agentEntries = await listAgentSessions(this.controller);
4520
4163
  if (this.sessions) return this.sessions.listMerged(agentEntries, this.adapterId);
4521
4164
  return agentEntries.map((e) => ({
4522
4165
  agentSessionId: e.sessionId,
@@ -4706,15 +4349,26 @@ export class AgentConversation implements AgentClient, Bridgeable {
4706
4349
  agentSessionId: this.agentSessionId,
4707
4350
  event: Object.freeze(event),
4708
4351
  });
4709
- for (const listener of [...this.listeners]) {
4710
- try {
4711
- listener(notification);
4712
- } catch (err) {
4713
- this.log.warn("agent_session_listener_failed", {
4714
- kind: event.kind,
4715
- error: String(err),
4716
- });
4717
- }
4352
+ this.listeners.emit(notification);
4353
+ this.observeMessageStatus(event);
4354
+ }
4355
+
4356
+ /**
4357
+ * Advances message statuses from the events the session already emits. Native conversations
4358
+ * (backend-supervised) report real milestones; ACP ones are approximated: sent means taken and
4359
+ * delivered, the provider's first output means seen.
4360
+ */
4361
+ private observeMessageStatus(event: AgentSessionEvent): void {
4362
+ const native = this.controller?.conversationCapabilities?.supervision === "backend";
4363
+ if (event.kind === "turn_started") {
4364
+ const ids = event.cause.messageIds ?? [];
4365
+ this.messageStatus.link(event.turnId, ids);
4366
+ for (const id of ids) this.messageStatus.advance(id, native ? "taken" : "delivered");
4367
+ } else if (event.kind === "items_receipt") {
4368
+ this.messageStatus.link(event.turnId, event.itemIds);
4369
+ for (const id of event.itemIds) this.messageStatus.advance(id, event.milestone);
4370
+ } else if (event.kind === "operation_stage_changed" && !native && event.activity.lastOutputAt !== null) {
4371
+ for (const id of this.messageStatus.idsOfTurn(event.activity.operationId)) this.messageStatus.advance(id, "seen");
4718
4372
  }
4719
4373
  }
4720
4374
  }
@@ -4731,94 +4385,6 @@ export type AgentConversationOpenResult = AgentSessionOpenResult;
4731
4385
  export type ManagedAgentConversationCreationBootstrap = ManagedAgentSessionCreationBootstrap;
4732
4386
  export type ManagedAgentConversationPersistenceSnapshot = ManagedAgentSessionPersistenceSnapshot;
4733
4387
 
4734
- function persistenceOperationKind(kind: MeteredOperationKind): OperationKind {
4735
- if (kind === "internal_command") return "internal_session_command";
4736
- if (
4737
- kind === "conversation_checkpoint"
4738
- || kind === "conversation_recovery"
4739
- || kind === "identity_update"
4740
- ) return "other";
4741
- return kind;
4742
- }
4743
-
4744
- function ownHandoffOptions(options: HandoffOptions): HandoffOptions {
4745
- return Object.freeze({
4746
- ...(options.summary === undefined ? {} : { summary: options.summary }),
4747
- ...(options.target === undefined
4748
- ? {}
4749
- : {
4750
- target: Object.freeze({
4751
- adapterId: options.target.adapterId,
4752
- ...(options.target.mode === undefined ? {} : { mode: options.target.mode }),
4753
- ...(options.target.adapter === undefined
4754
- ? {}
4755
- : {
4756
- adapter: Object.freeze({
4757
- ...(options.target.adapter.cancelGraceMs === undefined
4758
- ? {}
4759
- : { cancelGraceMs: options.target.adapter.cancelGraceMs }),
4760
- ...options.target.adapter,
4761
- command: Object.freeze([...options.target.adapter.command]) as unknown as string[],
4762
- ...(options.target.adapter.ptyCommand
4763
- ? {
4764
- ptyCommand: Object.freeze([
4765
- ...options.target.adapter.ptyCommand,
4766
- ]) as unknown as string[],
4767
- }
4768
- : {}),
4769
- }),
4770
- }),
4771
- ...(options.target.config === undefined
4772
- ? {}
4773
- : { config: Object.freeze({ ...options.target.config }) }),
4774
- }),
4775
- }),
4776
- ...(options.continuation === undefined
4777
- ? {}
4778
- : { continuation: Object.freeze({ ...options.continuation }) }),
4779
- ...(options.targetPrompt === undefined ? {} : { targetPrompt: options.targetPrompt }),
4780
- });
4781
- }
4782
-
4783
- function normalizeHandoffContinuation(options: HandoffOptions):
4784
- | { readonly kind: "generated"; readonly summaryPrompt: string }
4785
- | { readonly kind: "provided"; readonly content: string }
4786
- | { readonly kind: "none" } {
4787
- if (options.summary !== undefined && options.continuation !== undefined) {
4788
- throw new Error("handoff cannot combine deprecated summary with continuation");
4789
- }
4790
- if (options.target && !options.target.adapterId.trim()) {
4791
- throw new Error("handoff target adapter id cannot be blank");
4792
- }
4793
- if (options.targetPrompt !== undefined && !options.targetPrompt.trim()) {
4794
- throw new Error("handoff target prompt cannot be blank");
4795
- }
4796
- if (options.summary !== undefined) {
4797
- if (!options.summary.trim()) throw new Error("handoff summary cannot be blank");
4798
- return Object.freeze({ kind: "provided", content: options.summary });
4799
- }
4800
- const continuation = options.continuation ?? { kind: "generated" as const };
4801
- if (continuation.kind === "provided") {
4802
- if (!continuation.content.trim()) throw new Error("handoff continuation cannot be blank");
4803
- return Object.freeze({ kind: "provided", content: continuation.content });
4804
- }
4805
- if (continuation.kind === "none") return Object.freeze({ kind: "none" });
4806
- if (continuation.summaryPrompt !== undefined && continuation.summaryInstructions !== undefined) {
4807
- throw new Error("handoff generated continuation cannot combine summaryPrompt and summaryInstructions");
4808
- }
4809
- if (continuation.summaryPrompt !== undefined && !continuation.summaryPrompt.trim()) {
4810
- throw new Error("handoff summary prompt cannot be blank");
4811
- }
4812
- if (continuation.summaryInstructions !== undefined && !continuation.summaryInstructions.trim()) {
4813
- throw new Error("handoff summary instructions cannot be blank");
4814
- }
4815
- const base = continuation.summaryPrompt ?? HANDOFF_SUMMARY_PROMPT;
4816
- const summaryPrompt = continuation.summaryInstructions === undefined
4817
- ? base
4818
- : `${base}\n\nAdditional summary instructions:\n${continuation.summaryInstructions}`;
4819
- return Object.freeze({ kind: "generated", summaryPrompt });
4820
- }
4821
-
4822
4388
  function configurationTargetIssue(
4823
4389
  option: ConfigOption | undefined,
4824
4390
  target: PersistedSessionConfigSelection,
@@ -4929,6 +4495,8 @@ function runtimeRecordFromActivity(
4929
4495
  case "plan":
4930
4496
  case "plan_update":
4931
4497
  case "plan_removed":
4498
+ // A provider's warning, retry or failure: kept so a consumer can show it apart from messages.
4499
+ case "provider_notice":
4932
4500
  return {
4933
4501
  recordId,
4934
4502
  agentSessionId,
@@ -4957,66 +4525,3 @@ function runtimeRecordFromActivity(
4957
4525
  return null;
4958
4526
  }
4959
4527
  }
4960
-
4961
- function protocolMethod(message: PersistenceJsonValue): string | undefined {
4962
- if (message === null || Array.isArray(message) || typeof message !== "object") return undefined;
4963
- const method = (message as { readonly method?: unknown }).method;
4964
- return typeof method === "string" ? method : undefined;
4965
- }
4966
-
4967
- function toPersistenceJsonValue(value: unknown): PersistenceJsonValue {
4968
- if (value === undefined) return null;
4969
- const serialized = JSON.stringify(value);
4970
- return serialized === undefined ? String(value) : JSON.parse(serialized) as PersistenceJsonValue;
4971
- }
4972
-
4973
- function defaultPermissionOutcome(
4974
- request: PermissionRequest,
4975
- policy: "approve" | "cancel",
4976
- ): PermissionOutcome {
4977
- if (policy === "cancel") return { outcome: "cancelled" };
4978
- const allow = request.options.find((option) => option.kind === "allow_once")
4979
- ?? request.options.find((option) => option.kind === "allow_always");
4980
- return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
4981
- }
4982
-
4983
- function permissionRecordOutcome(
4984
- request: PermissionRequest,
4985
- outcome: PermissionOutcome,
4986
- ): "approved" | "denied" | "cancelled" {
4987
- if (outcome.outcome === "cancelled") return "cancelled";
4988
- const selected = request.options.find((option) => option.optionId === outcome.optionId);
4989
- return selected?.kind === "allow_once" || selected?.kind === "allow_always"
4990
- ? "approved"
4991
- : "denied";
4992
- }
4993
-
4994
- /** Do not let one notification observer mutate the PromptResult another observer sees. */
4995
- function copyPromptResult(result: PromptResult): PromptResult {
4996
- const messages = result.messages ?? (result.text ? [{ text: result.text }] : []);
4997
- return Object.freeze({
4998
- ...result,
4999
- messages: Object.freeze(
5000
- messages.map((message) => Object.freeze({ ...message })),
5001
- ),
5002
- usage: result.usage ? Object.freeze({ ...result.usage }) : null,
5003
- });
5004
- }
5005
-
5006
- /** Settle our wrapper too, so cancelled permission decisions are durably recorded. */
5007
- async function permissionWithAbort(
5008
- handler: () => PermissionOutcome | Promise<PermissionOutcome>,
5009
- signal?: AbortSignal,
5010
- ): Promise<PermissionOutcome> {
5011
- if (signal?.aborted) return { outcome: "cancelled" };
5012
- let abort!: () => void;
5013
- const cancelled = new Promise<PermissionOutcome>((resolve) => {
5014
- abort = () => resolve({ outcome: "cancelled" });
5015
- signal?.addEventListener("abort", abort, { once: true });
5016
- });
5017
- try {
5018
- return await Promise.race([Promise.resolve().then(handler), cancelled]);
5019
- } finally {
5020
- signal?.removeEventListener("abort", abort);
5021
- }
5022
- }