@qlairoslabs/acp-client 0.12.1 → 0.13.1-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 (288) 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 +984 -6
  6. package/MIGRATION-0.10-to-0.12.md +4 -1
  7. package/MIGRATION-0.12-to-0.13.md +288 -0
  8. package/README.md +17 -16
  9. package/package.json +11 -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 +95 -158
  19. package/src/agent/manager-settings.ts +1 -0
  20. package/src/agent/native-channel-lifecycle.ts +111 -0
  21. package/src/agent/native-operations.ts +39 -0
  22. package/src/agent/persisted-lifecycle.ts +44 -4
  23. package/src/agent/persistence-policy/context.ts +13 -0
  24. package/src/agent/persistence-policy/resolver.ts +7 -0
  25. package/src/agent/persistence-policy/types.ts +1 -0
  26. package/src/agent/record-capture.ts +1 -0
  27. package/src/agent-adapter-registry.ts +33 -7
  28. package/src/agent-conversation-contracts.ts +14 -1
  29. package/src/agent-conversation-errors.ts +8 -0
  30. package/src/agent-conversation-owner.ts +9 -4
  31. package/src/agent-session-config.ts +137 -0
  32. package/src/agent-session.ts +440 -934
  33. package/src/agent.ts +168 -0
  34. package/src/capabilities.ts +2 -0
  35. package/src/checkpointing/recovery.ts +3 -0
  36. package/src/cli/index.ts +3 -3
  37. package/src/cli/managed.ts +2 -2
  38. package/src/client.ts +56 -96
  39. package/src/connection-attempt.ts +95 -0
  40. package/src/controller-connection.ts +115 -0
  41. package/src/controller.ts +158 -148
  42. package/src/conversation-controller/capabilities.ts +88 -0
  43. package/src/conversation-controller/contracts.ts +208 -0
  44. package/src/conversation-controller/factory.ts +39 -0
  45. package/src/conversation-controller/guards.ts +98 -0
  46. package/src/conversation-controller/index.ts +20 -0
  47. package/src/conversation-startup.ts +35 -0
  48. package/src/conversation-turns/backend-turns.ts +373 -0
  49. package/src/conversation-turns/clear-operations.ts +37 -0
  50. package/src/conversation-turns/context.ts +135 -0
  51. package/src/conversation-turns/index.ts +4 -0
  52. package/src/conversation-turns/record-helpers.ts +75 -0
  53. package/src/conversation-turns/recording.ts +235 -0
  54. package/src/conversation-turns/run-turn.ts +367 -0
  55. package/src/conversation-turns/turn-run.ts +57 -0
  56. package/src/errors.ts +41 -0
  57. package/src/handoff-options.ts +81 -0
  58. package/src/identity/checkpoint-backed.ts +1 -1
  59. package/src/index.ts +59 -3
  60. package/src/internal-inference/coordination/manager.ts +11 -0
  61. package/src/internal-inference/runtime/harness-runtime.ts +4 -4
  62. package/src/launcher.ts +37 -2
  63. package/src/media/parts.ts +5 -0
  64. package/src/message-status.ts +83 -0
  65. package/src/metering/engine.ts +39 -64
  66. package/src/metering/measurement-provenance.ts +36 -0
  67. package/src/metering/native/durability.ts +115 -0
  68. package/src/metering/native/ledger.ts +104 -0
  69. package/src/metering/native/operation.ts +85 -0
  70. package/src/metering/native/projection.ts +114 -0
  71. package/src/metering/native/proof.ts +51 -0
  72. package/src/metering/native/requirements.ts +10 -0
  73. package/src/metering/native/retirement.ts +92 -0
  74. package/src/metering/native/source.ts +90 -0
  75. package/src/metering/record.ts +38 -1
  76. package/src/metering/state.ts +13 -3
  77. package/src/native/approvals.ts +186 -0
  78. package/src/native/capabilities.ts +17 -0
  79. package/src/native/channel-changes.ts +211 -0
  80. package/src/native/connection.ts +56 -0
  81. package/src/native/controller.ts +592 -0
  82. package/src/native/delegation-sender.ts +26 -0
  83. package/src/native/errors.ts +35 -0
  84. package/src/native/functions.ts +156 -0
  85. package/src/native/host-config.ts +59 -0
  86. package/src/native/host.ts +978 -0
  87. package/src/native/item-receipts.ts +15 -0
  88. package/src/native/metering.ts +12 -0
  89. package/src/native/records.ts +166 -0
  90. package/src/native/recovery.ts +186 -0
  91. package/src/native/reminders/fixtures/schema21.sqlite.gz +0 -0
  92. package/src/native/reminders/idle.ts +70 -0
  93. package/src/native/reminders/limits.ts +19 -0
  94. package/src/native/reminders/notifications.ts +29 -0
  95. package/src/native/reminders/routine-guard.ts +66 -0
  96. package/src/native/reminders/routine-schedule.ts +25 -0
  97. package/src/native/reminders/routine-wire.ts +21 -0
  98. package/src/native/reminders/schedule.ts +97 -0
  99. package/src/native/reminders/service.ts +280 -0
  100. package/src/native/reminders/supervisor.ts +91 -0
  101. package/src/native/reminders/sync.ts +301 -0
  102. package/src/native/reminders/wire.ts +197 -0
  103. package/src/native/submission-withdrawal.ts +65 -0
  104. package/src/native/usage.ts +15 -0
  105. package/src/native/worker-delivery.ts +61 -0
  106. package/src/native-harness/README.md +726 -0
  107. package/src/native-harness/package.json +24 -0
  108. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  109. package/src/native-harness/src/capabilities/context/build.ts +59 -0
  110. package/src/native-harness/src/capabilities/context/instructions/agent-demo.md +11 -0
  111. package/src/native-harness/src/capabilities/context/instructions/agent.md +5 -0
  112. package/src/native-harness/src/capabilities/context/instructions/harness.md +7 -0
  113. package/src/native-harness/src/capabilities/context/load-instructions.ts +22 -0
  114. package/src/native-harness/src/capabilities/context/session.ts +93 -0
  115. package/src/native-harness/src/capabilities/model/attempt.ts +27 -0
  116. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +72 -0
  117. package/src/native-harness/src/capabilities/model/openrouter.ts +62 -0
  118. package/src/native-harness/src/capabilities/model/runner.ts +116 -0
  119. package/src/native-harness/src/capabilities/model/scenario-attempt.ts +50 -0
  120. package/src/native-harness/src/capabilities/model/scenario-file.ts +125 -0
  121. package/src/native-harness/src/capabilities/model/scripted-error.ts +6 -0
  122. package/src/native-harness/src/capabilities/model/scripted.ts +81 -0
  123. package/src/native-harness/src/capabilities/model/usage.ts +15 -0
  124. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  125. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  126. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  127. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  128. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  129. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  130. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  131. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  132. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  133. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  134. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  135. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  136. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  137. package/src/native-harness/src/capabilities/tools/builtin/current-time.ts +28 -0
  138. package/src/native-harness/src/capabilities/tools/builtin/notify-channel.ts +17 -0
  139. package/src/native-harness/src/capabilities/tools/debug/index.ts +13 -0
  140. package/src/native-harness/src/capabilities/tools/debug/result.ts +12 -0
  141. package/src/native-harness/src/capabilities/tools/debug/test-echo.ts +16 -0
  142. package/src/native-harness/src/capabilities/tools/debug/test-fail.ts +14 -0
  143. package/src/native-harness/src/capabilities/tools/debug/test-wait.ts +19 -0
  144. package/src/native-harness/src/capabilities/tools/reminders/index.ts +97 -0
  145. package/src/native-harness/src/capabilities/tools/runtime/catalog.ts +103 -0
  146. package/src/native-harness/src/capabilities/tools/runtime/functions.ts +130 -0
  147. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +48 -0
  148. package/src/native-harness/src/capabilities/tools/testing/echo.ts +18 -0
  149. package/src/native-harness/src/capabilities/tools/testing/record.ts +47 -0
  150. package/src/native-harness/src/capabilities/tools/timeline/index.ts +41 -0
  151. package/src/native-harness/src/client.ts +18 -0
  152. package/src/native-harness/src/contracts/agent.ts +105 -0
  153. package/src/native-harness/src/contracts/config-permissions.ts +49 -0
  154. package/src/native-harness/src/contracts/context.ts +112 -0
  155. package/src/native-harness/src/contracts/events.ts +47 -0
  156. package/src/native-harness/src/contracts/input-limits.ts +7 -0
  157. package/src/native-harness/src/contracts/inspection.ts +22 -0
  158. package/src/native-harness/src/contracts/loop.ts +31 -0
  159. package/src/native-harness/src/contracts/model-execution.ts +83 -0
  160. package/src/native-harness/src/contracts/operator-controls.ts +106 -0
  161. package/src/native-harness/src/contracts/output.ts +13 -0
  162. package/src/native-harness/src/contracts/protocol.ts +320 -0
  163. package/src/native-harness/src/contracts/reminders.ts +134 -0
  164. package/src/native-harness/src/contracts/routines.ts +20 -0
  165. package/src/native-harness/src/contracts/scenario.ts +42 -0
  166. package/src/native-harness/src/contracts/session-file.ts +20 -0
  167. package/src/native-harness/src/contracts/session.ts +184 -0
  168. package/src/native-harness/src/contracts/storage.ts +597 -0
  169. package/src/native-harness/src/contracts/timeline-retrieval.ts +40 -0
  170. package/src/native-harness/src/contracts/tools.ts +133 -0
  171. package/src/native-harness/src/governance/permissions/gate.ts +129 -0
  172. package/src/native-harness/src/governance/policy/resolve.ts +32 -0
  173. package/src/native-harness/src/index.ts +322 -0
  174. package/src/native-harness/src/interfaces/cli/chat.ts +83 -0
  175. package/src/native-harness/src/interfaces/cli/development.ts +145 -0
  176. package/src/native-harness/src/interfaces/cli/format-reply.ts +27 -0
  177. package/src/native-harness/src/interfaces/cli/listeners.ts +74 -0
  178. package/src/native-harness/src/interfaces/cli/main.ts +47 -0
  179. package/src/native-harness/src/interfaces/cli/scenario.ts +37 -0
  180. package/src/native-harness/src/interfaces/cli/serve.ts +21 -0
  181. package/src/native-harness/src/interfaces/cli/start.ts +106 -0
  182. package/src/native-harness/src/interfaces/client.ts +225 -0
  183. package/src/native-harness/src/interfaces/inspector/index.html +283 -0
  184. package/src/native-harness/src/interfaces/inspector/observe.ts +35 -0
  185. package/src/native-harness/src/interfaces/inspector/server.ts +56 -0
  186. package/src/native-harness/src/interfaces/inspector/state.ts +92 -0
  187. package/src/native-harness/src/interfaces/protocol/channel-changes.ts +153 -0
  188. package/src/native-harness/src/interfaces/protocol/framing.ts +47 -0
  189. package/src/native-harness/src/interfaces/protocol/functions.ts +87 -0
  190. package/src/native-harness/src/interfaces/protocol/in-process.ts +67 -0
  191. package/src/native-harness/src/interfaces/protocol/live-queue.ts +55 -0
  192. package/src/native-harness/src/interfaces/protocol/load.ts +60 -0
  193. package/src/native-harness/src/interfaces/protocol/local.ts +120 -0
  194. package/src/native-harness/src/interfaces/protocol/operator.ts +120 -0
  195. package/src/native-harness/src/interfaces/protocol/output.ts +59 -0
  196. package/src/native-harness/src/interfaces/protocol/server.ts +519 -0
  197. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +126 -0
  198. package/src/native-harness/src/interfaces/protocol/stdio-server.ts +82 -0
  199. package/src/native-harness/src/interfaces/protocol/subscribe.ts +41 -0
  200. package/src/native-harness/src/interfaces/protocol/transfers.ts +146 -0
  201. package/src/native-harness/src/interfaces/web-chat/index.html +94 -0
  202. package/src/native-harness/src/interfaces/web-chat/server.ts +34 -0
  203. package/src/native-harness/src/kernel/channels.ts +409 -0
  204. package/src/native-harness/src/kernel/loop.ts +45 -0
  205. package/src/native-harness/src/runtime/config/development.ts +23 -0
  206. package/src/native-harness/src/runtime/config/managed.ts +2 -0
  207. package/src/native-harness/src/runtime/config/paths.ts +33 -0
  208. package/src/native-harness/src/runtime/reminder-timer.ts +42 -0
  209. package/src/native-harness/src/runtime/reminder-validation.ts +125 -0
  210. package/src/native-harness/src/runtime/reminders.ts +66 -0
  211. package/src/native-harness/src/state/storage/archive.ts +257 -0
  212. package/src/native-harness/src/state/storage/engine.ts +1204 -0
  213. package/src/native-harness/src/state/storage/inference.ts +124 -0
  214. package/src/native-harness/src/state/storage/memory-reminders.ts +103 -0
  215. package/src/native-harness/src/state/storage/memory.ts +354 -0
  216. package/src/native-harness/src/state/storage/policy-metadata.ts +32 -0
  217. package/src/native-harness/src/state/storage/reminder-archive.ts +104 -0
  218. package/src/native-harness/src/state/storage/reminder-change.ts +138 -0
  219. package/src/native-harness/src/state/storage/reminder-tables.ts +35 -0
  220. package/src/native-harness/src/state/storage/retrieval.ts +122 -0
  221. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  222. package/src/native-harness/src/state/storage/script-identity.ts +7 -0
  223. package/src/native-harness/src/state/storage/session-file.ts +85 -0
  224. package/src/native-harness/src/state/storage/sqlite-reminders.ts +174 -0
  225. package/src/native-harness/src/state/storage/sqlite.ts +632 -0
  226. package/src/native-harness/src/testing.ts +190 -0
  227. package/src/native-harness/src/util/config.ts +66 -0
  228. package/src/native-harness/src/util/intake.ts +7 -0
  229. package/src/native-harness/src/util/json.ts +41 -0
  230. package/src/native-harness/src/util/message-position.ts +3 -0
  231. package/src/native-harness/src/util/reminder-schedule.ts +44 -0
  232. package/src/native-harness/src/util/schema.ts +40 -0
  233. package/src/native-harness/src/util/timeline-text.ts +72 -0
  234. package/src/native-harness/src/util/timeline-tool-names.ts +3 -0
  235. package/src/native-harness/tsconfig.json +20 -0
  236. package/src/observation/agent-event-bus.ts +44 -18
  237. package/src/observation/index.ts +1 -0
  238. package/src/operations/contracts.ts +11 -3
  239. package/src/operations/errors.ts +5 -0
  240. package/src/operations/stale-policy.ts +1 -1
  241. package/src/operations/supervisor.ts +34 -10
  242. package/src/orchestrator/acp-delivery.ts +68 -0
  243. package/src/orchestrator/assignments.ts +27 -0
  244. package/src/orchestrator/busy.ts +15 -0
  245. package/src/orchestrator/config.ts +41 -0
  246. package/src/orchestrator/consumer-api.ts +24 -0
  247. package/src/orchestrator/contracts.ts +71 -0
  248. package/src/orchestrator/durable-assignments.ts +111 -0
  249. package/src/orchestrator/native-delegation.ts +103 -0
  250. package/src/orchestrator/orchestrator.ts +318 -0
  251. package/src/orchestrator/permissions.ts +28 -0
  252. package/src/orchestrator/policy.ts +44 -0
  253. package/src/orchestrator/pool.ts +123 -0
  254. package/src/orchestrator/tool-descriptions.ts +11 -0
  255. package/src/permissions/acp.ts +18 -0
  256. package/src/permissions/arrival.ts +13 -0
  257. package/src/permissions/consumer-config.ts +19 -0
  258. package/src/permissions/conversation.ts +288 -0
  259. package/src/permissions/matcher.ts +87 -0
  260. package/src/permissions/outcome.ts +26 -0
  261. package/src/permissions/policy.ts +86 -0
  262. package/src/permissions/request.ts +26 -0
  263. package/src/persistence/activity-projection.ts +1 -0
  264. package/src/persistence/backend.ts +34 -1
  265. package/src/persistence/channels.ts +23 -0
  266. package/src/persistence/index.ts +4 -0
  267. package/src/persistence/protocol-method.ts +5 -0
  268. package/src/persistence/reminder-wake.ts +49 -0
  269. package/src/persistence/reminders.ts +385 -0
  270. package/src/persistence/sqlite-backend.ts +84 -6
  271. package/src/persistence/sqlite-channels.ts +65 -0
  272. package/src/persistence/sqlite-reminders.ts +85 -0
  273. package/src/persistence/sqlite-schema.ts +108 -3
  274. package/src/persistence/sqlite-worker-delivery.ts +374 -0
  275. package/src/persistence/sqlite-workers.ts +59 -0
  276. package/src/persistence/worker-delivery-contract.ts +104 -0
  277. package/src/persistence/worker-terminal-reason.ts +29 -0
  278. package/src/persistence/workers.ts +19 -0
  279. package/src/provider-notices.ts +137 -0
  280. package/src/repl/commands.ts +2 -2
  281. package/src/steering/combine.ts +3 -1
  282. package/src/steering/contracts.ts +11 -2
  283. package/src/steering/controller.ts +3 -2
  284. package/src/terminals.ts +9 -6
  285. package/src/transport/acp-transport.ts +24 -14
  286. package/src/types.ts +15 -12
  287. package/src/updates.ts +14 -2
  288. package/src/wire-log.ts +1 -1
