@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,597 @@
1
+ import type { InspectionStorageReads } from "./inspection.ts";
2
+ import type { IntakeLimit } from "./input-limits.ts";
3
+ import type { OperatorStorageReads } from "./operator-controls.ts";
4
+ import type { ModelCallStore } from "./model-execution.ts";
5
+ import type { ItemKind, ItemMilestone } from "./agent.ts";
6
+ import type { ContextEntry, InferenceStorageReads } from "./context.ts";
7
+ import type { Message } from "./loop.ts";
8
+
9
+ /** Storage contract revision 4 (decisions 0013, 0014, 0016).
10
+ * One owner process, one session per location. Every method is synchronous and
11
+ * is one atomic transaction, so the owner's calls are totally ordered: any two
12
+ * operations (for example an acceptance and a finish) commit in one definite
13
+ * order and each observes the other's full effect or none of it. No transaction
14
+ * spans inference or tool execution. */
15
+
16
+ /** Expected failures never require callers to inspect SQLite or exception text. */
17
+ export type StorageErrorCode =
18
+ | "already_exists" | "not_found" | "owner_conflict" | "incompatible"
19
+ | "invalid_input" | "invalid_config" | "invalid_state" | "invalid_policy" | "closed"
20
+ /** The item ID was accepted earlier with a different payload signature. */
21
+ | "item_conflict"
22
+ /** The session lifecycle does not admit this work (suspending/suspended). */
23
+ | "not_running"
24
+ /** The channel's own suspension (suspending/suspended) does not admit or run this work. */
25
+ | "channel_suspended"
26
+ /** The channel ID is retired (deleted); it is reserved and never reused. */
27
+ | "channel_retired"
28
+ /** Deletion refused: the channel has an active or checkpointed turn, or pending input. */
29
+ | "channel_busy"
30
+ /** Export refused: active or pending work exists and the session is not suspended. */
31
+ | "busy"
32
+ | "invalid_archive"
33
+ | "serialization_error" | "storage_failure" | "transfer_limit" | "invalid_cursor";
34
+
35
+ /** A failed mutation leaves no partial domain changes. Do not retry blindly. */
36
+ export interface StorageError { code: StorageErrorCode; message: string }
37
+
38
+ /** A success returns only after commit and names the storage revision that
39
+ * includes it (the current revision for reads and no-op calls). A failure
40
+ * exposes no success value and commits nothing. */
41
+ export type StorageResult<T> = { ok: true; value: T; revision: number } | { ok: false; error: StorageError };
42
+
43
+ /** Supplied again on every open. Contains no secrets or executable implementations. */
44
+ export interface StorageIdentity {
45
+ sessionId: string;
46
+ /** Caller-defined identity of compatible prompt, model and tool configuration.
47
+ * The key given to `create` is stored once. A different key on `open` does not
48
+ * fail and is never written by open: the session stays readable and exportable.
49
+ * This owner's key is recorded on each turn it begins, and compared by exact
50
+ * equality with every checkpointed turn's key on resume. Items that were never
51
+ * taken use the key of the owner that later begins their turn. */
52
+ compatibilityKey: string;
53
+ }
54
+
55
+ /** No implicit create-on-open or overwrite. Location is configured on the adapter. */
56
+ export interface StorageOpenOptions {
57
+ mode: "create" | "open";
58
+ identity: StorageIdentity;
59
+ /** Opt-in scripted identity check. Create persists identity.compatibilityKey
60
+ * as scripted-jsonl-v1:<digest>:<systemHash>, with both hashes lowercase
61
+ * 64-character hexadecimal SHA-256. The digest segment must equal this value.
62
+ * Under ownership, open matches that segment of the stored key exactly.
63
+ * Untagged, malformed, or mismatched keys return incompatible without writes,
64
+ * before format upgrade, recovery, attempt repair, or any reservation.
65
+ * Existing checkpoint comparison uses the entire key, including systemHash.
66
+ * Changing only the system preserves open but blocks checkpoint resume.
67
+ * Callers that omit this option retain the existing behavior. */
68
+ requiredScriptDigest?: string;
69
+ /** Validated policies for this owner; legacy callers use the legacy policy. */
70
+ config?: import("./config-permissions.ts").ManagedConfig;
71
+ }
72
+
73
+ /** `suspended` is committed only by completeSuspend; it is the sole state that
74
+ * preserves checkpoints across reopen. */
75
+ export type SessionLifecycle = "running" | "suspending" | "suspended";
76
+
77
+ /** Timestamps are UTC strings assigned by storage; never use them as ordering keys. */
78
+ export interface StoredSession {
79
+ sessionId: string;
80
+ /** Storage contract/data format revision, distinct from RPC and archive versions.
81
+ * Revision 5 stores model calls and script reservations. Formats 2–4 upgrade on open. */
82
+ formatVersion: 6 | 7 | 8;
83
+ createdAt: string;
84
+ lifecycle: SessionLifecycle;
85
+ /** The key supplied at create. Immutable; open never rewrites it. */
86
+ compatibilityKey: string;
87
+ }
88
+
89
+ /** The channel's own lifecycle, independent of the session's and of its turn
90
+ * status (decision 0014). `open`: admits input; it may be idle or have a turn.
91
+ * `suspending`: closed to input and to taking pending items while its running
92
+ * turn finishes the current iteration; it always has a running turn.
93
+ * `suspended`: committed and durable; admits no input, takes no pending items
94
+ * and starts nothing, and may hold a checkpointed turn. `retired`: deleted; the
95
+ * ID is reserved forever and the timeline is kept. `retired` is final. */
96
+ export type ChannelLifecycle = "open" | "suspending" | "suspended" | "retired";
97
+
98
+ /** A channel remains available for new turns after failure or interruption. */
99
+ export interface StoredChannel {
100
+ channelId: string;
101
+ policy?: string;
102
+ /** Optional label; never an identity. 1..200 characters after trimming. */
103
+ displayName?: string;
104
+ lifecycle: ChannelLifecycle;
105
+ /** Derived from the channel's timeline entries: senders that have a timeline
106
+ * entry there, not access rights. A sender whose message is still pending is
107
+ * not listed until take. */
108
+ participantIds: string[];
109
+ }
110
+
111
+ /** Observed caller identity. Participant roles/policies are outside this contract. */
112
+ export interface StoredParticipant { participantId: string }
113
+
114
+ /** New work offered to the durable inbox. `senderId` is a participant ID for a
115
+ * message and `channel:<sourceChannelId>` for a notice. */
116
+ export interface AcceptItem {
117
+ /** Stable caller ID used for deduplication. If omitted, storage assigns
118
+ * `auto:<decimal nextItemNumber>` and increments that counter (first value 1).
119
+ * Accepting a caller ID of the exact form `auto:<n>` with n >= the counter sets
120
+ * the counter to n + 1. The counter is durable and restored by import, so an
121
+ * allocated ID is never issued twice. */
122
+ itemId?: string;
123
+ kind: ItemKind;
124
+ channelId: string;
125
+ senderId: string;
126
+ sourceChannelId?: string;
127
+ /** Trusted participant override; null and omission are equivalent. */
128
+ explicitPolicy?: string | null;
129
+ /** Internal source turn of a notice; never supplied by model arguments. */
130
+ sourceTurnId?: number;
131
+ /** External notice attribution and submitted policy set only. */
132
+ externalSource?: string;
133
+ inheritedPolicyNames?: readonly string[];
134
+ /** Original payload, kept unrendered for the life of the item. */
135
+ text: string;
136
+ }
137
+
138
+ /** An accepted input. While `milestone` is `received` it is pending: in the
139
+ * inbox, outside the timeline and outside every model context. From take onward
140
+ * `turnId`/`entrySeq` are set and never change; the item is never pending again.
141
+ * `withdrawn` is the other terminal state of a pending item: it was never taken,
142
+ * is not pending, has no `turnId`/`entrySeq`, never enters the timeline and is
143
+ * retained for deduplication, so a retry cannot make it pending again. */
144
+ export interface StoredItem extends Required<Pick<AcceptItem, "itemId">>, Omit<AcceptItem, "itemId"> {
145
+ policy?: import("./config-permissions.ts").ItemPolicy;
146
+ /** Lowercase SHA-256 of the UTF-8 identity array in decision 0025.
147
+ * External notices use source and the sorted inherited set. Existing
148
+ * participant and internal notice formulas retain their explicit override. */
149
+ signature: string;
150
+ /** Global sequence position of acceptance; acceptance order within a channel. */
151
+ acceptedSeq: number;
152
+ acceptedAt: string;
153
+ /** Last confirmed milestone. Failure or interruption never lowers it. */
154
+ milestone: ItemMilestone;
155
+ /** Set only when `milestone` is `withdrawn`. */
156
+ withdrawnAt?: string;
157
+ turnId?: number;
158
+ entrySeq?: number;
159
+ }
160
+
161
+ /** A timeline entry. `seq` comes from the session-wide committed sequence and is
162
+ * the entry's stable ID (assistant message ID `String(seq)`); values increase
163
+ * but need not be contiguous. `itemId` is set on entries created by a take. */
164
+ export interface TimelineEntry extends ContextEntry { itemId?: string; /** Reserved model message ID when produced by the call runner. */ messageId?: string }
165
+
166
+ /** Enough to continue at the next step without repeating recorded work. Only
167
+ * references to committed records; no functions, credentials or handles. */
168
+ export interface TurnCheckpoint {
169
+ /** The only resumable boundary: every requested call has a recorded result. */
170
+ nextStep: "inference";
171
+ /** Last timeline seq of the turn when it was checkpointed. */
172
+ afterSeq: number;
173
+ /** Canonical definitions of policies contributed by inputs taken by this turn. */
174
+ policyFingerprint?: string;
175
+ }
176
+
177
+ /** A turn exists only from its first take; there is no queued turn. Failed and
178
+ * interrupted are terminal for the turn and leave the channel usable.
179
+ * `uncertainCallIds` lists recorded calls with no recorded result: their
180
+ * external effect is unknown and they are never executed again by the harness. */
181
+ export type StoredTurnState =
182
+ | { status: "running"; dispatchedCallIds?: string[] }
183
+ | { status: "suspended"; checkpoint: TurnCheckpoint; dispatchedCallIds?: string[] }
184
+ | { status: "completed" }
185
+ | { status: "failed"; reason: string; uncertainCallIds: string[] }
186
+ | { status: "interrupted"; reason: string; uncertainCallIds: string[] };
187
+
188
+ export interface StoredTurn {
189
+ /** Positive safe integer, never reused, increasing in begin order. */
190
+ turnId: number;
191
+ channelId: string;
192
+ /** Every item this turn has taken, in take order. Several IDs may share a turn. */
193
+ itemIds: string[];
194
+ startedSeq: number;
195
+ startedAt: string;
196
+ /** Configuration identity under which the turn began. */
197
+ compatibilityKey: string;
198
+ state: StoredTurnState;
199
+ }
200
+
201
+ /** Items taken by one transaction with the turn link and timeline entries they produced. */
202
+ export interface TurnTake { turn: StoredTurn; items: StoredItem[]; entries: TimelineEntry[] }
203
+
204
+ /** One consistent read at `revision`; records never alias storage or caller objects. */
205
+ export interface StorageSnapshot {
206
+ /** Number identifying this committed state. Increases with every commit. */
207
+ revision: number;
208
+ session: StoredSession;
209
+ channels: StoredChannel[];
210
+ participants: StoredParticipant[];
211
+ /** Ordered by turn ID. */
212
+ turns: StoredTurn[];
213
+ /** Pending, taken and withdrawn items, ordered by acceptedSeq. Retained for
214
+ * deduplication. A withdrawn item has no turn link and no timeline entry; it
215
+ * survives export, import and reopen so a retry cannot revive it. */
216
+ items: StoredItem[];
217
+ /** All entries in increasing seq order, suitable for the context builder. */
218
+ timeline: TimelineEntry[];
219
+ /** Durable call records and each channel's next zero-based scripted step. */
220
+ modelCalls: import("./model-execution.ts").ModelCallSummary[];
221
+ scriptPositions: Record<string, number>;
222
+ /** Decision 0021: names of revocable tools whose grant is revoked, sorted.
223
+ * Absent when none ever was. Carried by export and import. */
224
+ revokedTools?: string[];
225
+ }
226
+
227
+ /** Logical, adapter-independent session copy. JSON-serializable. Versioned
228
+ * independently of `formatVersion`. Version 4 adds model call records and script reservations.
229
+ * Version 5 adds external notices. */
230
+ export interface SessionArchive {
231
+ format: "harness-session";
232
+ archiveVersion: 5 | 6 | 7;
233
+ reminderState?: import("./reminders.ts").ReminderArchiveState;
234
+ exportedAt: string;
235
+ snapshot: StorageSnapshot;
236
+ /** ID allocation state so the copy never reissues a turn ID, seq or item ID. */
237
+ allocation: { nextTurnId: number; nextSeq: number; nextItemNumber: number };
238
+ }
239
+
240
+ /** The archive written by the persistence revision. Import-only: it is read as
241
+ * every channel `open` without a name, no withdrawn items and no retired IDs.
242
+ * Nothing in this revision exports it. */
243
+ export interface SessionArchiveV1 {
244
+ format: "harness-session";
245
+ archiveVersion: 1;
246
+ exportedAt: string;
247
+ snapshot: Omit<StorageSnapshot, "session" | "channels" | "modelCalls" | "scriptPositions"> & {
248
+ session: Omit<StoredSession, "formatVersion"> & { formatVersion: 2 };
249
+ channels: Omit<StoredChannel, "displayName" | "lifecycle">[];
250
+ };
251
+ allocation: SessionArchive["allocation"];
252
+ }
253
+
254
+ /** Import-only logical format from the channel-controls revision. */
255
+ export interface SessionArchiveV2 {
256
+ format: "harness-session"; archiveVersion: 2; exportedAt: string;
257
+ snapshot: Omit<StorageSnapshot, "session" | "modelCalls" | "scriptPositions"> & { session: Omit<StoredSession, "formatVersion"> & { formatVersion: 3 } };
258
+ allocation: SessionArchive["allocation"];
259
+ }
260
+
261
+ /** Import-only logical format from configuration and permissions. */
262
+ export interface SessionArchiveV3 {
263
+ format: "harness-session"; archiveVersion: 3; exportedAt: string;
264
+ snapshot: Omit<StorageSnapshot, "session" | "modelCalls" | "scriptPositions"> & { session: Omit<StoredSession, "formatVersion"> & { formatVersion: 4 } };
265
+ allocation: SessionArchive["allocation"];
266
+ }
267
+
268
+ /** Import-only model execution archive, before external notices. */
269
+ export interface SessionArchiveV4 extends Omit<SessionArchive, "archiveVersion" | "snapshot"> {
270
+ archiveVersion: 4;
271
+ snapshot: Omit<StorageSnapshot, "session"> & { session: Omit<StoredSession, "formatVersion"> & { formatVersion: 5 } };
272
+ }
273
+
274
+ /** Result of `withdrawItem`. The two outcomes are the two sides of the race with
275
+ * take; whichever transaction commits first decides, and the decision is final.
276
+ * `withdrawn` also answers a repeat of an earlier successful withdrawal. */
277
+ export type WithdrawOutcome =
278
+ | { outcome: "withdrawn"; item: StoredItem; repeated: boolean }
279
+ | { outcome: "taken"; item: StoredItem; turnId: number };
280
+
281
+ /** Result of `interruptTurn`. `interrupted: false` changes nothing and returns
282
+ * the turn as it is now: it was already ended, or is checkpointed. */
283
+ export type InterruptOutcome =
284
+ | { interrupted: true; turn: StoredTurn }
285
+ | { interrupted: false; turn: StoredTurn };
286
+
287
+ /** Only the adapter's owner closes this handle; borrowers must not close it. */
288
+ export interface TimelineRetrievalReads {
289
+ searchTimeline(input: import("./timeline-retrieval.ts").TimelineSearch, maxResponseBytes?: number): StorageResult<import("./timeline-retrieval.ts").TimelineSearchResult>;
290
+ readMessage(input: import("./timeline-retrieval.ts").TimelineWindow, maxResponseBytes?: number): StorageResult<import("./timeline-retrieval.ts").TimelineWindowResult>;
291
+ }
292
+
293
+ export interface ReminderStorage {
294
+ scheduleAgentReminder(turnId: number, invocationId: string, schedule: import("./reminders.ts").AgentReminderSchedule | import("./reminders.ts").RoutineSchedule, text: string,
295
+ policyNames: readonly string[], expiresAfter: number | null | undefined, now: number, delivery?: import("./reminders.ts").RoutineDeliveryOptions): StorageResult<{ reminder: import("./reminders.ts").Reminder; created: boolean }>;
296
+ cancelAgentReminder(turnId: number, id: string): StorageResult<{ id: string; alreadyQueued: boolean; changed: boolean }>;
297
+ changeReminder(change: import("./reminders.ts").ReminderChange, now: number): StorageResult<import("./reminders.ts").ReminderChangeResult>;
298
+ readReminder(id: string): StorageResult<import("./reminders.ts").Reminder | undefined>;
299
+ listReminders(input: import("./reminders.ts").ReminderListParams): StorageResult<import("./reminders.ts").ReminderList>;
300
+ reminderWake(): StorageResult<import("./reminders.ts").ReminderWake>;
301
+ fireDueReminders(now: number): StorageResult<Array<{ channel: string; event: import("./reminders.ts").ReminderChannelEvent }>>;
302
+ }
303
+
304
+ export interface SessionStorage extends ModelCallStore, ReminderStorage, TimelineRetrievalReads, OperatorStorageReads, InferenceStorageReads, InspectionStorageReads {
305
+ readSession(): StorageResult<StoredSession>;
306
+ readExecution(): StorageResult<Pick<StorageSnapshot, "revision" | "session" | "channels" | "turns" | "items">>;
307
+ readReadyChannels(intake?: IntakeLimit): StorageResult<{ lifecycle: SessionLifecycle; channels: string[] }>;
308
+ readRevokedTools(): StorageResult<string[]>;
309
+ /** Validated config supplied to this open, copied at bind time; undefined for
310
+ * legacy allow-only opens. Returns a defensive copy. It is independent of
311
+ * saved/imported config and is not retargeted by saveConfig. Failure is not
312
+ * equivalent to absence and must fail session assembly. */
313
+ ownerConfig(): StorageResult<import("./config-permissions.ts").ManagedConfig | undefined>;
314
+ /** Commit that a running turn's own unanswered, not-yet-marked call is being
315
+ * dispatched. Invalid or duplicate marks write nothing; failure cannot invoke
316
+ * the tool or emit started. After success its effect is uncertain until its
317
+ * result commits. This evidence is never an approval grant. */
318
+ markToolDispatched(turnId: number, callId: string): StorageResult<void>;
319
+ /** False when stored policy references cannot be resolved by this owner. */
320
+ unattendedGuard(): StorageResult<number | undefined>;
321
+ executionCompatible(): StorageResult<boolean>;
322
+ /** Imported configuration, or undefined for sessions not imported from a file. */
323
+ importedConfig(): StorageResult<import("./session-file.ts").PortableSessionConfig | undefined>;
324
+ /** Persist the validated configuration used by this owner. */
325
+ saveConfig(config: import("./config-permissions.ts").ManagedConfig): StorageResult<void>;
326
+ /** Durable acceptance (the Received milestone). In order:
327
+ * 1. A known itemId with the same signature returns the original item with
328
+ * `duplicate: true` and commits nothing, in every lifecycle state, for a
329
+ * withdrawn item and after reopen. A different signature is `item_conflict`.
330
+ * 2. Empty routing/content is `invalid_input`. A notice to a channel that has
331
+ * no record (never created or messaged) is `not_found`.
332
+ * 3. A retired channel ID is `channel_retired`, for messages and notices.
333
+ * 4. Session admission: messages need `running`; notices are also admitted
334
+ * while `suspending`. Otherwise `not_running`.
335
+ * 5. Channel admission: a `suspending` or `suspended` channel refuses messages
336
+ * and notices alike with `channel_suspended`. (Step 4 is checked first.)
337
+ * 6. Commit the pending item. A message to an ID with no record also creates
338
+ * its StoredChannel (open, unnamed) and StoredParticipant; `participantIds`
339
+ * is unaffected until take.
340
+ * Nothing is added to the timeline and no turn is created or changed. */
341
+ /** External notice retries compare durable identity before admission or
342
+ * policy validation for new work, through a path that writes nothing. */
343
+ acceptItem(input: AcceptItem, maxInputBytes?: number): StorageResult<{ item: StoredItem; duplicate: boolean }>;
344
+
345
+ /** Start the channel's next turn by taking ALL its pending items, in
346
+ * acceptance order, in one transaction: create the running turn, move each
347
+ * item received -> taken, append its timeline entry and link both to the turn.
348
+ * A message entry renders as `Participant: <JSON id>\n\n<text>`; a notice as
349
+ * its text. Returns null, committing nothing, when the channel has a running
350
+ * or suspended turn or has nothing pending. Requires `running` session
351
+ * lifecycle (`not_running`) and an `open` channel (`channel_suspended`; an
352
+ * unknown or retired channel is `not_found`/`channel_retired`). */
353
+ beginTurn(channelId: string, intake?: IntakeLimit): StorageResult<TurnTake | null>;
354
+
355
+ /** Steering: take all items pending on a running turn's channel, exactly as
356
+ * beginTurn does, at the turn's inference boundary. An empty take commits
357
+ * nothing. A turn that is not running is `invalid_state` and takes nothing, so
358
+ * a late caller cannot link items to an ended or checkpointed turn. Requires
359
+ * `running` lifecycle: refused with `not_running` for the whole `suspending`
360
+ * state, so suspension never forces an extra inference. The same holds for the
361
+ * turn's channel while `suspending`: `channel_suspended`, taking nothing. A
362
+ * resumed turn calls this before its first inference. */
363
+ takePending(turnId: number, intake?: IntakeLimit): StorageResult<TurnTake>;
364
+
365
+ /** Append only to a running turn. Storage assigns seq/time/channel/turn/from.
366
+ * Assistant messages are from agent; tool results are from tool. Calls are
367
+ * recorded before execution. A new assistant response requires all prior calls
368
+ * in the turn to have results. Tool results must match an unanswered call in
369
+ * that turn; duplicate call IDs/results are invalid. Each operation is atomic.
370
+ * A turn that is no longer running rejects with `invalid_state`: this is the
371
+ * fence that stops late model/tool output from advancing stopped work.
372
+ * Reject non-JSON data, including unsupported opaque provider state, without
373
+ * silently discarding it. Preserve supported provider state unchanged. */
374
+ appendMessage(
375
+ turnId: number,
376
+ message: Extract<Message, { role: "assistant" | "tool" }>,
377
+ ): StorageResult<TimelineEntry>;
378
+
379
+ /** Record provider evidence for every item the running turn has taken so far
380
+ * (no take can occur during the turn's own inference, so these are exactly the
381
+ * items in that request). `seen` implies `delivered`. Returns the items whose
382
+ * milestone advanced; none advancing commits nothing. A turn that is not
383
+ * running is `invalid_state` and commits nothing, so a model result arriving
384
+ * after interruption or failure cannot advance a receipt. Never called for an
385
+ * outbound request alone, a rejected call, or another channel's inference. */
386
+ confirmReceipts(turnId: number, milestone: "delivered" | "seen"): StorageResult<StoredItem[]>;
387
+
388
+ /** End a running turn.
389
+ * - completed: requires a recorded final tool-free assistant response and no
390
+ * unanswered calls. The pending-inbox check is part of this transaction in
391
+ * both `running` and `suspending`: if the channel has pending items the turn
392
+ * stays running and `{ finished: false }` is returned. While `running` the
393
+ * caller then takes them and infers again. While `suspending` the caller
394
+ * must checkpoint instead; the items stay pending for the resumed turn. The
395
+ * same applies while the turn's channel is `suspending`.
396
+ * - failed / interrupted: unconditional. Recorded entries, taken items and
397
+ * receipts are kept; unanswered calls become `uncertainCallIds`; pending
398
+ * items stay pending; the channel can begin a new turn.
399
+ * Terminal states cannot be overwritten or applied twice (`invalid_state`).
400
+ * Whenever this transaction ends the running turn of a `suspending` channel,
401
+ * the channel becomes `suspended` in the same transaction (no checkpoint). */
402
+ finishTurn(
403
+ turnId: number,
404
+ outcome: { status: "completed" } | { status: "failed" | "interrupted"; reason: string },
405
+ ): StorageResult<{ finished: true; turn: StoredTurn } | { finished: false; pending: number }>;
406
+
407
+ /** running -> suspended with a checkpoint at the inference boundary, for a
408
+ * turn that still needs an inference. Requires the session lifecycle or the
409
+ * turn's channel to be `suspending`, and no unanswered calls. A `suspending`
410
+ * channel becomes `suspended` in this same transaction, so the checkpoint and
411
+ * the channel suspension are durable together. `invalid_state`, changing nothing, when the turn's last
412
+ * entry is a tool-free assistant response and its channel has nothing
413
+ * pending: that turn is naturally finished and must be completed instead.
414
+ * Pending items are not taken; they wait for the resumed turn. */
415
+ checkpointTurn(turnId: number): StorageResult<StoredTurn>;
416
+
417
+ /** running -> suspending. Already suspending or suspended returns that state
418
+ * unchanged. From this commit, new messages, beginTurn and takePending are refused. */
419
+ beginSuspend(): StorageResult<StoredSession>;
420
+
421
+ /** suspending -> suspended. `invalid_state` while any turn is still running,
422
+ * and when the lifecycle is `running` (never suspending, or stopped by
423
+ * interruptActive). Already suspended returns unchanged. Pending items and
424
+ * checkpoints persist. Individual channel suspensions are independent: they
425
+ * neither delay nor are changed by this call. */
426
+ completeSuspend(): StorageResult<StoredSession>;
427
+
428
+ /** suspended -> running; every suspended turn whose channel is neither itself
429
+ * `suspended` nor `retired` returns to running in the same transaction and is returned for
430
+ * continuation. Turns of individually suspended channels stay checkpointed:
431
+ * they wait for `resumeChannel`, and a key mismatch on them does not block
432
+ * this call. A turn on a retired channel (only possible in unvalidated data)
433
+ * is left unchanged and never blocks this call. `incompatible`, writing nothing (lifecycle, checkpoints and
434
+ * pending items all unchanged), if any turn being resumed has a
435
+ * compatibilityKey different from the key passed to this open. Already running
436
+ * returns no turns; `suspending` is `invalid_state`. */
437
+ resume(): StorageResult<{ session: StoredSession; turns: StoredTurn[]; unblockedReminders?: import("./reminders.ts").Reminder[] }>;
438
+
439
+ /** Stop, in one transaction, by lifecycle:
440
+ * - `running`: every running turn becomes interrupted.
441
+ * - `suspending`: every running AND every checkpointed turn becomes
442
+ * interrupted and the lifecycle returns to `running`, so this attempt can
443
+ * no longer commit `suspended`.
444
+ * - `suspended`: nothing changes; clean checkpoints are kept.
445
+ * In every lifecycle, a checkpointed turn on a `suspended` channel is kept: an
446
+ * individually committed suspension is not part of this attempt. A `suspending`
447
+ * channel loses its turn and returns to `open` (it never committed). Unanswered
448
+ * calls become `uncertainCallIds`. Pending items stay pending.
449
+ * Returns the turns interrupted by this call. */
450
+ interruptActive(reason: string): StorageResult<StoredTurn[]>;
451
+
452
+ /** Decision 0021. Record that a revocable tool's grant is revoked or
453
+ * restored. Names only: definitions are not stored. A repeat writes nothing.
454
+ * An empty name is `invalid_input`. Allowed in every lifecycle. Returns the
455
+ * sorted revoked set. */
456
+ setToolRevoked(name: string, revoked: boolean): StorageResult<string[]>;
457
+
458
+ /** Explicit channel creation. Creation starts no turn and takes nothing.
459
+ * A new ID gets an `open` channel with the optional name. An existing open,
460
+ * suspending or suspended channel with the same name (or both unnamed) returns
461
+ * it with `created: false`; a different name is `already_exists`, so a retry
462
+ * is harmless but nothing is silently renamed. A retired ID is
463
+ * `channel_retired`. Invalid ID or name is `invalid_input`. Allowed in every
464
+ * session lifecycle: it admits no input. */
465
+ createChannel(input: { channelId: string; displayName?: string; policy?: string }): StorageResult<{ channel: StoredChannel; created: boolean }>;
466
+
467
+ /** Set (string) or clear (null) the display name only. Channel ID, history,
468
+ * lifecycle and execution state are untouched; a repeat is a no-op success.
469
+ * `not_found`, `channel_retired` and `invalid_input` as for create. Allowed in
470
+ * every session and channel lifecycle state. */
471
+ editChannel(channelId: string, displayName: string | null, policy?: string | null): StorageResult<StoredChannel>;
472
+
473
+ /** Begin this channel's individual suspension, independent of the session's.
474
+ * - `open` without a running turn: `suspended` in this transaction (an
475
+ * existing checkpoint is preserved).
476
+ * - `open` with a running turn: `suspending`. From this commit `acceptItem`,
477
+ * `beginTurn` and `takePending` refuse the channel with `channel_suspended`
478
+ * and `finishTurn(completed)` leaves pending items for a checkpoint. The
479
+ * running turn finishes its iteration, then `checkpointTurn`, `finishTurn` or
480
+ * `interruptTurn` makes the channel `suspended` in their own transaction.
481
+ * - already `suspending` or `suspended`: returned unchanged.
482
+ * Pending items are never taken or discarded. `not_found`, `channel_retired`.
483
+ * Allowed in every session lifecycle. */
484
+ beginChannelSuspend(channelId: string): StorageResult<StoredChannel>;
485
+
486
+ /** Clear the channel's individual suspension. `open` returns unchanged;
487
+ * `suspending` is `invalid_state` (retry after it settles). A retired ID is
488
+ * `channel_retired` and `not_found` an unknown one, both writing nothing.
489
+ * `suspended` becomes
490
+ * `open`; if the channel holds a checkpointed turn and the session lifecycle
491
+ * is `running`, that turn returns to running in the same transaction and is
492
+ * returned, under its original ID, for continuation: `incompatible`, writing
493
+ * nothing, if its compatibilityKey differs from this open's key. With the
494
+ * session `suspending` or `suspended` only the channel suspension is cleared:
495
+ * the checkpoint stays under the session suspension, no turn runs, and the
496
+ * session's own resume continues it. Pending items become eligible once both
497
+ * lifecycles permit. */
498
+ resumeChannel(channelId: string): StorageResult<{ channel: StoredChannel; turn?: StoredTurn; unblockedReminders?: import("./reminders.ts").Reminder[] }>;
499
+
500
+ /** Retire the channel: `retired` is final and the ID is reserved. Refused with
501
+ * `channel_busy`, changing nothing, while the channel has a running or
502
+ * checkpointed turn (an unresolved or incompatible checkpoint included) or any
503
+ * pending item, so acceptance and deletion are decided by commit order: an
504
+ * item accepted first blocks deletion; a deletion committed first makes later
505
+ * sends fail `channel_retired`. The timeline, items and turns are kept.
506
+ * Retired already returns it unchanged. `not_found`. Allowed in every
507
+ * session lifecycle and from `suspended`. */
508
+ deleteChannel(channelId: string): StorageResult<StoredChannel & { cancelledReminderIds?: string[] }>;
509
+
510
+ /** Withdraw a pending input of this channel, message or notice alike. Competes with
511
+ * `beginTurn`/`takePending` by commit order. Pending (`received`) becomes
512
+ * `withdrawn`: out of pending delivery and out of the timeline, durable across
513
+ * reopen, and a later `acceptItem` retry of the same ID returns it still
514
+ * withdrawn. An item already taken (or later) returns `taken` with its turn ID
515
+ * and changes nothing. Repeating a withdrawal returns `repeated: true`.
516
+ * `not_found` if the item is unknown or belongs to another channel. Allowed in
517
+ * every lifecycle state, so a suspended channel's backlog (which blocks
518
+ * deletion) can be cleared. */
519
+ withdrawItem(channelId: string, itemId: string): StorageResult<WithdrawOutcome>;
520
+
521
+ /** Interrupt this specific turn, unconditionally and without waiting for its
522
+ * inference or tools. Only a `running` turn is interrupted: it becomes
523
+ * interrupted with its unanswered calls as `uncertainCallIds`, its taken items
524
+ * and entries kept, pending items left pending, and any later
525
+ * `appendMessage`/`confirmReceipts`/`takePending` refused (`invalid_state`),
526
+ * so a late result is never recorded. A checkpointed or already ended turn
527
+ * returns `interrupted: false` with the turn as it is;
528
+ * in particular a stale ID never affects a newer turn. A `suspending` channel
529
+ * becomes `suspended` in the same transaction, without a checkpoint. The
530
+ * outcome of a competing checkpoint is decided by commit order. `not_found`
531
+ * for a turn ID never issued or one that belongs to another channel. Allowed
532
+ * in every session lifecycle. */
533
+ interruptTurn(channelId: string, turnId: number, reason: string): StorageResult<InterruptOutcome>;
534
+
535
+ /** Full neutral read for load/inspection/context. No prompt rendering or SQL
536
+ * leaks through this interface. Reading does not start or resume any work. */
537
+ snapshot(): StorageResult<StorageSnapshot>;
538
+
539
+ /** One consistent logical copy. Allowed only when the lifecycle is
540
+ * `suspended`, or it is `running` with no running turn, nothing pending, no
541
+ * checkpointed turn and no `suspending` channel (a `suspended` channel with
542
+ * neither checkpoint nor backlog is fine). `suspending` is always `busy`, even
543
+ * when every turn is already checkpointed or completed, because that state is
544
+ * not yet a clean suspension. Any other case is `busy`. Leaves the session
545
+ * unchanged. */
546
+ exportArchive(): StorageResult<SessionArchive>;
547
+
548
+ /** Release ownership/resources, never erase history. Idempotent after success.
549
+ * Caller must first stop using the handle from live execution. This is NOT
550
+ * suspend or stop: turns still running are interrupted by the next open.
551
+ * Failure must not advertise released ownership. Other calls after successful
552
+ * close return closed. */
553
+ close(): StorageResult<void>;
554
+ }
555
+
556
+ /** Adapter configured with a location (for example a SQLite path) by assembly.
557
+ * Methods are synchronous. Returned values and later reads are defensive copies.
558
+ * Commit notifications/output are wired by composition after success, never
559
+ * from inside a transaction. No durable event replay is promised. */
560
+ export interface SessionStorageAdapter {
561
+ /** Read the saved configuration without creating or recovering a session. */
562
+ readSavedConfig(): StorageResult<import("./session-file.ts").PortableSessionConfig | undefined>;
563
+ /** Atomically publish the logical archive and validated portable config. */
564
+ importSessionFile(payload: import("./session-file.ts").SessionFilePayload<SessionArchive | SessionArchiveV2 | SessionArchiveV3 | SessionArchiveV4>, options?: { sessionId?: string }): StorageResult<StoredSession>;
565
+ /** Acquire exclusive ownership, then check format and session ID, before any
566
+ * write. A second owner (`owner_conflict`), unreadable or unsupported format
567
+ * and a different session ID (`incompatible`) leave the data untouched.
568
+ * Recovery on reopen is one transaction, and executes nothing:
569
+ * - lifecycle `suspended`: no turn changes. Pending items and checkpoints are
570
+ * kept for explicit resume.
571
+ * - lifecycle `running` or `suspending` (the prior owner exited without clean
572
+ * suspension): every running turn, and every checkpointed turn whose channel
573
+ * is not `suspended`, becomes interrupted with its unanswered calls as
574
+ * `uncertainCallIds`; lifecycle becomes `running`. Taken items stay with
575
+ * their turn; pending items stay pending.
576
+ * - in every case a `suspending` channel (its suspension never committed)
577
+ * returns to `open`; a committed `suspended` channel and its checkpoint
578
+ * survive. Retired IDs and withdrawn items are untouched.
579
+ * - formats 2 and 3 upgrade to 4 transactionally; legacy policy references
580
+ * and item signatures are migrated. Incompatible old formats can be read
581
+ * through an isolated inspection view without modifying the owned file. */
582
+ open(options: StorageOpenOptions): StorageResult<SessionStorage>;
583
+
584
+ /** Validate the whole archive, then publish it atomically at this adapter's
585
+ * location, which must not already hold a session (`already_exists`). IDs
586
+ * inside the session are preserved; `sessionId` may replace the session's own.
587
+ * An archive whose lifecycle is `suspending`, or that holds a running turn, is
588
+ * `invalid_archive`: open would interrupt its checkpoints as an unclean exit.
589
+ * So is a `suspending` channel, a checkpointed turn on a non-`suspended`
590
+ * channel while the session is `running`, a withdrawn item with a turn link,
591
+ * a pending item on a retired channel, and, in every session lifecycle, a
592
+ * running or checkpointed turn on a retired channel. Version 1 archives (the persistence
593
+ * revision) import as channels `open` and unnamed; version 2 preserves
594
+ * channel lifecycle, names, withdrawn items and retired IDs.
595
+ * Any failure leaves no partial session. The result is not opened or owned. */
596
+ importArchive(archive: SessionArchive | SessionArchiveV1 | SessionArchiveV2 | SessionArchiveV3 | SessionArchiveV4, options?: { sessionId?: string }): StorageResult<StoredSession>;
597
+ }
@@ -0,0 +1,40 @@
1
+ /** Validated timeline query. The optional channel narrows session visibility. */
2
+ export interface TimelineSearch {
3
+ query: string;
4
+ channel?: string;
5
+ match?: "keywords" | "phrase";
6
+ case_sensitive?: boolean;
7
+ }
8
+
9
+ export interface RetrievedMessage {
10
+ seq: number;
11
+ message_id: string;
12
+ channel: string;
13
+ sender: string;
14
+ at?: string;
15
+ text: string;
16
+ }
17
+
18
+ export interface TimelineHit extends Omit<RetrievedMessage, "text"> {
19
+ excerpt: string;
20
+ }
21
+
22
+ export interface TimelineSearchResult {
23
+ hits: TimelineHit[];
24
+ partial: boolean;
25
+ }
26
+
27
+ export interface TimelineWindow {
28
+ message_id: string;
29
+ before?: number;
30
+ after?: number;
31
+ cursor?: string;
32
+ }
33
+
34
+ export interface TimelineWindowResult {
35
+ target: string;
36
+ sequence: number;
37
+ revision: number;
38
+ messages: Array<Omit<RetrievedMessage, "text"> & { text: string; offset: number }>;
39
+ next?: string;
40
+ }