@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
@@ -0,0 +1,218 @@
1
+ import { useFormat3Schema } from "./fixtures/format3-schema.ts";
2
+ import { expect, test, spyOn } from "bun:test";
3
+ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { createHash } from "node:crypto";
7
+ import { createInProcessHarness } from "../src/testing.ts";
8
+ import { validateManagedConfig } from "../src/runtime/config/managed.ts";
9
+ import { ask } from "./helpers/session.ts";
10
+ import { createSqliteStorageAdapter } from "../src/state/storage/sqlite.ts";
11
+ import { openDevelopment } from "../src/interfaces/cli/development.ts";
12
+ import { decodeSessionFile } from "../src/state/storage/session-file.ts";
13
+ import { openRouter } from "../src/capabilities/model/openrouter.ts";
14
+ import type { Model } from "../src/contracts/loop.ts";
15
+
16
+ const secret = "test-custom-credential-8d3b", different = "test-default-credential-126c";
17
+ const environment = { CONFIG_TEST_CUSTOM_KEY: secret, OPENROUTER_API_KEY: different, OPENROUTER_MODEL: "environment/model" };
18
+ const config = validateManagedConfig({ version: 1, system: "provider system", model: { protocol: "openrouter", model: "saved/model", apiKeyEnv: "CONFIG_TEST_CUSTOM_KEY" },
19
+ defaultPolicy: "main", policies: { main: { fallback: "allow", tools: {} }, unused: { fallback: "ask", tools: {} } } });
20
+ const fake = (calls: { key: string; model: string }[]) => (key: string, model: string): Model => {
21
+ calls.push({ key, model }); return async () => ({ role: "assistant", content: "offline response", calls: [] });
22
+ };
23
+ const until = async (check: () => boolean | Promise<boolean>) => { for (let i = 0; i < 400; i++) { if (await check()) return; await new Promise(r => setTimeout(r, 5)); } throw new Error("timed out"); };
24
+ const push = (id: string) => ({ channel: "a", item: { id, kind: "user_message" as const, sender: "u", content: [{ type: "text" as const, text: "hello" }] } });
25
+
26
+ test("OpenRouter config validates references and never accepts key values", () => {
27
+ expect(validateManagedConfig({ ...config, model: { protocol: "openrouter" } }).model).toEqual({ protocol: "openrouter", model: "deepseek/deepseek-v4.1-flash", apiKeyEnv: "OPENROUTER_API_KEY" });
28
+ expect(() => validateManagedConfig({ ...config, model: { ...config.model, apiKey: secret } })).toThrow("config.model.apiKey");
29
+ expect(() => validateManagedConfig({ ...config, model: { ...config.model, apiKeyEnv: "bad-name" } })).toThrow("config.model.apiKeyEnv");
30
+ });
31
+
32
+ test("offline OpenRouter dispatch does not log the credential", async () => {
33
+ const log = spyOn(console, "log").mockImplementation(() => {}), error = spyOn(console, "error").mockImplementation(() => {});
34
+ const calls: { key: string; model: string }[] = [];
35
+ const harness = createInProcessHarness({ environment, providerFactory: fake(calls) });
36
+ try {
37
+ await harness.client.initialize(); await harness.client.createSession({ sessionId: "s", config, participants: [], channels: {} });
38
+ await harness.client.push(push("m")); await until(() => calls.length === 1); await until(async () => (await harness.client.idle()).idle);
39
+ expect(JSON.stringify([log.mock.calls, error.mock.calls])).not.toContain(secret);
40
+ } finally { harness.close(); log.mockRestore(); error.mockRestore(); }
41
+ });
42
+
43
+ test("provider error text cannot leak an echoed credential", async () => {
44
+ const fetchSpy = spyOn(globalThis, "fetch").mockImplementation((async () => new Response(`echo ${secret}`, { status: 401 })) as unknown as typeof fetch);
45
+ try {
46
+ const result = await openRouter(secret, "saved/model")([], []).catch(error => String(error));
47
+ expect(result).toContain("[REDACTED]"); expect(result).not.toContain(secret);
48
+ fetchSpy.mockImplementation((async () => { throw new Error(`transport echoed ${secret}`); }) as unknown as typeof fetch);
49
+ const transport = await openRouter(secret, "saved/model")([], []).catch(error => String(error));
50
+ expect(transport).toContain("[REDACTED]"); expect(transport).not.toContain(secret);
51
+ } finally { fetchSpy.mockRestore(); }
52
+ });
53
+
54
+ test("offline OpenRouter export and fresh-home reopen uses named secret without storing it", async () => {
55
+ const source = mkdtempSync(join(tmpdir(), "provider-source-")), dest = mkdtempSync(join(tmpdir(), "provider-dest-"));
56
+ const calls: { key: string; model: string }[] = [], wire: unknown[] = [];
57
+ const first = createInProcessHarness({ home: source, environment, providerFactory: fake(calls) });
58
+ let bytes: Uint8Array;
59
+ try {
60
+ wire.push(await first.client.initialize()); wire.push(await first.client.createSession({ sessionId: "s", config, participants: [], channels: {} }));
61
+ first.client.onChannelEvent(event => wire.push(event));
62
+ wire.push(await first.client.push(push("a1"))); await until(async () => (await first.client.idle()).idle);
63
+ expect(calls).toEqual([{ key: secret, model: "saved/model" }]);
64
+ bytes = await first.client.exportArchive();
65
+ expect((decodeSessionFile(bytes, 268435456) as any).config).toEqual(config);
66
+ expect(Buffer.from(bytes).includes(secret)).toBe(false);
67
+ } finally { first.close(); }
68
+ expect(readFileSync(join(source, "s", "session.sqlite")).includes(secret)).toBe(false);
69
+ const second = createInProcessHarness({ home: dest, environment, providerFactory: fake(calls) });
70
+ try {
71
+ wire.push(await second.client.initialize()); wire.push(await second.client.importArchive(bytes));
72
+ const loaded = await second.client.openSession({ sessionId: "s" }); wire.push(loaded);
73
+ second.client.onChannelEvent(event => wire.push(event));
74
+ wire.push(await second.client.push(push("a2"))); await until(() => calls.length === 2); await until(async () => (await second.client.idle()).idle);
75
+ expect(calls).toEqual([{ key: secret, model: "saved/model" }, { key: secret, model: "saved/model" }]);
76
+ expect(JSON.stringify(wire)).not.toContain(secret);
77
+ } finally { second.close(); }
78
+ const database = join(dest, "s", "session.sqlite");
79
+ expect(readFileSync(database).includes(secret)).toBe(false);
80
+ const before = readFileSync(database);
81
+ const missing = createInProcessHarness({ home: dest, environment: { OPENROUTER_API_KEY: different }, providerFactory: fake(calls) });
82
+ try { await missing.client.initialize(); await expect(missing.client.openSession({ sessionId: "s" })).rejects.toMatchObject({ code: "invalid_config", message: expect.stringContaining("CONFIG_TEST_CUSTOM_KEY") }); }
83
+ finally { missing.close(); }
84
+ expect(readFileSync(database).equals(before)).toBe(true);
85
+ const empty = createInProcessHarness({ home: dest, environment: { CONFIG_TEST_CUSTOM_KEY: "" }, providerFactory: fake(calls) });
86
+ try { await empty.client.initialize(); await expect(empty.client.openSession({ sessionId: "s" })).rejects.toMatchObject({ code: "invalid_config" }); }
87
+ finally { empty.close(); }
88
+ expect(readFileSync(database).equals(before)).toBe(true);
89
+ rmSync(source, { recursive: true, force: true }); rmSync(dest, { recursive: true, force: true });
90
+ }, 20000);
91
+
92
+ test("OpenRouter checkpoint key binds model and contributing policy but not credential reference", async () => {
93
+ const directory = mkdtempSync(join(tmpdir(), "provider-checkpoint-")), path = join(directory, "session.sqlite");
94
+ const key = createHash("sha256").update(JSON.stringify([config.system, "saved/model", ["current_time", "notify_channel"]])).digest("hex");
95
+ const adapter = createSqliteStorageAdapter(path), identity = { sessionId: "development", compatibilityKey: key };
96
+ const r = adapter.open({ mode: "create", identity, config }); if (!r.ok) throw new Error(r.error.message); const store = r.value;
97
+ const must = <T>(v: { ok: true; value: T } | { ok: false; error: { message: string } }) => { if (!v.ok) throw new Error(v.error.message); return v.value; };
98
+ must(store.acceptItem({ kind: "participant_message", channelId: "a", senderId: "u", text: "hi", itemId: "m" }));
99
+ const turn = must(store.beginTurn("a"))!.turn; must(store.beginChannelSuspend("a")); must(store.checkpointTurn(turn.turnId)); must(store.saveConfig(config)); store.close();
100
+ const systemMismatch = await openDevelopment({ systemPrompt: "ignored", instructions: "changed system",
101
+ database: path, managedConfig: config, environment, providerFactory: fake([]) });
102
+ const unchanged = systemMismatch.session.snapshot();
103
+ expect(systemMismatch.session.channels.resume("a")).toMatchObject({ ok: false, error: { code: "incompatible" } });
104
+ expect(systemMismatch.session.snapshot()).toEqual(unchanged); systemMismatch.close();
105
+ const changedModel = validateManagedConfig({ ...config, model: { protocol: "openrouter", model: "changed/model", apiKeyEnv: "CONFIG_TEST_CUSTOM_KEY" } });
106
+ const different = await openDevelopment({ systemPrompt: "ignored", database: path, managedConfig: changedModel, environment, providerFactory: fake([]) });
107
+ const before = different.session.snapshot();
108
+ expect(different.session.channels.resume("a")).toMatchObject({ ok: false, error: { code: "incompatible" } });
109
+ expect(different.session.snapshot()).toEqual(before); different.close();
110
+ const refChanged = validateManagedConfig({ ...config, model: { protocol: "openrouter", model: "saved/model", apiKeyEnv: "ANOTHER_TEST_KEY" },
111
+ policies: { ...config.policies, unused: { fallback: "deny", tools: {} } } });
112
+ const calls: { key: string; model: string }[] = [];
113
+ const same = await openDevelopment({ systemPrompt: "ignored", database: path, managedConfig: refChanged, environment: { ANOTHER_TEST_KEY: "new-key" }, providerFactory: fake(calls) });
114
+ expect(same.session.channels.resume("a")).toMatchObject({ ok: true });
115
+ await until(() => same.session.status().channels[0]?.activeTurn === undefined); same.close();
116
+ rmSync(directory, { recursive: true, force: true });
117
+ });
118
+
119
+ test("saved provider model beats environment and sidecar wins over inline", async () => {
120
+ const directory = mkdtempSync(join(tmpdir(), "provider-sidecar-")), path = join(directory, "session.sqlite"), calls: { key: string; model: string }[] = [];
121
+ const make = (model: string) => validateManagedConfig({ ...config, model: { protocol: "openrouter", model, apiKeyEnv: "CONFIG_TEST_CUSTOM_KEY" } });
122
+ const first = await openDevelopment({ systemPrompt: "unused", database: path, create: true, managedConfig: config, environment, providerFactory: fake(calls) });
123
+ first.close();
124
+ const saved = await openDevelopment({ systemPrompt: "unused", database: path, environment, providerFactory: fake(calls) });
125
+ saved.session.start(); saved.session.agent.send({ channelId: "a", participantId: "u", text: "hi", itemId: "1" });
126
+ await until(() => saved.session.agent.idle()); saved.close();
127
+ writeFileSync(join(directory, "config.json"), JSON.stringify(make("sidecar/model")));
128
+ const sidecar = await openDevelopment({ systemPrompt: "unused", database: path, managedConfig: config, environment, providerFactory: fake(calls) });
129
+ sidecar.session.start(); sidecar.session.agent.send({ channelId: "a", participantId: "u", text: "hello", itemId: "2" });
130
+ await until(() => sidecar.session.agent.idle()); sidecar.close();
131
+ expect(calls).toEqual([{ key: secret, model: "saved/model" }, { key: secret, model: "sidecar/model" }]);
132
+ expect(readdirSync(directory)).toEqual(expect.arrayContaining(["config.json", "session.sqlite"]));
133
+ rmSync(directory, { recursive: true, force: true });
134
+ });
135
+
136
+ test("legacy OpenRouter checkpoint resumes with its original compatibility key", async () => {
137
+ const { Database } = await import("bun:sqlite"), { legacyItemSignature } = await import("../src/state/storage/policy-metadata.ts");
138
+ const directory = mkdtempSync(join(tmpdir(), "provider-legacy-")), path = join(directory, "session.sqlite");
139
+ const legacyConfig = validateManagedConfig({ ...config, defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow", tools: {} } } });
140
+ const identity = { sessionId: "development", compatibilityKey: createHash("sha256").update(JSON.stringify([config.system, "saved/model", ["current_time", "notify_channel"]])).digest("hex") };
141
+ const adapter = createSqliteStorageAdapter(path), opened = adapter.open({ mode: "create", identity, config: legacyConfig });
142
+ if (!opened.ok) throw new Error(opened.error.message);
143
+ const input = { kind: "participant_message" as const, channelId: "a", senderId: "u", text: "hello", itemId: "m" };
144
+ const accepted = opened.value.acceptItem(input); if (!accepted.ok) throw new Error(accepted.error.message);
145
+ const begun = opened.value.beginTurn("a"); if (!begun.ok || !begun.value) throw new Error("begin failed");
146
+ if (!opened.value.beginChannelSuspend("a").ok || !opened.value.checkpointTurn(begun.value.turn.turnId).ok) throw new Error("checkpoint failed");
147
+ opened.value.close();
148
+ const db = new Database(path); db.query("UPDATE items SET signature = ?").run(legacyItemSignature(input));
149
+ const raw = db.query<{ state: string }, []>("SELECT state FROM turns").get()!; const state = JSON.parse(raw.state); delete state.checkpoint.policyFingerprint;
150
+ db.query("UPDATE turns SET state = ?").run(JSON.stringify(state));
151
+ useFormat3Schema(db); db.close();
152
+ expect(adapter.readSavedConfig()).toMatchObject({ ok: true });
153
+ const calls: { key: string; model: string }[] = [];
154
+ const legacy = await openDevelopment({ systemPrompt: config.system, database: path, provider: { apiKey: secret, model: "saved/model" }, environment: {}, providerFactory: fake(calls) });
155
+ expect(legacy.session.channels.resume("a")).toMatchObject({ ok: true });
156
+ await until(() => legacy.session.status().channels[0]?.activeTurn === undefined); legacy.close(); await new Promise(resolve => setTimeout(resolve, 30));
157
+ expect(adapter.readSavedConfig()).toMatchObject({ ok: true });
158
+ const reopened = await expect(openDevelopment({ systemPrompt: config.system, database: path, provider: { apiKey: secret, model: "saved/model" }, environment: {}, providerFactory: fake(calls) })).rejects.toThrow("OPENROUTER_API_KEY");
159
+ expect(reopened).toBeUndefined();
160
+ rmSync(directory, { recursive: true, force: true });
161
+ });
162
+
163
+
164
+ test("development instruction overrides replace saved and sidecar text without offering the demo tool", async () => {
165
+ const directory = mkdtempSync(join(tmpdir(), "provider-instructions-")), database = join(directory, "session.sqlite");
166
+ const fallback = { systemPrompt: "bundled instructions", database, environment };
167
+ const seen: Array<{ prompt: string; tools: string[] }> = [];
168
+ const providerFactory = (): Model => async (messages, tools) => {
169
+ seen.push({ prompt: messages[0]!.content!, tools: tools.map(tool => tool.name) });
170
+ return { role: "assistant", content: "offline reply", calls: [] };
171
+ };
172
+ try {
173
+ const created = await openDevelopment({ ...fallback, create: true, managedConfig: config, providerFactory });
174
+ created.close();
175
+ const sidecar = join(directory, "config.json");
176
+ writeFileSync(sidecar, JSON.stringify({ ...config, system: "sidecar instructions" }));
177
+ const instructions = "Custom instructions. \n";
178
+ const edited = await openDevelopment({ ...fallback, instructions, providerFactory });
179
+ try {
180
+ edited.session.start();
181
+ await ask(edited.session, { channelId: "channel", participantId: "alice", text: "Hello" });
182
+ } finally { edited.close(); }
183
+ expect(seen[0]!.prompt.startsWith(instructions + "\n\n")).toBe(true);
184
+ expect(seen[0]!.tools).toEqual(["current_time", "notify_channel", "schedule_reminder", "list_reminders", "cancel_reminder"]);
185
+ expect(readFileSync(sidecar, "utf8")).toContain("sidecar instructions");
186
+ rmSync(sidecar);
187
+ const reopened = await openDevelopment({ ...fallback, providerFactory });
188
+ try {
189
+ reopened.session.start();
190
+ await ask(reopened.session, { channelId: "channel", participantId: "alice", text: "Continue" });
191
+ } finally { reopened.close(); }
192
+ expect(seen[1]).toEqual(seen[0]);
193
+ } finally { rmSync(directory, { recursive: true, force: true }); }
194
+ });
195
+
196
+ test("debug mode sends the same composed system message shown in Live Context", async () => {
197
+ const { loadInstructions } = await import("../src/capabilities/context/load-instructions.ts");
198
+ const debugInstructions = loadInstructions("agent-demo");
199
+ let sent: unknown;
200
+ const fetchSpy = spyOn(globalThis, "fetch").mockImplementation((async (_url, init) => {
201
+ sent = JSON.parse(init!.body as string).messages[0];
202
+ return new Response("Offline test stops after request capture", { status: 400 });
203
+ }) as typeof fetch);
204
+ try {
205
+ const development = await openDevelopment({
206
+ systemPrompt: "usual instructions", debugInstructions, debugTools: true,
207
+ provider: { apiKey: "unused-test-key", model: "offline/test" },
208
+ });
209
+ try {
210
+ development.session.start();
211
+ await expect(ask(development.session, { channelId: "a", participantId: "alice", text: "hello" })).rejects.toThrow();
212
+ const preview = development.inspection.liveContext().base[0];
213
+ expect(preview?.content).toContain(debugInstructions.trimEnd());
214
+ expect(preview?.content).toContain(loadInstructions("harness").trimEnd());
215
+ expect(sent).toEqual(preview);
216
+ } finally { development.close(); }
217
+ } finally { fetchSpy.mockRestore(); }
218
+ });
@@ -0,0 +1,132 @@
1
+ import { modelScenario } from "./helpers/scenario.ts";
2
+ import { expect, test } from "bun:test";
3
+ import { createInProcessHarness } from "../src/testing.ts";
4
+ import { spawnHarness } from "./helpers/stdio.ts";
5
+ import type { ChannelEvent } from "../src/contracts/events.ts";
6
+
7
+ for (const transport of ["in-process", "stdio"] as const) {
8
+ test(`${transport}: observe pending approval and page the same live message positions`, async () => {
9
+ const harness = transport === "stdio" ? spawnHarness() : createInProcessHarness();
10
+ const { client } = harness;
11
+ const events: ChannelEvent["event"][] = [];
12
+ client.onChannelEvent(({ event }) => events.push(event));
13
+ async function event<T extends ChannelEvent["event"]["type"]>(type: T) {
14
+ for (let i = 0; i < 300; i++) {
15
+ const found = events.find(event => event.type === type);
16
+ if (found) return found as Extract<ChannelEvent["event"], { type: T }>;
17
+ await new Promise(resolve => setTimeout(resolve, 10));
18
+ }
19
+ throw new Error(`Missing event ${type}`);
20
+ }
21
+ try {
22
+ const init = await client.initialize({ protocolVersion: 1, host: { name: "test", version: "0" }, callbacks: [], approval: true,
23
+ subscription: { text: "final", tools: "full" } });
24
+ expect(init.description.capabilities.methods).not.toContain("session/load");
25
+ expect(init.description.capabilities.methods).not.toContain("session/messages");
26
+ const ready = await client.createSession({ sessionId: "s", participants: [], channels: {}, config: {
27
+ version: 1, system: "test", model: { protocol: "scripted", script: new URL("./fixtures/echo-scenario.jsonl", import.meta.url).pathname },
28
+ defaultPolicy: "ask", policies: { ask: { fallback: "ask", tools: {} } },
29
+ } });
30
+ expect(ready).toMatchObject({ sessionId: "s", lifecycle: "running", revision: expect.any(Number) });
31
+ await client.push({ channel: "a", item: { id: "item", kind: "user_message", sender: "alice", content: [{ type: "text", text: "original" }] } });
32
+ const approval = await event("approval_requested");
33
+ const view = await client.request("channel/observe", { channel: "a" });
34
+ expect(view).toMatchObject({ sessionLifecycle: "running", channel: { pendingCount: 0, waitingForResume: false },
35
+ approvals: [{ requestId: approval.requestId }] });
36
+ await client.respondApproval(approval.requestId, "allow_once");
37
+ expect(await event("approval_closed")).toMatchObject({ requestId: approval.requestId, reason: "dispatched" });
38
+ await event("turn_ended");
39
+ const take = events.find(event => event.type === "turn_started");
40
+ const completion = await event("message_completed");
41
+ if (take?.type !== "turn_started") throw new Error("Missing take");
42
+ const page = await client.request("channel/messages", { channel: "a" });
43
+ expect(page.messages[0]).toMatchObject({ ...take.messages?.[0], itemId: "item", parts: [{ text: "original" }] });
44
+ expect(take.messages?.[0]?.position).toBe(page.messages[0]?.position as string);
45
+ expect(completion.position).toBe(page.messages.find(message => message.messageId === completion.messageId)?.position);
46
+ await expect(client.request("channel/messages", { channel: "b", after: page.messages[0]!.position, throughRevision: view.revision }))
47
+ .rejects.toMatchObject({ code: "invalid_params" });
48
+ const tracked = await client.request("channel/reconcile", { channel: "a", itemIds: ["item", "unknown"], turnIds: [approval.turnId] });
49
+ expect(tracked).toMatchObject({ unknownItemIds: ["unknown"], turns: [{ turnId: approval.turnId, state: "completed" }] });
50
+ expect(tracked.replies.map(reply => reply.messageId)).toContain(completion.messageId!);
51
+ expect((await client.request("channel/observe", { channel: "a" })).approvals).toEqual([]);
52
+ } finally { await harness.close(); }
53
+ });
54
+ }
55
+
56
+ test("focused startup and observation do not request a full storage snapshot", async () => {
57
+ const { createMemoryStorageAdapter } = await import("../src/state/storage/memory.ts");
58
+ const { createSession } = await import("../src/index.ts");
59
+ const { createProtocolServer } = await import("../src/interfaces/protocol/server.ts");
60
+ const { HarnessClient, createInProcessTransport } = await import("../src/client.ts");
61
+ const storage = createMemoryStorageAdapter().open({ mode: "create", identity: { sessionId: "s", compatibilityKey: "" } });
62
+ if (!storage.ok) throw new Error(storage.error.message);
63
+ const owner = storage.value;
64
+ const accepted = owner.acceptItem({ kind: "participant_message", channelId: "a", senderId: "u", itemId: "i", text: "test" });
65
+ if (!accepted.ok) throw new Error(accepted.error.message);
66
+ const turn = owner.beginTurn("a");
67
+ if (!turn.ok || !turn.value) throw new Error("Failed to seed turn");
68
+ const turnId = turn.value.turn.turnId;
69
+ const reply = owner.appendMessage(turnId, { role: "assistant", content: "old reply", calls: [] });
70
+ const oversized = owner.appendMessage(turnId, { role: "assistant", content: "x".repeat(1024 * 1024 + 1), calls: [] });
71
+ if (!oversized.ok) throw new Error(oversized.error.message);
72
+ if (!reply.ok || !owner.finishTurn(turnId, { status: "completed" }).ok) throw new Error("Failed to seed reply");
73
+ let snapshots = 0;
74
+ owner.snapshot = () => { snapshots++; throw new Error("Unexpected full storage read"); };
75
+ const server = createProtocolServer(async () => ({
76
+ session: createSession({ systemPrompt: "test", storage: owner, configureTurn() { throw new Error("Unexpected inference"); } }),
77
+ close() { owner.close(); },
78
+ }), { durable: true });
79
+ const client = new HarnessClient(createInProcessTransport(server));
80
+ try {
81
+ await client.initialize();
82
+ expect(await client.openSession({ sessionId: "s", channelChanges: [{ channel: "a", changeId: "1", displayName: "Alice" }] }))
83
+ .toMatchObject({ sessionId: "s", channelChanges: [{ outcome: "applied" }] });
84
+ expect(await client.observeChannel({ channel: "a" })).toMatchObject({ channel: { displayName: "Alice", pendingCount: 0 } });
85
+ expect(await client.reconcileChannel({ channel: "a", turnIds: [String(turnId)], itemIds: ["i"] }))
86
+ .toMatchObject({ turns: [{ state: "completed" }], items: [{ id: "i" }], replies: [{ messageId: String(reply.value.seq) }, { messageId: String(oversized.value.seq) }] });
87
+ const newest = await client.timeline({ limit: 1 });
88
+ expect(newest.events).toMatchObject([{ omitted: true, messageId: String(oversized.value.seq) }]);
89
+ const older = await client.timeline({ cursor: newest.next!, limit: 1 });
90
+ expect(older.events).toMatchObject([{ messageId: String(reply.value.seq) }]);
91
+ const latest = await client.channelMessages({ channel: "a", limit: 1 });
92
+ expect(latest.messages).toMatchObject([{ reference: true, messageId: String(oversized.value.seq) }]);
93
+ const foreignPosition = Buffer.from(JSON.stringify(["other-session", "a", reply.value.seq])).toString("base64url");
94
+ await expect(client.channelMessages({ channel: "a", after: foreignPosition, throughRevision: oversized.revision }))
95
+ .rejects.toMatchObject({ code: "invalid_params" });
96
+ expect(snapshots).toBe(0);
97
+ } finally { client.close(); server.dispose(); }
98
+ });
99
+
100
+ for (const denied of [false, true]) test(denied ? "stdio policy deny prevents notify_channel dispatch" : "stdio offers notify_channel by default and a notice wakes an unattached channel", async () => {
101
+ const { mkdtempSync, rmSync, writeFileSync } = await import("node:fs");
102
+ const { tmpdir } = await import("node:os");
103
+ const { join } = await import("node:path");
104
+ const directory = mkdtempSync(join(tmpdir(), "operator-notice-"));
105
+ const script = join(directory, "script.jsonl");
106
+ writeFileSync(script, modelScenario([
107
+ { content: null, calls: [{ id: "notice", name: "notify_channel", arguments: { channelId: "bob", text: "wake" } }] },
108
+ { content: "done" },
109
+ ]));
110
+ const harness = spawnHarness();
111
+ const events: ChannelEvent[] = [];
112
+ harness.client.onChannelEvent(event => events.push(event));
113
+ try {
114
+ await harness.client.initialize();
115
+ await harness.client.createSession({ sessionId: "notice", participants: [], channels: {}, config: {
116
+ version: 1, system: "test", model: { protocol: "scripted", script }, defaultPolicy: denied ? "receiver" : "allow",
117
+ policies: { allow: { fallback: "allow", tools: {} }, receiver: { fallback: "allow", tools: { notify_channel: "deny" } } },
118
+ }, channelChanges: [{ channel: "bob", changeId: "1", policy: "receiver" }] });
119
+ await harness.client.push({ channel: "alice", item: { id: "wake", kind: "user_message", sender: "alice", content: [{ type: "text", text: "notify Bob" }] } });
120
+ const target = denied ? "alice" : "bob";
121
+ for (let i = 0; i < 300 && !events.some(event => event.channel === target && event.event.type === "turn_ended"); i++)
122
+ await new Promise(resolve => setTimeout(resolve, 10));
123
+ expect(events.some(event => event.channel === target && event.event.type === "turn_ended" && event.event.outcome === "completed")).toBe(true);
124
+ const activity = (await harness.client.timeline()).events;
125
+ if (denied) {
126
+ expect(activity.some(event => event.kind === "channel_notice")).toBe(false);
127
+ expect(events.some(({ event }) => event.type === "tool_call" && event.status === "started")).toBe(false);
128
+ } else expect(activity).toContainEqual(expect.objectContaining({
129
+ kind: "channel_notice", sourceChannel: "alice", channel: "bob", actor: { kind: "agent", id: "alice" },
130
+ }));
131
+ } finally { await harness.close(); rmSync(directory, { recursive: true, force: true }); }
132
+ }, 15000);
@@ -0,0 +1,44 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { createChannelOutputs, publishChannelEvent } from "../src/interfaces/protocol/output.ts";
4
+ import { serveLocal, sendLocal } from "../src/interfaces/protocol/local.ts";
5
+ import { subscribeLocal } from "../src/interfaces/protocol/subscribe.ts";
6
+ import { createSession } from "../src/index.ts";
7
+ import type { ChannelOutput } from "../src/contracts/output.ts";
8
+ import { lastInput } from "./helpers/session.ts";
9
+
10
+ test("channel subscription delivers own and notice-started replies once, isolated by channel", async () => {
11
+ const directory = await mkdtemp("/tmp/harness-output-");
12
+ const socket = `${directory}/agent.sock`;
13
+ const outputs = createChannelOutputs();
14
+ const session = createSession({ systemPrompt: "test", configureTurn: () => ({
15
+ model: async messages => ({ role: "assistant", content: `Answer: ${lastInput(messages)}`, calls: [] }),
16
+ tools: [], executeTool: async () => "unused",
17
+ }) });
18
+ session.subscribe(event => publishChannelEvent(outputs, event));
19
+ session.start();
20
+ const agent = session.agent;
21
+ const server = serveLocal(session, socket, outputs);
22
+ const received: ChannelOutput[] = [];
23
+ let resolve!: () => void;
24
+ let delivery = new Promise<void>(r => { resolve = r; });
25
+ const subscription = await subscribeLocal(socket, "bob", event => { received.push(event); resolve(); });
26
+ try {
27
+ await sendLocal(socket, { channelId: "alice", participantId: "alice", text: "other" });
28
+ expect(received).toHaveLength(0);
29
+ expect(await sendLocal(socket, { channelId: "bob", participantId: "bob", text: "hello" })).toBe("Answer: hello");
30
+ await delivery;
31
+ expect(received.map(e => e.text)).toEqual(["Answer: hello"]);
32
+ delivery = new Promise<void>(r => { resolve = r; });
33
+ expect(agent.notify({ channelId: "bob", fromChannelId: "alice", text: "What is the error?" })).toMatchObject({ accepted: true, milestone: "received" });
34
+ await delivery;
35
+ expect(received.map(e => e.text)).toEqual(["Answer: hello", "Answer: What is the error?"]);
36
+ expect(new Set(received.map(e => e.turnId)).size).toBe(2);
37
+ subscription.close(); await subscription.done;
38
+ expect(await sendLocal(socket, { channelId: "bob", participantId: "bob", text: "after disconnect" })).toBe("Answer: after disconnect");
39
+ } finally {
40
+ subscription.close(); await subscription.done;
41
+ await server.stop(true);
42
+ await rm(directory, { recursive: true, force: true });
43
+ }
44
+ }, 5000);
@@ -0,0 +1,64 @@
1
+ import { expect, test } from "bun:test";
2
+ import { createSession } from "../src/index.ts";
3
+ import { createMemoryStorageAdapter } from "../src/state/storage/memory.ts";
4
+ import type { ManagedConfig } from "../src/contracts/config-permissions.ts";
5
+ import type { SessionStorage } from "../src/contracts/storage.ts";
6
+ import { createSqliteStorageAdapter } from "../src/state/storage/sqlite.ts";
7
+ import { mkdtempSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ const base = (): ManagedConfig => ({ version: 1, system: "owner", model: { protocol: "scripted", script: "fixture" }, defaultPolicy: "__legacy_allow",
12
+ policies: { __legacy_allow: { fallback: "deny", tools: {} } } });
13
+ async function until(check: () => boolean) { for (let i = 0; i < 300; i++) { if (check()) return; await new Promise(r => setTimeout(r, 5)); } throw new Error("timeout"); }
14
+ function services(effects: string[]) { return { tools: [], model: async (messages: readonly { role: string }[]) => messages.at(-1)?.role === "tool"
15
+ ? { role: "assistant" as const, content: "done", calls: [] }
16
+ : { role: "assistant" as const, content: null, calls: [{ id: "c", name: "work", arguments: "{}" }] },
17
+ executeTool: async () => { effects.push("ran"); return "ok"; } }; }
18
+
19
+ for (const kind of ["memory", "sqlite"] as const) test(`${kind}: omitted session config uses an immutable owner snapshot, not legacy allow`, async () => {
20
+ const dir = mkdtempSync(join(tmpdir(), "harness-owner-config-"));
21
+ const adapter = kind === "memory" ? createMemoryStorageAdapter() : createSqliteStorageAdapter(join(dir, "session.sqlite"));
22
+ const supplied = base(), opened = adapter.open({ mode: "create", identity: { sessionId: "s", compatibilityKey: "k" }, config: supplied });
23
+ if (!opened.ok) throw new Error(opened.error.message);
24
+ supplied.policies.__legacy_allow!.fallback = "allow";
25
+ const effects: string[] = [], session = createSession({ systemPrompt: "owner", storage: opened.value, configureTurn: () => services(effects) });
26
+ try {
27
+ const owner = opened.value.ownerConfig(); expect(owner).toMatchObject({ ok: true, value: { policies: { __legacy_allow: { fallback: "deny" } } } });
28
+ if (owner.ok && owner.value) owner.value.policies.__legacy_allow!.fallback = "allow";
29
+ const replacement = base(); replacement.policies.__legacy_allow!.fallback = "allow";
30
+ expect(opened.value.saveConfig(replacement).ok).toBe(true);
31
+ expect(opened.value.ownerConfig()).toMatchObject({ ok: true, value: { policies: { __legacy_allow: { fallback: "deny" } } } });
32
+ session.start(); session.agent.send({ channelId: "a", participantId: "u", text: "hi" });
33
+ await until(() => session.snapshot().turns[0]?.state.status === "completed");
34
+ expect(effects).toEqual([]);
35
+ const result = session.snapshot().timeline.find(entry => entry.message.role === "tool")!.message;
36
+ expect(result.role === "tool" && JSON.parse(result.content).code).toBe("policy_denied");
37
+ } finally { session.stop("done"); opened.value.close(); rmSync(dir, { recursive: true, force: true }); }
38
+ });
39
+
40
+ test("assembly checks config values and prompt, ignores key order, and never treats read failure as absence", () => {
41
+ const config = base(), opened = createMemoryStorageAdapter().open({ mode: "create", identity: { sessionId: "s", compatibilityKey: "k" }, config });
42
+ if (!opened.ok) throw new Error(opened.error.message);
43
+ try {
44
+ const reordered = { policies: { __legacy_allow: { tools: {}, fallback: "deny" as const } }, defaultPolicy: "__legacy_allow", model: { script: "fixture", protocol: "scripted" as const }, system: "owner", version: 1 as const };
45
+ expect(() => createSession({ systemPrompt: "owner", storage: opened.value, config: reordered, configureTurn: () => services([]) })).not.toThrow();
46
+ const wrong = base(); wrong.policies.__legacy_allow!.fallback = "allow";
47
+ expect(() => createSession({ systemPrompt: "owner", storage: opened.value, config: wrong, configureTurn: () => services([]) })).toThrow("does not match");
48
+ expect(() => createSession({ systemPrompt: "other", storage: opened.value, configureTurn: () => services([]) })).toThrow("system prompt");
49
+ const broken = new Proxy(opened.value, { get(target, key) { return key === "ownerConfig" ? () => ({ ok: false, error: { code: "storage_failure", message: "read failed" } }) : Reflect.get(target, key); } }) as SessionStorage;
50
+ expect(() => createSession({ systemPrompt: "owner", storage: broken, config, configureTurn: () => services([]) })).toThrow("read failed");
51
+ } finally { opened.value.close(); }
52
+ });
53
+
54
+ test("legacy opens expose absence; own storage receives an explicit config", async () => {
55
+ const legacy = createMemoryStorageAdapter().open({ mode: "create", identity: { sessionId: "legacy", compatibilityKey: "k" } });
56
+ if (!legacy.ok) throw new Error(legacy.error.message);
57
+ expect(legacy.value.ownerConfig()).toMatchObject({ ok: true, value: undefined });
58
+ expect(() => createSession({ systemPrompt: "arbitrary legacy prompt", storage: legacy.value, configureTurn: () => services([]) })).not.toThrow();
59
+ expect(() => createSession({ systemPrompt: "owner", storage: legacy.value, config: base(), configureTurn: () => services([]) })).toThrow("does not match");
60
+ legacy.value.close();
61
+ const effects: string[] = [], session = createSession({ systemPrompt: "owner", config: base(), configureTurn: () => services(effects) });
62
+ try { session.start(); session.agent.send({ channelId: "a", participantId: "u", text: "hi" }); await until(() => session.snapshot().turns[0]?.state.status === "completed"); expect(effects).toEqual([]); }
63
+ finally { session.stop("done"); }
64
+ });
@@ -0,0 +1,68 @@
1
+ import { inspectOperatorView } from "./helpers/operator-view.ts";
2
+ import { expect, test } from "bun:test";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { createInProcessHarness } from "../src/testing.ts";
7
+ import { spawnHarness } from "./helpers/stdio.ts";
8
+ import type { ChannelEvent, ManagedConfig } from "../src/client.ts";
9
+
10
+ const script = new URL("./fixtures/approval-e2e.jsonl", import.meta.url).pathname;
11
+ const config: ManagedConfig = { version: 1, system: "Test approvals", model: { protocol: "scripted", script }, defaultPolicy: "ask",
12
+ policies: { ask: { fallback: "ask", tools: {} }, deny: { fallback: "deny", tools: {} } } };
13
+ const init = { protocolVersion: 1, host: { name: "test", version: "0" }, callbacks: [], approval: true,
14
+ subscription: { text: "final" as const, tools: "full" as const } };
15
+ const push = (channel: string, id: string, policy?: string) => ({ channel, item: { id, kind: "user_message" as const, sender: channel,
16
+ content: [{ type: "text" as const, text: id }], ...(policy ? { policy } : {}) } });
17
+ const lines = (path: string) => existsSync(path) ? readFileSync(path, "utf8").split("\n").filter(Boolean) : [];
18
+ async function until(check: () => boolean, what: string) { for (let i = 0; i < 600; i++) { if (check()) return; await new Promise(r => setTimeout(r, 5)); } throw new Error(`Timed out: ${what}`); }
19
+
20
+ for (const transport of ["in-process", "stdio"] as const) test(`${transport}: suspension cancels approval, resumes with its result, then approves a fresh call`, async () => {
21
+ const home = mkdtempSync(join(tmpdir(), "harness-permissions-e2e-")), effects = join(home, "effects.log"), requests = join(home, "requests.jsonl");
22
+ const destination = mkdtempSync(join(tmpdir(), "harness-permissions-destination-"));
23
+ const open = (location: string) => transport === "stdio" ? spawnHarness({ home: location, effects, requests }) : createInProcessHarness({ home: location, effects, requests });
24
+ const harness = open(home);
25
+ let sourceClosed = false, restored: ReturnType<typeof open> | undefined;
26
+ const events: ChannelEvent[] = []; harness.client.onChannelEvent(event => events.push(event));
27
+ try {
28
+ await harness.client.initialize(init);
29
+ await harness.client.createSession({ sessionId: "s", config, participants: [], channels: {} });
30
+ await harness.client.push(push("alice", "a1"));
31
+ await until(() => events.some(e => e.channel === "alice" && e.event.type === "approval_requested"), "first approval");
32
+ const first = events.find(e => e.channel === "alice" && e.event.type === "approval_requested")!.event;
33
+ if (first.type !== "approval_requested") throw new Error("missing approval");
34
+ expect(first).toMatchObject({ turnId: "1", toolCallId: "first", tool: "record" });
35
+ await harness.client.push(push("bob", "b1", "deny"));
36
+ await until(() => events.some(e => e.channel === "bob" && e.event.type === "turn_ended" && e.event.outcome === "completed"), "Bob completes");
37
+ expect(lines(effects)).toEqual([]);
38
+ expect(await harness.client.suspendChannel({ channel: "alice" })).toMatchObject({ channel: { lifecycle: "suspended", activeTurn: { turnId: "1", state: "suspended" } } });
39
+ expect(lines(effects)).toEqual([]);
40
+ await expect(harness.client.respondApproval(first.requestId, "allow_once")).rejects.toMatchObject({ code: "not_found" });
41
+ expect(events.filter(e => e.channel === "alice" && e.event.type === "tool_call" && e.event.status === "started")).toEqual([]);
42
+
43
+ // Export needs a clean session suspension when an individual checkpoint
44
+ // remains; import into a fresh home and reopen from its saved config.
45
+ await harness.client.suspend(); const archive = await harness.client.exportArchive();
46
+ await harness.close(); sourceClosed = true;
47
+ restored = open(destination); restored.client.onChannelEvent(event => events.push(event));
48
+ await restored.client.initialize(init); await restored.client.importArchive(archive);
49
+ const loaded = await inspectOperatorView(restored.client, { sessionId: "s" });
50
+ await expect(restored.client.respondApproval(first.requestId, "allow_once")).rejects.toMatchObject({ code: "not_found" });
51
+ expect(loaded.status.channels.find(channel => channel.channel === "alice")).toMatchObject({ lifecycle: "suspended", activeTurn: { turnId: "1", state: "suspended" } });
52
+ await restored.client.resume();
53
+ expect((await restored.client.status()).channels.find(channel => channel.channel === "alice")).toMatchObject({ lifecycle: "suspended" });
54
+ await restored.client.resumeChannel({ channel: "alice" });
55
+ await until(() => events.filter(e => e.channel === "alice" && e.event.type === "approval_requested").length === 2, "second approval");
56
+ const approvals = events.filter(e => e.channel === "alice" && e.event.type === "approval_requested").map(e => e.event);
57
+ const second = approvals[1]!; if (second.type !== "approval_requested") throw new Error("missing second approval");
58
+ expect(second).toMatchObject({ turnId: "1", toolCallId: "second", tool: "record" }); expect(second.requestId).not.toBe(first.requestId);
59
+ const aliceRequests = lines(requests).map(line => JSON.parse(line)).filter(request => request.channel === "alice");
60
+ expect(aliceRequests).toHaveLength(2);
61
+ const result = aliceRequests[1].messages.findLast((message: { role: string }) => message.role === "tool");
62
+ expect(result.callId).toBe("first"); expect(JSON.parse(result.content)).toMatchObject({ code: "approval_cancelled_by_suspension", ok: false });
63
+ expect(await restored.client.respondApproval(second.requestId, "allow_once")).toEqual({ accepted: true });
64
+ await until(() => events.some(e => e.channel === "alice" && e.event.type === "turn_ended" && e.event.outcome === "completed"), "Alice completes");
65
+ expect(lines(effects)).toEqual(["approved"]);
66
+ expect(events.filter(e => e.channel === "alice" && e.event.type === "tool_call" && e.event.status === "started")).toHaveLength(1);
67
+ } finally { if (!sourceClosed) await harness.close(); if (restored) await restored.close(); rmSync(home, { recursive: true, force: true }); rmSync(destination, { recursive: true, force: true }); }
68
+ }, 20000);