@@ -0,0 +1,120 @@
1
+ import type { ChannelInput } from "../../contracts/agent.ts";
2
+ import type { ChannelOutputs } from "../../contracts/output.ts";
3
+ import type { PersistentSession } from "../../contracts/session.ts";
4
+ import { outputStream } from "./output.ts";
5
+
6
+ type LocalSession = Pick<PersistentSession, "agent" | "subscribe">;
7
+ /** Lifecycle operations for the process owner's local socket only. */
8
+ export type LocalControl = Pick<PersistentSession, "status" | "suspend" | "resume">;
9
+
10
+ /** Private to the local adapters: hold an HTTP request until the turn that
11
+ * took its input ends. Acceptance only names the item; `turn_started` or
12
+ * `turn_took` names the turn, and that turn's events carry the reply. Inputs
13
+ * that share a turn all resolve with its last completed message. This is not
14
+ * a public wait-for-reply API. */
15
+ function followReplies(subscribe: LocalSession["subscribe"]) {
16
+ const waiters = new Map<string, { resolve(answer: string): void; reject(error: Error): void }>();
17
+ const turns = new Map<string, { items: string[]; answer: string }>();
18
+ subscribe(({ event }) => {
19
+ if (event.type === "turn_started" || event.type === "turn_took") {
20
+ const mine = event.items.filter(id => waiters.has(id));
21
+ if (!mine.length) return;
22
+ const turn = turns.get(event.turnId) ?? { items: [], answer: "" };
23
+ turn.items.push(...mine); turns.set(event.turnId, turn);
24
+ } else if (event.type === "message_completed") {
25
+ const turn = turns.get(event.turnId);
26
+ if (turn) turn.answer = (event.parts ?? []).map(part => part.text).join("");
27
+ } else if (event.type === "turn_ended" || event.type === "turn_suspended") {
28
+ const turn = turns.get(event.turnId);
29
+ if (!turn) return;
30
+ turns.delete(event.turnId);
31
+ for (const id of turn.items) {
32
+ const waiter = waiters.get(id); waiters.delete(id);
33
+ // A checkpointed turn answers only after resume, possibly in another
34
+ // process: release the request now instead of holding it open.
35
+ if (event.type !== "turn_ended") waiter?.reject(new Error("The session was suspended before this turn finished; its reply follows after resume"));
36
+ else if (event.outcome === "completed") waiter?.resolve(turn.answer);
37
+ else waiter?.reject(new Error(event.error ?? `Turn ${event.outcome}`));
38
+ }
39
+ }
40
+ });
41
+ // Register in the same tick as acceptance: the take is always a later task.
42
+ return (itemId: string) => new Promise<string>((resolve, reject) => { waiters.set(itemId, { resolve, reject }); });
43
+ }
44
+
45
+ /** Shared channel HTTP operations for local terminal and browser adapters. */
46
+ export function createChannelHandler(session: LocalSession, outputs?: ChannelOutputs, control?: LocalControl) {
47
+ const reply = followReplies(session.subscribe);
48
+ return async (request: Request): Promise<Response> => {
49
+ const url = new URL(request.url);
50
+ if (control && url.pathname === "/session") {
51
+ if (request.method === "GET") return Response.json(control.status());
52
+ if (request.method !== "POST") return new Response("Use GET or POST", { status: 405 });
53
+ const action = url.searchParams.get("action");
54
+ if (action !== "suspend" && action !== "resume") return Response.json({ error: "action must be suspend or resume" }, { status: 400 });
55
+ // Suspend answers when the session is suspended, after running tools finish.
56
+ const outcome = action === "suspend" ? await control.suspend() : control.resume();
57
+ return outcome.ok ? Response.json(outcome.status) : Response.json({ error: outcome.error.message, code: outcome.error.code }, { status: 409 });
58
+ }
59
+ if (url.pathname === "/events" && outputs) {
60
+ if (request.method !== "GET") return new Response("Use GET", { status: 405 });
61
+ const channelId = url.searchParams.get("channelId");
62
+ if (!channelId?.trim()) return new Response("channelId is required", { status: 400 });
63
+ return outputStream(outputs, channelId);
64
+ }
65
+ if (url.pathname !== "/messages") return new Response("Not found", { status: 404 });
66
+ if (request.method !== "POST") return new Response("Use POST", { status: 405 });
67
+ let input: ChannelInput;
68
+ try {
69
+ const body = await request.json() as ChannelInput | null;
70
+ if (!body || ![body.channelId, body.participantId, body.text].every(
71
+ (value) => typeof value === "string" && value.trim().length > 0,
72
+ )) throw new Error("Expected channelId, participantId and text as nonempty strings");
73
+ input = { channelId: body.channelId, participantId: body.participantId, text: body.text };
74
+ } catch (error) {
75
+ return Response.json({ error: String(error) }, { status: 400 });
76
+ }
77
+ const accepted = session.agent.send(input);
78
+ if (!accepted.accepted) return Response.json({ error: accepted.error }, { status: accepted.code === "invalid_input" ? 400 : 503 });
79
+ try { return Response.json({ answer: await reply(accepted.itemId) }); }
80
+ catch (error) { return Response.json({ error: String(error) }, { status: 500 }); }
81
+ };
82
+ }
83
+
84
+ /** Experimental local HTTP interface; caller identity is self-reported. */
85
+ export function serveLocal(session: LocalSession, socketPath: string, outputs?: ChannelOutputs, control?: LocalControl) {
86
+ let handle: ReturnType<typeof createChannelHandler> | undefined;
87
+ return Bun.serve({
88
+ unix: socketPath,
89
+ fetch(request, server) {
90
+ server.timeout(request, 0);
91
+ handle ??= createChannelHandler(session, outputs, control);
92
+ return handle(request);
93
+ },
94
+ });
95
+ }
96
+
97
+ /** Deliver one turn to a separately running local agent. */
98
+ export async function sendLocal(socketPath: string, input: ChannelInput, signal?: AbortSignal): Promise<string> {
99
+ const response = await fetch("http://localhost/messages", {
100
+ unix: socketPath, method: "POST",
101
+ headers: { "Content-Type": "application/json" },
102
+ body: JSON.stringify(input),
103
+ signal,
104
+ });
105
+ const result = await response.json() as { answer?: string; error?: string };
106
+ if (!response.ok || typeof result.answer !== "string") {
107
+ throw new Error(result.error ?? `Agent HTTP ${response.status}`);
108
+ }
109
+ return result.answer;
110
+ }
111
+
112
+ /** Read or change the lifecycle of a separately running local agent. */
113
+ export async function controlLocal(socketPath: string, action: "status" | "suspend" | "resume"): Promise<unknown> {
114
+ const response = await fetch(`http://localhost/session${action === "status" ? "" : `?action=${action}`}`, {
115
+ unix: socketPath, method: action === "status" ? "GET" : "POST",
116
+ });
117
+ const result = await response.json() as { error?: string };
118
+ if (!response.ok) throw new Error(result.error ?? `Agent HTTP ${response.status}`);
119
+ return result;
120
+ }
@@ -0,0 +1,120 @@
1
+ import { timelineMessageId as messageId } from "../../util/timeline-text.ts";
2
+ import { messagePosition } from "../../util/message-position.ts";
3
+ import type { PersistentSession } from "../../contracts/session.ts";
4
+ import type { StorageResult, TimelineEntry } from "../../contracts/storage.ts";
5
+ import { MAX_FRAME_BYTES } from "./framing.ts";
6
+ import { turnStatus } from "./load.ts";
7
+
8
+ export class OperatorFault extends Error {
9
+ constructor(readonly code: string, message: string) { super(message); }
10
+ }
11
+ const bad = (message: string): never => { throw new OperatorFault("invalid_params", message); };
12
+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
13
+ const decode = (value: unknown): unknown[] => {
14
+ if (typeof value !== "string" || value.length > 65536) return bad("Invalid cursor");
15
+ try {
16
+ const data = JSON.parse(Buffer.from(value, "base64url").toString());
17
+ if (Array.isArray(data) && encode(data) === value) return data;
18
+ } catch { /* report a typed parameter error */ }
19
+ return bad("Invalid cursor");
20
+ };
21
+ export function readValue<T>(result: StorageResult<T>) {
22
+ if (!result.ok) throw new OperatorFault(result.error.code === "invalid_input" ? "invalid_params" : result.error.code, result.error.message);
23
+ return result;
24
+ }
25
+ const id = (value: unknown): string => typeof value === "string" && value.trim() ? value : bad("Expected an ID");
26
+ const sequence = (value: unknown): number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : bad("Invalid sequence");
27
+ const turnId = (value: unknown): number => {
28
+ const text = id(value), n = Number(text);
29
+ return n > 0 && String(sequence(n)) === text ? n : bad("Invalid turn ID");
30
+ };
31
+ const ids = (value: unknown): string[] => {
32
+ if (value === undefined) return [];
33
+ if (!Array.isArray(value) || value.length > 100) return bad("Invalid tracked IDs");
34
+ const list = value.map(id);
35
+ if (new Set(list).size !== list.length) return bad("Duplicate tracked IDs");
36
+ return list;
37
+ };
38
+
39
+ export const operatorMethods = ["channel/observe", "channel/reconcile", "channel/messages", "session/timeline"] as const;
40
+ export function operatorRead(session: PersistentSession, method: string, p: Record<string, unknown>, approvalConsumer: boolean) {
41
+ const storage = session.operatorReads;
42
+ if (!storage) throw new OperatorFault("invalid_state", "Focused reads are unavailable");
43
+ const header = readValue(storage.readSession());
44
+ const scope = header.value.sessionId;
45
+ const channel = method === "session/timeline" ? undefined : id(p.channel);
46
+ const position = (entry: TimelineEntry) => messagePosition(scope, entry.channelId, entry.seq);
47
+ const budget = MAX_FRAME_BYTES - 1024;
48
+ if (method === "channel/observe") {
49
+ const found = readValue(storage.readChannel(channel!));
50
+ const { channelId, ...state } = found.value.channel;
51
+ const turn = found.value.activeTurn;
52
+ const phase = turn && session.turnPhase?.(turn.turnId);
53
+ return { revision: found.revision, sessionLifecycle: header.value.lifecycle,
54
+ channel: { channel: channelId, ...state, pendingCount: found.value.pendingCount,
55
+ waitingForResume: (state.lifecycle !== "open" || header.value.lifecycle !== "running") && (found.value.pendingCount > 0 || turn?.state.status === "suspended"),
56
+ ...(turn ? { activeTurn: { turnId: String(turn.turnId), state: turn.state.status, ...(phase ? { phase } : {}) } } : {}) },
57
+ approvals: approvalConsumer ? (session.approvals.waiting?.() ?? []).filter(request => request.channel === channel) : [] };
58
+ }
59
+ if (method === "channel/reconcile") {
60
+ const cursor = p.cursor === undefined ? undefined : decode(p.cursor);
61
+ if (cursor && (cursor.length !== 6 || cursor[0] !== scope || cursor[1] !== method || cursor[2] !== channel || p.itemIds !== undefined || p.turnIds !== undefined)) return bad("Invalid reconcile cursor");
62
+ const inputIds = ids(p.itemIds), turns = ids(cursor?.[5] ?? p.turnIds).map(turnId);
63
+ if (inputIds.length + turns.length > 100) return bad("Too many tracked IDs");
64
+ const revision = cursor ? sequence(cursor[3]) : header.revision;
65
+ const tracked = cursor ? undefined : readValue(storage.readTracked(channel!, inputIds, turns)).value;
66
+ const page = readValue(storage.readTimeline({ kind: "replies", channel, turnIds: turns, direction: "newer", throughRevision: revision,
67
+ exclusiveSeq: cursor ? sequence(cursor[4]) : undefined, limit: 50 })).value;
68
+ const items = tracked?.items.map(item => ({ id: item.itemId, channel: item.channelId, kind: item.kind, sender: item.senderId, ...(item.externalSource === undefined ? {} : { externalSource: item.externalSource }),
69
+ milestone: item.milestone, ...(item.policy ? { policy: item.policy } : {}), ...(item.turnId !== undefined ? { turnId: String(item.turnId) } : {}) })) ?? [];
70
+ const foundTurns = tracked?.turns.map(turnStatus) ?? [];
71
+ const result = { revision, items, turns: foundTurns, unknownItemIds: inputIds.filter(id => !items.some(item => item.id === id)),
72
+ unknownTurnIds: cursor ? [] : turns.map(String).filter(id => !foundTurns.some(turn => turn.turnId === id)),
73
+ replies: page.entries.map(entry => ({ messageId: messageId(entry), turnId: String(entry.turnId), position: position(entry) })),
74
+ ...(page.more ? { next: encode([scope, method, channel, revision, page.entries.at(-1)!.seq, turns.map(String)]) } : {}) };
75
+ if (Buffer.byteLength(JSON.stringify(result)) > budget) throw new OperatorFault("transfer_limit", "Tracked view exceeds the response budget");
76
+ return result;
77
+ }
78
+ const limit = p.limit === undefined ? 50 : sequence(p.limit);
79
+ if (limit < 1 || limit > 100) return bad("Expected a limit between 1 and 100");
80
+ const cursor = p.cursor === undefined ? undefined : decode(p.cursor);
81
+ if (cursor && (cursor.length !== 6 || cursor[0] !== scope || cursor[1] !== method || cursor[2] !== (channel ?? null)
82
+ || p.after !== undefined || p.throughRevision !== undefined || !["older", "newer"].includes(String(cursor[3])))) return bad("Invalid history cursor");
83
+ if ((p.after === undefined) !== (p.throughRevision === undefined) || (!channel && p.after !== undefined)) return bad("Invalid catch-up bounds");
84
+ const after = p.after === undefined ? undefined : decode(p.after);
85
+ if (after && (after.length !== 3 || after[0] !== scope || after[1] !== channel)) return bad("Position belongs to another session or channel");
86
+ const direction = cursor?.[3] === "newer" || after ? "newer" : "older";
87
+ const throughRevision = cursor ? sequence(cursor[4]) : after ? sequence(p.throughRevision) : header.revision;
88
+ const exclusiveSeq = cursor ? sequence(cursor[5]) : after ? sequence(after[2]) : undefined;
89
+ if (direction === "newer" && exclusiveSeq !== undefined && exclusiveSeq > throughRevision) return bad("Position exceeds revision");
90
+ const page = readValue(storage.readTimeline({ kind: channel ? "conversation" : "timeline", channel, throughRevision, exclusiveSeq, direction, limit })).value;
91
+ let size = 0, last = 0;
92
+ const records = [];
93
+ for (const entry of page.entries) {
94
+ const participant = entry.kind === "participant_message";
95
+ const actor = entry.kind === "external_notice" ? { kind: "agent", id: entry.externalSource ?? "host" } : participant ? { kind: "participant", id: entry.from } : { kind: "agent", id: entry.sourceChannelId ?? scope };
96
+ const base = { channel: entry.channelId, turnId: String(entry.turnId), actor, position: position(entry) };
97
+ const message = entry.message;
98
+ const content = participant && message.role === "user" ? message.content.slice(`Participant: ${JSON.stringify(entry.from)}\n\n`.length) : message.content;
99
+ const identity = { ...base, messageId: messageId(entry), ...(participant ? { itemId: entry.itemId } : {}) };
100
+ const activity = { ...base, ...(entry.kind === "external_notice" ? { itemId: entry.itemId, externalSource: entry.externalSource } : {}), ...(entry.sourceChannelId ? { sourceChannel: entry.sourceChannelId } : {}),
101
+ kind: entry.kind ?? (message.role === "tool" ? "tool_result" : message.role === "assistant" && !message.content ? "tool_call" : "assistant_message"),
102
+ ...(message.role === "assistant" || participant ? { messageId: messageId(entry) } : {}) };
103
+ let record: object = channel ? { ...identity, parts: [{ type: "text", text: content }] } : { ...activity, payload: message };
104
+ let bytes = Buffer.byteLength(JSON.stringify(record)) + 1;
105
+ if (bytes > budget) {
106
+ record = channel ? { ...identity, ...(participant ? { omitted: true } : { reference: true }) } : { ...activity, omitted: true,
107
+ ...(message.role === "tool" && message.outcome?.reference ? { resultReference: message.outcome.reference } : {}) };
108
+ bytes = Buffer.byteLength(JSON.stringify(record)) + 1;
109
+ if (bytes > budget && !channel) { record = { ...activity, omitted: true }; bytes = Buffer.byteLength(JSON.stringify(record)) + 1; }
110
+ }
111
+ if (size + bytes > budget) {
112
+ if (!records.length) throw new OperatorFault("transfer_limit", "Record identity exceeds the response budget");
113
+ break;
114
+ }
115
+ records.push(record); last = entry.seq; size += bytes;
116
+ }
117
+ const next = page.more || records.length < page.entries.length ? encode([scope, method, channel ?? null, direction, throughRevision, last]) : undefined;
118
+ if (direction === "older") records.reverse();
119
+ return { [channel ? "messages" : "events"]: records, ...(next ? { next } : {}) };
120
+ }
@@ -0,0 +1,59 @@
1
+ import type { ChannelOutput, ChannelOutputs } from "../../contracts/output.ts";
2
+ import type { ChannelEvent } from "../../contracts/events.ts";
3
+
4
+ /** Development clients consume completed messages, never a second final return. */
5
+ export function publishChannelEvent(outputs: ChannelOutputs, { channel, event }: ChannelEvent) {
6
+ if (event.type === "message_completed") outputs.publish({ channelId: channel, turnId: Number(event.turnId),
7
+ type: "reply", text: (event.parts ?? []).map(part => part.text).join("") });
8
+ if (event.type === "turn_ended" && event.outcome !== "completed") outputs.publish({ channelId: channel,
9
+ turnId: Number(event.turnId), type: "error", text: event.error ?? `Turn ${event.outcome}` });
10
+ }
11
+
12
+ export function createChannelOutputs(): ChannelOutputs {
13
+ const listeners = new Map<string, Set<(output: ChannelOutput) => void>>();
14
+ return {
15
+ publish(output) {
16
+ for (const listener of listeners.get(output.channelId) ?? []) {
17
+ // A disconnected client cannot turn a successfully completed turn into
18
+ // an execution failure or prevent delivery to another connected client.
19
+ try { listener(structuredClone(output)); } catch { /* Subscriber owns cleanup. */ }
20
+ }
21
+ },
22
+ subscribe(channelId, listener) {
23
+ let group = listeners.get(channelId);
24
+ if (!group) { group = new Set(); listeners.set(channelId, group); }
25
+ group.add(listener);
26
+ return () => {
27
+ group.delete(listener);
28
+ if (!group.size) listeners.delete(channelId);
29
+ };
30
+ },
31
+ };
32
+ }
33
+
34
+ export function outputStream(outputs: ChannelOutputs, channelId: string): Response {
35
+ let unsubscribe = () => {};
36
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
37
+ const cleanup = () => { unsubscribe(); clearInterval(heartbeat); };
38
+ const encoder = new TextEncoder();
39
+ const stream = new ReadableStream<Uint8Array>({
40
+ start(controller) {
41
+ const send = (frame: string) => {
42
+ if ((controller.desiredSize ?? 0) <= 0) {
43
+ cleanup(); controller.close(); return;
44
+ }
45
+ controller.enqueue(encoder.encode(frame));
46
+ };
47
+ unsubscribe = outputs.subscribe(channelId, output => send(`data: ${JSON.stringify(output)}\n\n`));
48
+ // Handshake proves the subscription exists before the client sends work.
49
+ controller.enqueue(encoder.encode('event: ready\ndata: {}\n\n'));
50
+ // Keep idle Unix HTTP connections alive through runtime/client timeouts.
51
+ // SSE comments are ignored by the client and do not produce chat output.
52
+ heartbeat = setInterval(() => send(": keepalive\n\n"), 5000);
53
+ },
54
+ cancel() { cleanup(); },
55
+ }, { highWaterMark: 64 });
56
+ return new Response(stream, { headers: {
57
+ "Content-Type": "text/event-stream", "Cache-Control": "no-cache",
58
+ } });
59
+ }