@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,190 @@
1
+ import { wallReminderClock } from "./runtime/reminder-timer.ts";
2
+ import { createHash } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { mkdtempSync, mkdirSync, existsSync, rmdirSync, appendFileSync } from "node:fs";
6
+ import { createSession } from "./index.ts";
7
+ import type { SessionStorage, SessionStorageAdapter } from "./contracts/storage.ts";
8
+ import type { ExecuteTool, Model } from "./contracts/loop.ts";
9
+ import { loadScenario, scriptedCompatibilityKey } from "./capabilities/model/scenario-file.ts";
10
+ import { scenarioAttempt } from "./capabilities/model/scenario-attempt.ts";
11
+ import type { ModelRequest } from "./contracts/model-execution.ts";
12
+ import type { LoadedScenario } from "./contracts/scenario.ts";
13
+ export type { LoadedScenario, ScenarioHeader, ScenarioModelRecord, ScenarioRecord, ScenarioSend } from "./contracts/scenario.ts";
14
+ export { loadScenario, parseScenario } from "./capabilities/model/scenario-file.ts";
15
+ import { bindModelAttempt } from "./capabilities/model/attempt.ts";
16
+ import { openRouterAttempt } from "./capabilities/model/openrouter-stream.ts";
17
+ import { openRouter } from "./capabilities/model/openrouter.ts";
18
+ import { notifyChannelDefinition } from "./capabilities/tools/builtin/notify-channel.ts";
19
+ import { echoDefinition, executeEcho } from "./capabilities/tools/testing/echo.ts";
20
+ import { createHoldTool, createRecordTool, holdDefinition, recordDefinition } from "./capabilities/tools/testing/record.ts";
21
+ import { createMemoryStorageAdapter } from "./state/storage/memory.ts";
22
+ import { createSqliteStorageAdapter } from "./state/storage/sqlite.ts";
23
+ import { validateSessionPayload } from "./state/storage/archive.ts";
24
+ import { createProtocolServer, SessionOpenError } from "./interfaces/protocol/server.ts";
25
+ import { parseCatalog } from "./capabilities/tools/runtime/catalog.ts";
26
+ import { HarnessClient, createInProcessTransport } from "./client.ts";
27
+ import { chooseManagedConfig, managedSessionPaths } from "./runtime/config/paths.ts";
28
+ import { resolveCredential } from "./runtime/config/managed.ts";
29
+
30
+ export interface ScriptedServerOptions {
31
+ /** Directory of durable sessions, one SQLite file per session ID. */
32
+ home?: string;
33
+ /** Storage location for a session ID, for tests that keep one location across servers. */
34
+ adapter?: (sessionId: string) => SessionStorageAdapter;
35
+ /** `<point>:<n>`: kill this process, without unwinding, right after the n-th
36
+ * time the point is passed. Points are storage method names (after their
37
+ * commit) and `tool` (after a tool ran, before its result is recorded). */
38
+ fault?: string;
39
+ /** File the `record` tool appends to. */
40
+ effects?: string;
41
+ /** Offline test-only request capture; one JSON record per inference. */
42
+ requests?: string;
43
+ /** Opt-in scripted stall and shorter model deadline for offline process tests. */
44
+ stallChannel?: string;
45
+ snapshotLog?: string;
46
+ /** Lightweight local attempt evidence without request capture. */
47
+ attempts?: string;
48
+ captureRequests?: boolean;
49
+ /** Test seam for observing file reads. */
50
+ scenarioLoader?: (path: string) => Promise<LoadedScenario>;
51
+ streamResponses?: boolean;
52
+ modelTimeoutMs?: number;
53
+ reminderTime?: number;
54
+ /** Directory for transfer files when there is no home. */
55
+ transfers?: string;
56
+ /** Smaller transfer limits for tests. */
57
+ limits?: Partial<{ chunkBytes: number; maxBytes: number; idleMs: number }>;
58
+ /** Offline provider injection and destination environment for tests/hosts. */
59
+ providerFactory?: (apiKey: string, model: string) => Model;
60
+ environment?: Record<string, string | undefined>;
61
+ }
62
+
63
+ /** Real process death at an exact durable boundary: nothing after the commit
64
+ * runs, so no event, acknowledgment or cleanup can soften the crash. */
65
+ function faults(spec: string | undefined) {
66
+ const [point, nth] = (spec ?? "").split(":");
67
+ let seen = 0;
68
+ return (passed: string) => {
69
+ if (!point || passed !== point || ++seen !== Number(nth)) return;
70
+ process.kill(process.pid, "SIGKILL");
71
+ Bun.sleepSync(60_000);
72
+ };
73
+ }
74
+ function withFaults(storage: SessionStorage, hit: (point: string) => void): SessionStorage {
75
+ return new Proxy(storage, { get(target, key) {
76
+ const value = Reflect.get(target, key) as unknown;
77
+ if (typeof value !== "function" || typeof key !== "string") return value;
78
+ return (...args: unknown[]) => { const result = value.apply(target, args); if (result?.ok) hit(key); return result; };
79
+ } });
80
+ }
81
+
82
+ /** Real execution with scripted models per channel, exposed through the
83
+ * protocol. In memory by default; durable when given a home or an adapter. */
84
+ const BUILTINS = [echoDefinition, recordDefinition, holdDefinition];
85
+ export function createScriptedServer(options: ScriptedServerOptions = {}) {
86
+ const models = new Map<string, ModelRequest[]>();
87
+ const durable = !!(options.home || options.adapter);
88
+ const hit = faults(options.fault);
89
+ const memory = createMemoryStorageAdapter();
90
+ const noSidecar = join(mkdtempSync(join(tmpdir(), "harness-config-")), "config.json");
91
+ const locate = (sessionId: string) => {
92
+ return options.adapter?.(sessionId) ?? (options.home ? createSqliteStorageAdapter(managedSessionPaths(sessionId, options.home).database) : memory);
93
+ };
94
+ const server = createProtocolServer(async ({ mode, sessionId, config: inline, tools }) => {
95
+ // Decision 0021: the catalog's names must not collide with the built-ins.
96
+ const catalog = tools && parseCatalog(tools, BUILTINS.map(tool => tool.name));
97
+ const paths = options.home ? managedSessionPaths(sessionId, options.home) : undefined;
98
+ const adapter = locate(sessionId);
99
+ const stored = mode === "open" ? adapter.readSavedConfig() : undefined;
100
+ if (stored && !stored.ok) throw new SessionOpenError(stored.error.code === "not_found" || stored.error.code === "owner_conflict" ? stored.error.code : "storage_failure", stored.error.message);
101
+ const config = chooseManagedConfig({ mode, sidecar: paths?.config ?? noSidecar, inline, saved: stored?.ok ? stored.value : undefined });
102
+ const script = config.model.protocol === "scripted" ? await (options.scenarioLoader ?? loadScenario)(config.model.script) : undefined;
103
+ const credential = config.model.protocol === "openrouter" ? resolveCredential(config.model, options.environment ?? process.env) : undefined;
104
+ const compatibilityKey = script ? scriptedCompatibilityKey(script.modelDigest, config.system)
105
+ : createHash("sha256").update(JSON.stringify([config.system, config.model.protocol === "openrouter" && config.model.model,
106
+ [...BUILTINS, notifyChannelDefinition].map(tool => tool.name)])).digest("hex");
107
+ if (mode === "create" && paths) mkdirSync(paths.directory, { recursive: true });
108
+ const opened = adapter.open({ mode, identity: { sessionId, compatibilityKey }, config, requiredScriptDigest: script?.modelDigest });
109
+ if (!opened.ok) {
110
+ const code = opened.error.code;
111
+ throw new SessionOpenError(code === "not_found" || code === "already_exists" || code === "owner_conflict" || code === "incompatible" || code === "invalid_config" ? code : "storage_failure", opened.error.message);
112
+ }
113
+ const storage = options.fault || options.snapshotLog ? withFaults(opened.value, point => {
114
+ if (point === "snapshot" && options.snapshotLog) appendFileSync(options.snapshotLog, "snapshot\n");
115
+ hit(point);
116
+ }) : opened.value;
117
+ const record = createRecordTool(options.effects), hold = createHoldTool(options.effects);
118
+ const executeTool: ExecuteTool = async (call, signal) => {
119
+ const result = await (call.name === "record" ? record(call, signal) : call.name === "hold" ? hold(call, signal) : executeEcho(call, signal));
120
+ hit("tool");
121
+ return result;
122
+ };
123
+ const revisions = new Map<string, number>();
124
+ const session = createSession({
125
+ ...(script && options.reminderTime !== undefined && Number.isSafeInteger(options.reminderTime)
126
+ ? { reminderClock: { ...wallReminderClock, now: () => options.reminderTime! } } : {}), ...(options.requests ? { captureContext: ({ context }: import("./contracts/context.ts").ContextCapture) =>
127
+ revisions.set(context.channelId, context.timelineRevision) } : {}), systemPrompt: config.system, config, storage, ...(catalog ? { catalog } : {}), configureTurn(turn) {
128
+ if (config.model.protocol === "openrouter") {
129
+ const model = (options.providerFactory ?? openRouter)(credential!, config.model.model);
130
+ if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => openRouterAttempt(credential!, config.model.protocol === "openrouter" ? config.model.model : "") });
131
+ return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
132
+ }
133
+ const model: Model = async () => { throw new Error("Scripted model requires a reserved attempt"); };
134
+ bindModelAttempt(model, { scripted: true, ...(options.modelTimeoutMs === undefined ? {} : { settings: { timeoutMs: options.modelTimeoutMs } }), create: (step, ordinal) => {
135
+ const next = scenarioAttempt(script!, turn.channelId, step!);
136
+ return async function* (request, signal) {
137
+ if (options.attempts) appendFileSync(options.attempts, `${JSON.stringify({ channel: turn.channelId, turnId: turn.turnId, step, ordinal, itemIds: request.takenItemIds })}\n`);
138
+ if (options.captureRequests) {
139
+ const requests = models.get(turn.channelId) ?? [];
140
+ requests.push(structuredClone(request));
141
+ models.set(turn.channelId, requests);
142
+ }
143
+ if (options.requests) appendFileSync(options.requests, `${JSON.stringify({ channel: turn.channelId, turnId: turn.turnId, revision: revisions.get(turn.channelId), messages: request.messages, tools: request.tools.map(tool => tool.name) })}\n`);
144
+ if (options.stallChannel === turn.channelId && step === 0) {
145
+ yield { type: "accepted" }; yield { type: "usage", usage: { inputTokens: 7 } };
146
+ yield { type: "text_delta", text: "Partial reply" };
147
+ if (!signal.aborted) await new Promise<void>(resolve => signal.addEventListener("abort", () => resolve(), { once: true }));
148
+ return;
149
+ }
150
+ let streamed = false;
151
+ for await (const event of next(request, signal)) {
152
+ if (event.type === "text_delta") streamed = true;
153
+ if (!streamed && options.streamResponses && event.type === "response" && event.response.content)
154
+ yield { type: "text_delta", text: event.response.content };
155
+ yield event;
156
+ }
157
+ };
158
+ } });
159
+ return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
160
+ } });
161
+ return { session, config, close() { opened.value.close(); }, commitConfig() {
162
+ const saved = storage.saveConfig(config);
163
+ if (!saved.ok && saved.error.code !== "incompatible") throw new SessionOpenError("storage_failure", saved.error.message);
164
+ }, exportArchive: () => storage.exportArchive() };
165
+ }, { durable, functions: true, limits: options.limits, transferDirectory: durable ? options.home ?? options.transfers ?? mkdtempSync(join(tmpdir(), "harness-transfers-")) : undefined,
166
+ importArchive(payload, sessionId) {
167
+ let createdDirectory: string | undefined;
168
+ try {
169
+ validateSessionPayload(payload);
170
+ if (options.home) {
171
+ const directory = managedSessionPaths(sessionId, options.home).directory;
172
+ if (!existsSync(directory)) { mkdirSync(directory, { recursive: true }); createdDirectory = directory; }
173
+ }
174
+ const result = locate(sessionId).importSessionFile(payload, { sessionId });
175
+ if (!result.ok && createdDirectory) { try { rmdirSync(createdDirectory); } catch { /* Keep an occupied directory. */ } }
176
+ return result;
177
+ }
178
+ catch (error) {
179
+ if (createdDirectory) { try { rmdirSync(createdDirectory); } catch { /* Keep an occupied directory. */ } }
180
+ return { ok: false, error: { code: (error as { code?: string }).code === "invalid_archive" ? "invalid_archive" : "invalid_input", message: String(error) } };
181
+ }
182
+ } });
183
+ return { server, models };
184
+ }
185
+
186
+ export function createInProcessHarness(options?: ScriptedServerOptions) {
187
+ const { server, models } = createScriptedServer(options);
188
+ const client = new HarnessClient(createInProcessTransport(server));
189
+ return { client, models, server, close: () => { client.close(); server.dispose(); } };
190
+ }
@@ -0,0 +1,66 @@
1
+ import type { ManagedConfig, ToolDecision, ToolPolicy } from "../contracts/config-permissions.ts";
2
+
3
+ /** The upgrade preserves the behavior of sessions created before policies existed. */
4
+ export const LEGACY_POLICY = "__legacy_allow";
5
+ export class ConfigError extends Error {
6
+ constructor(readonly field: string, message: string) { super(`${field}: ${message}`); }
7
+ }
8
+ const fail = (field: string, message: string): never => { throw new ConfigError(field, message); };
9
+ const record = (value: unknown, field: string): Record<string, unknown> => {
10
+ if (!value || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return fail(field, "expected an object");
11
+ return value as Record<string, unknown>;
12
+ };
13
+ const keys = (value: Record<string, unknown>, allowed: string[], field: string) => {
14
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(`${field}.${key}`, "unknown field");
15
+ };
16
+ const name = (value: unknown, field: string): string => typeof value === "string" && value.trim() ? value : fail(field, "expected a nonempty string");
17
+ const decision = (value: unknown, field: string): ToolDecision => value === "allow" || value === "ask" || value === "deny" ? value : fail(field, "expected allow, ask or deny");
18
+
19
+ /** Validate without side effects. Only explicitly requested legacy imports may
20
+ * fill absent policy fields; partly specified modern configs are invalid. */
21
+ export function validateManagedConfig(input: unknown, legacy = false): ManagedConfig {
22
+ const raw = record(input, "config"); keys(raw, ["version", "system", "model", "defaultPolicy", "policies", "timelineTools", "limits"], "config");
23
+ if (raw.version !== 1) fail("config.version", "expected version 1");
24
+ if (typeof raw.system !== "string") fail("config.system", "expected a string");
25
+ const model = record(raw.model, "config.model");
26
+ let selectedModel: ManagedConfig["model"];
27
+ if (model.protocol === "scripted") {
28
+ keys(model, ["protocol", "script"], "config.model");
29
+ selectedModel = { protocol: "scripted", script: name(model.script, "config.model.script") };
30
+ } else if (model.protocol === "openrouter") {
31
+ keys(model, ["protocol", "model", "apiKeyEnv"], "config.model");
32
+ const reference = model.apiKeyEnv === undefined ? "OPENROUTER_API_KEY" : name(model.apiKeyEnv, "config.model.apiKeyEnv");
33
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) fail("config.model.apiKeyEnv", "expected an environment variable name");
34
+ selectedModel = { protocol: "openrouter", model: model.model === undefined ? "deepseek/deepseek-v4.1-flash" : name(model.model, "config.model.model"), apiKeyEnv: reference };
35
+ } else return fail("config.model.protocol", "expected scripted or openrouter");
36
+ const isLegacy = legacy && raw.defaultPolicy === undefined && raw.policies === undefined;
37
+ const defaultPolicy = isLegacy ? LEGACY_POLICY : name(raw.defaultPolicy, "config.defaultPolicy");
38
+ const policiesInput = isLegacy ? { [LEGACY_POLICY]: { fallback: "allow", tools: {} } } : record(raw.policies, "config.policies");
39
+ const policies: Record<string, ToolPolicy> = Object.create(null);
40
+ for (const [policyName, rawPolicy] of Object.entries(policiesInput)) {
41
+ name(policyName, "config.policies");
42
+ const field = `config.policies.${policyName}`, policy = record(rawPolicy, field);
43
+ keys(policy, ["fallback", "tools"], field);
44
+ const toolInput = record(policy.tools, `${field}.tools`), tools: Record<string, ToolDecision> = Object.create(null);
45
+ for (const [tool, rule] of Object.entries(toolInput)) { name(tool, `${field}.tools`); tools[tool] = decision(rule, `${field}.tools.${tool}`); }
46
+ policies[policyName] = { fallback: decision(policy.fallback, `${field}.fallback`), tools };
47
+ }
48
+ if (!Object.hasOwn(policies, defaultPolicy)) fail("config.defaultPolicy", `unknown policy ${defaultPolicy}`);
49
+ if (raw.timelineTools !== undefined && typeof raw.timelineTools !== "boolean") fail("config.timelineTools", "expected a boolean");
50
+ let limits: ManagedConfig["limits"];
51
+ if (raw.limits !== undefined) {
52
+ const value = record(raw.limits, "config.limits");
53
+ keys(value, ["unattendedTurns"], "config.limits");
54
+ if (typeof value.unattendedTurns !== "number" || !Number.isSafeInteger(value.unattendedTurns) || value.unattendedTurns < 1)
55
+ return fail("config.limits.unattendedTurns", "expected a positive safe integer");
56
+ limits = { unattendedTurns: value.unattendedTurns };
57
+ }
58
+ return { ...(limits ? { limits } : {}), ...(typeof raw.timelineTools === "boolean" ? { timelineTools: raw.timelineTools } : {}), version: 1, system: raw.system as string, model: selectedModel, defaultPolicy, policies };
59
+ }
60
+
61
+ /** Resolve only at execution open, never during validation or import. */
62
+ export function resolveCredential(model: Extract<ManagedConfig["model"], { protocol: "openrouter" }>, environment: Record<string, string | undefined>): string {
63
+ const value = environment[model.apiKeyEnv];
64
+ if (!value) return fail(`config.model.apiKeyEnv`, `environment variable ${model.apiKeyEnv} is missing or empty`);
65
+ return value;
66
+ }
@@ -0,0 +1,7 @@
1
+ import { SESSION_INPUT_MAX_BYTES, type IntakeLimit } from "../contracts/input-limits.ts";
2
+
3
+ /** Default initial take used by the scheduler and routine wake decision. */
4
+ export const SESSION_INTAKE_LIMITS: Readonly<IntakeLimit> = {
5
+ maxTakenTextBytes: SESSION_INPUT_MAX_BYTES,
6
+ maxTakenItems: 16,
7
+ };
@@ -0,0 +1,41 @@
1
+ /** JSON.parse discards duplicate keys. Reject them while reading config and
2
+ * protocol inputs so a later field cannot silently replace a reviewed one. */
3
+ export class DuplicateJsonField extends SyntaxError {
4
+ constructor(readonly field: string) { super(`Duplicate field: ${field}`); }
5
+ }
6
+ export function parseUniqueJson(source: string): unknown {
7
+ const parsed: unknown = JSON.parse(source);
8
+ let at = 0;
9
+ const space = () => { while (/[\t\n\r ]/.test(source[at] ?? "\0")) at++; };
10
+ const string = () => {
11
+ const start = at++;
12
+ while (at < source.length) {
13
+ const c = source[at++];
14
+ if (c === "\\") at++;
15
+ else if (c === '"') return JSON.parse(source.slice(start, at)) as string;
16
+ }
17
+ throw new SyntaxError("Unterminated string");
18
+ };
19
+ const value = (depth: number, path: string): void => {
20
+ if (depth > 128) throw new SyntaxError("JSON nesting limit exceeded");
21
+ space(); const c = source[at];
22
+ if (c === '"') { string(); return; }
23
+ if (c === "{") {
24
+ at++; space(); const keys = new Set<string>();
25
+ if (source[at] === "}") { at++; return; }
26
+ for (;;) {
27
+ space(); const key = string(), field = path ? `${path}.${key}` : key;
28
+ if (keys.has(key)) throw new DuplicateJsonField(field); keys.add(key);
29
+ space(); at++; value(depth + 1, field); space();
30
+ if (source[at++] === "}") return;
31
+ }
32
+ }
33
+ if (c === "[") {
34
+ at++; space(); if (source[at] === "]") { at++; return; }
35
+ for (;;) { value(depth + 1, path); space(); if (source[at++] === "]") return; }
36
+ }
37
+ while (at < source.length && !/[\s,\]}]/.test(source[at]!)) at++;
38
+ };
39
+ value(0, "");
40
+ return parsed;
41
+ }
@@ -0,0 +1,3 @@
1
+ export function messagePosition(sessionId: string, channelId: string, seq: number): string {
2
+ return Buffer.from(JSON.stringify([sessionId, channelId, seq])).toString("base64url");
3
+ }
@@ -0,0 +1,44 @@
1
+ import type { AgentReminderSchedule, ReminderLimits } from "../contracts/reminders.ts";
2
+
3
+ export const REMINDER_LIMITS: Readonly<ReminderLimits> = Object.freeze({
4
+ minLeadMs: 120_000,
5
+ minIntervalMs: 600_000,
6
+ maxActiveRoutinesPerChannel: 0,
7
+ minExpiryGraceMs: 300_000,
8
+ maxExpiryGraceMs: 86_400_000,
9
+ expiryMultiplier: 2,
10
+ });
11
+
12
+ export function reminderInstant(value: string): number | undefined {
13
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)) return;
14
+ const instant = Date.parse(value);
15
+ if (!Number.isFinite(instant)) return;
16
+ const canonical = value.replace(/(?:\.(\d{1,3}))?Z$/, (_, fraction?: string) => `.${(fraction ?? "").padEnd(3, "0")}Z`);
17
+ return new Date(instant).toISOString() === canonical ? instant : undefined;
18
+ }
19
+
20
+ export function resolveAgentReminder(schedule: AgentReminderSchedule, now: number): string | undefined {
21
+ if ("at" in schedule) return reminderInstant(schedule.at) === undefined ? undefined : schedule.at;
22
+ const duration = /^([1-9]\d*)([mhd])$/.exec(schedule.in);
23
+ if (!duration) return;
24
+ const multiplier = duration[2] === "m" ? 60_000 : duration[2] === "h" ? 3_600_000 : 86_400_000;
25
+ const instant = now + Number(duration[1]) * multiplier;
26
+ if (!Number.isSafeInteger(instant) || instant > 253_402_300_799_999) return;
27
+ return new Date(instant).toISOString();
28
+ }
29
+
30
+ export function normalizeReminderSchedule(at: string, acceptedAt: string, expiresAfter: number | null | undefined, now: number) {
31
+ const due = reminderInstant(at), anchor = reminderInstant(acceptedAt);
32
+ if (due === undefined || anchor === undefined || anchor > now + 30_000 || due - anchor < REMINDER_LIMITS.minLeadMs) return;
33
+ const grace = expiresAfter === undefined
34
+ ? Math.min(REMINDER_LIMITS.maxExpiryGraceMs, Math.max(REMINDER_LIMITS.minExpiryGraceMs, (due - anchor) * REMINDER_LIMITS.expiryMultiplier))
35
+ : expiresAfter;
36
+ if (grace !== null && (!Number.isSafeInteger(grace) || grace < REMINDER_LIMITS.minExpiryGraceMs ||
37
+ grace > REMINDER_LIMITS.maxExpiryGraceMs || due + grace > 253_402_300_799_999)) return;
38
+ return {
39
+ schedule: { at: new Date(due).toISOString() },
40
+ acceptedAt: new Date(anchor).toISOString(),
41
+ expiresAfter: grace,
42
+ expiresAt: grace === null ? null : new Date(due + grace).toISOString(),
43
+ };
44
+ }
@@ -0,0 +1,40 @@
1
+ /** A small JSON Schema check for tool arguments (decision 0021). It covers what
2
+ * a function's `parameters` normally use: `type`, `properties`, `required`,
3
+ * `additionalProperties`, `enum`, `const`, `items`, and numeric and length
4
+ * bounds. Keywords it does not know are ignored, so a schema is never stricter
5
+ * here than its author wrote. Returns the first problem, or undefined. */
6
+ export function schemaProblem(schema: unknown, value: unknown, path = "arguments"): string | undefined {
7
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return undefined;
8
+ const rule = schema as Record<string, unknown>;
9
+ const kind = (item: unknown) => item === null ? "null" : Array.isArray(item) ? "array" : Number.isInteger(item) ? "integer" : typeof item;
10
+ if (rule.type !== undefined) {
11
+ const allowed = Array.isArray(rule.type) ? rule.type : [rule.type], actual = kind(value);
12
+ if (!allowed.some(type => type === actual || (type === "number" && actual === "integer"))) return `${path} must be ${allowed.join(" or ")}`;
13
+ }
14
+ if (Array.isArray(rule.enum) && !rule.enum.some(option => JSON.stringify(option) === JSON.stringify(value))) return `${path} must be one of ${JSON.stringify(rule.enum)}`;
15
+ if ("const" in rule && JSON.stringify(rule.const) !== JSON.stringify(value)) return `${path} must be ${JSON.stringify(rule.const)}`;
16
+ if (typeof value === "number") {
17
+ if (typeof rule.minimum === "number" && value < rule.minimum) return `${path} must be at least ${rule.minimum}`;
18
+ if (typeof rule.maximum === "number" && value > rule.maximum) return `${path} must be at most ${rule.maximum}`;
19
+ }
20
+ if (typeof value === "string") {
21
+ if (typeof rule.minLength === "number" && value.length < rule.minLength) return `${path} must have at least ${rule.minLength} characters`;
22
+ if (typeof rule.maxLength === "number" && value.length > rule.maxLength) return `${path} must have at most ${rule.maxLength} characters`;
23
+ }
24
+ if (Array.isArray(value)) {
25
+ for (let index = 0; index < value.length; index++) {
26
+ const problem = schemaProblem(rule.items, value[index], `${path}[${index}]`);
27
+ if (problem) return problem;
28
+ }
29
+ } else if (value && typeof value === "object") {
30
+ const object = value as Record<string, unknown>;
31
+ const properties = rule.properties && typeof rule.properties === "object" ? rule.properties as Record<string, unknown> : {};
32
+ for (const name of Array.isArray(rule.required) ? rule.required : []) if (!Object.hasOwn(object, name)) return `${path}.${name} is required`;
33
+ for (const [name, item] of Object.entries(object)) {
34
+ if (Object.hasOwn(properties, name)) { const problem = schemaProblem(properties[name], item, `${path}.${name}`); if (problem) return problem; }
35
+ else if (rule.additionalProperties === false) return `${path}.${name} is not an accepted field`;
36
+ else { const problem = schemaProblem(rule.additionalProperties, item, `${path}.${name}`); if (problem) return problem; }
37
+ }
38
+ }
39
+ return undefined;
40
+ }
@@ -0,0 +1,72 @@
1
+ import { isTimelineTool } from "./timeline-tool-names.ts";
2
+ import type { TimelineEntry } from "../contracts/storage.ts";
3
+ import type { RetrievedMessage, TimelineSearch } from "../contracts/timeline-retrieval.ts";
4
+
5
+ export const timelineMessageId = (entry: TimelineEntry) => entry.itemId ? `item:${entry.itemId}` : entry.messageId ?? String(entry.seq);
6
+
7
+ export function retrievalMessage(entry: TimelineEntry): RetrievedMessage | undefined {
8
+ const message = entry.message;
9
+ const participant = entry.kind === "participant_message" && message.role === "user";
10
+ if (!participant && (message.role !== "assistant" || !message.content)) return;
11
+ const text = participant ? message.content.slice(`Participant: ${JSON.stringify(entry.from)}\n\n`.length) : message.content!;
12
+ return { seq: entry.seq, message_id: timelineMessageId(entry), channel: entry.channelId, sender: entry.from, at: entry.at, text };
13
+ }
14
+
15
+ export function timelineTokens(text: string) {
16
+ return Array.from(text.normalize("NFC").matchAll(/[\p{L}\p{M}\p{N}]+/gu), match => ({
17
+ exact: match[0], folded: match[0].toLowerCase().normalize("NFC"),
18
+ }));
19
+ }
20
+
21
+ export const timelineTokenLimit = 256;
22
+ export const timelineBytes = (text: string) => Buffer.byteLength(text);
23
+ export const encodedTimelineToken = (word: string) => `x${Buffer.from(word).toString("hex")}`;
24
+
25
+ export function timelineIndexText(text: string): string {
26
+ return timelineTokens(text).flatMap(({ folded }) => timelineBytes(folded) <= timelineTokenLimit
27
+ ? [encodedTimelineToken(folded)] : []).join(" ");
28
+ }
29
+
30
+ export function timelineQuery(input: TimelineSearch) {
31
+ if (timelineBytes(input.query) > 1024) return;
32
+ const words = timelineTokens(input.query);
33
+ if (words.length === 0 || words.length > 32 ||
34
+ words.some(({ exact, folded }) => timelineBytes(exact) > timelineTokenLimit || timelineBytes(folded) > timelineTokenLimit)) return;
35
+ return words;
36
+ }
37
+
38
+ /** Every eligible start counts, including overlapping phrase matches. */
39
+ export function scoreTimeline(words: readonly string[], query: readonly string[], phrase: boolean): { score: number; first: number } {
40
+ const unique = new Set(query);
41
+ let score = 0, first = -1;
42
+ for (let index = 0; index < words.length; index++) {
43
+ const qualifies = phrase ? query.every((word, offset) => words[index + offset] === word) : unique.has(words[index]!);
44
+ if (!qualifies) continue;
45
+ if (first < 0) first = index;
46
+ score++;
47
+ }
48
+ if (!phrase) {
49
+ const present = new Set(words);
50
+ if ([...unique].some(word => !present.has(word))) return { score: 0, first: -1 };
51
+ }
52
+ return { score: Math.min(score, 255), first };
53
+ }
54
+
55
+ /** Historical candidates already contain only conversation messages. Strip
56
+ * retrieval calls from text-bearing mixed assistant records before charging. */
57
+ export function historicalRetrievalProjection(message: TimelineEntry["message"]): TimelineEntry["message"] {
58
+ if (message.role !== "assistant" || !message.calls.some(call => isTimelineTool(call.name))) return message;
59
+ return { ...message, calls: message.calls.filter(call => !isTimelineTool(call.name)) };
60
+ }
61
+
62
+ /** Register retrieval calls and decide whether this row spends a historical
63
+ * candidate slot. Other activity keeps its existing recent-range semantics. */
64
+ export function historicalCandidate(
65
+ message: TimelineEntry["message"], register: (callId: string) => void, contains: (callId: string) => boolean,
66
+ ): boolean {
67
+ if (message.role === "tool") return !contains(message.callId);
68
+ if (message.role !== "assistant") return true;
69
+ const retrieval = message.calls.filter(call => isTimelineTool(call.name));
70
+ for (const call of retrieval) register(call.id);
71
+ return !!message.content || !retrieval.length || retrieval.length !== message.calls.length;
72
+ }
@@ -0,0 +1,3 @@
1
+ /** Reserved names also identify retrieval exchanges during history projection. */
2
+ export const timelineToolNames = ["search_timeline", "read_message"] as const;
3
+ export const isTimelineTool = (name: string): boolean => timelineToolNames.some(value => value === name);
@@ -0,0 +1,20 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["ESNext"],
4
+ "target": "ESNext",
5
+ "module": "Preserve",
6
+ "moduleResolution": "bundler",
7
+ "moduleDetection": "force",
8
+ "allowImportingTsExtensions": true,
9
+ "verbatimModuleSyntax": true,
10
+ "noEmit": true,
11
+ "strict": true,
12
+ "skipLibCheck": true,
13
+ "noUncheckedIndexedAccess": true,
14
+ "noFallthroughCasesInSwitch": true,
15
+ "noImplicitOverride": true,
16
+ "types": ["bun"]
17
+ },
18
+ "include": ["**/*.ts"],
19
+ "exclude": ["node_modules", ".res"]
20
+ }
@@ -1,3 +1,4 @@
1
+ import type { WorkerEvent } from "../orchestrator/contracts.ts";
1
2
  import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
2
3
  import {
3
4
  isConversationRecordKind,
@@ -20,26 +21,30 @@ export interface ConversationRecordCommittedEvent {
20
21
  readonly record: ConversationRecord;
21
22
  }
22
23
 
23
- export type AgentEvent = ConversationRecordCommittedEvent;
24
+ export type AgentEvent = ConversationRecordCommittedEvent | WorkerEvent;
24
25
 
25
- export interface AgentEventNotification {
26
+ export interface AgentEventNotification<Event extends AgentEvent = ConversationRecordCommittedEvent> {
26
27
  /** Process-local order assigned before subscriber filtering. Not a durable cursor. */
27
28
  readonly deliverySequence: number;
28
- /** Time at which the committed record was offered to listeners. */
29
+ /** Time at which the event was offered to listeners. */
29
30
  readonly emittedAt: string;
30
31
  readonly agentSessionId: AgentSessionId;
31
- readonly event: AgentEvent;
32
+ readonly event: Event;
32
33
  }
33
34
 
35
+ export type WorkerEventNotification = AgentEventNotification<WorkerEvent>;
36
+
34
37
  export type AgentEventListener = (notification: AgentEventNotification) => void;
35
38
 
36
39
  export interface AgentEventBus extends Subscribable<AgentEventNotification> {
37
40
  subscribe(listener: AgentEventListener, options?: AgentEventSubscriptionOptions): Unsubscribe;
41
+ /** Observe process-local worker facts independently of committed-record filters. */
42
+ subscribeWorkers(listener: (notification: WorkerEventNotification) => void): Unsubscribe;
38
43
  }
39
44
 
40
45
  export interface AgentEventBusOptions {
41
46
  readonly agentSessionId: AgentSessionId;
42
- readonly onListenerError?: (failure: SubscriptionListenerError<AgentEventNotification>) => void;
47
+ readonly onListenerError?: (failure: SubscriptionListenerError<AgentEventNotification<AgentEvent>>) => void;
43
48
  }
44
49
 
45
50
  type RecordFilter = (record: ConversationRecord) => boolean;
@@ -96,12 +101,15 @@ function compileRecordKinds(
96
101
  */
97
102
  export class CommittedRecordEventBus implements AgentEventBus {
98
103
  private readonly hub: SubscriptionHub<AgentEventNotification>;
104
+ private readonly workerHub: SubscriptionHub<WorkerEventNotification>;
105
+ private workerSubscriptions = 0;
99
106
  private deliverySequence = 0;
100
107
  private subscriptionCount = 0;
101
108
  private closed = false;
102
109
 
103
110
  constructor(private readonly options: AgentEventBusOptions) {
104
- this.hub = new SubscriptionHub(options.onListenerError);
111
+ this.hub = new SubscriptionHub<AgentEventNotification>(options.onListenerError);
112
+ this.workerHub = new SubscriptionHub<WorkerEventNotification>(options.onListenerError);
105
113
  }
106
114
 
107
115
  subscribe(listener: AgentEventListener, options: AgentEventSubscriptionOptions = {}): Unsubscribe {
@@ -123,6 +131,34 @@ export class CommittedRecordEventBus implements AgentEventBus {
123
131
  };
124
132
  }
125
133
 
134
+ subscribeWorkers(listener: (notification: WorkerEventNotification) => void): Unsubscribe {
135
+ if (typeof listener !== "function") throw new TypeError("worker event subscription listener must be a function");
136
+ this.workerSubscriptions++;
137
+ const unsubscribe = this.workerHub.subscribe(notification => listener(notification));
138
+ let subscribed = true;
139
+ return () => {
140
+ if (!subscribed) return;
141
+ subscribed = false;
142
+ this.workerSubscriptions--;
143
+ unsubscribe();
144
+ };
145
+ }
146
+
147
+ /** @internal Publish a worker fact after the corresponding state change. */
148
+ publishWorker(event: WorkerEvent): void {
149
+ if (this.closed || this.workerSubscriptions === 0) return;
150
+ this.workerHub.emit(this.envelope(event));
151
+ }
152
+
153
+ private envelope<Event extends AgentEvent>(event: Event): AgentEventNotification<Event> {
154
+ return Object.freeze({
155
+ deliverySequence: ++this.deliverySequence,
156
+ emittedAt: new Date().toISOString(),
157
+ agentSessionId: this.options.agentSessionId,
158
+ event: Object.freeze(event),
159
+ });
160
+ }
161
+
126
162
  /** @internal Publish records whose persistence transaction has already committed. */
127
163
  publish(records: readonly ConversationRecord[]): void {
128
164
  // No subscribers means no notification to allocate; the delivery sequence is
@@ -131,18 +167,7 @@ export class CommittedRecordEventBus implements AgentEventBus {
131
167
  const ordered = records.length > 1
132
168
  ? [...records].sort((left, right) => left.sequence - right.sequence)
133
169
  : records;
134
- for (const record of ordered) {
135
- const notification: AgentEventNotification = Object.freeze({
136
- deliverySequence: (this.deliverySequence += 1),
137
- emittedAt: new Date().toISOString(),
138
- agentSessionId: this.options.agentSessionId,
139
- event: Object.freeze({
140
- kind: "conversation_record_committed" as const,
141
- record,
142
- }),
143
- });
144
- this.hub.emit(notification);
145
- }
170
+ for (const record of ordered) this.hub.emit(this.envelope({ kind: "conversation_record_committed", record }));
146
171
  }
147
172
 
148
173
  /** @internal Prevent further publication and drop every subscription. */
@@ -150,5 +175,6 @@ export class CommittedRecordEventBus implements AgentEventBus {
150
175
  this.closed = true;
151
176
  this.subscriptionCount = 0;
152
177
  this.hub.clear();
178
+ this.workerHub.clear();
153
179
  }
154
180
  }
@@ -11,6 +11,7 @@ export type {
11
11
  AgentEventBus,
12
12
  AgentEventListener,
13
13
  AgentEventNotification,
14
+ WorkerEventNotification,
14
15
  AgentEventSubscriptionOptions,
15
16
  ConversationRecordCommittedEvent,
16
17
  } from "./agent-event-bus.ts";