@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,49 @@
1
+ export interface ReminderDeadline {
2
+ readonly sessionId: string;
3
+ readonly revision: number;
4
+ readonly nextDueAt: number | null;
5
+ }
6
+
7
+ export type ReminderDeadlineDecision = "accepted" | "unchanged" | "stale" | "mismatch";
8
+
9
+ /** Both executable opens and events use this fence. A reconnect retains the session ID. */
10
+ export function compareReminderDeadline(
11
+ current: ReminderDeadline | null,
12
+ incoming: ReminderDeadline,
13
+ replaceSession = false,
14
+ ): ReminderDeadlineDecision {
15
+ if (current === null) return "accepted";
16
+ if (current.sessionId !== incoming.sessionId) return replaceSession ? "accepted" : "stale";
17
+ if (incoming.revision > current.revision) return "accepted";
18
+ if (incoming.revision < current.revision) return "stale";
19
+ return current.nextDueAt === incoming.nextDueAt ? "unchanged" : "mismatch";
20
+ }
21
+
22
+ export interface ReminderWakeCandidate {
23
+ readonly op: "create" | "update" | "cancel";
24
+ readonly state: "pending" | "maybe_sent" | "applied" | "blocked";
25
+ readonly acceptedAt: number;
26
+ readonly dueAt: number | null;
27
+ readonly paused: boolean;
28
+ readonly suspended: boolean;
29
+ readonly retiring: boolean;
30
+ }
31
+
32
+ /** Deadlines request validation or replay without changing the stored schedule. */
33
+ export function deriveReminderWake(
34
+ reported: ReminderDeadline | null,
35
+ candidates: Iterable<ReminderWakeCandidate>,
36
+ validationDelayMs: number,
37
+ ): number | null {
38
+ let earliest = reported?.nextDueAt ?? null;
39
+ for (const candidate of candidates) {
40
+ if (candidate.op === "cancel" || candidate.paused || candidate.suspended || candidate.retiring) continue;
41
+ if (candidate.state !== "pending" && candidate.state !== "maybe_sent") continue;
42
+ const validationAt = candidate.acceptedAt + validationDelayMs;
43
+ if (!Number.isFinite(candidate.acceptedAt) || !Number.isFinite(validationAt) || (candidate.dueAt !== null && !Number.isFinite(candidate.dueAt))) continue;
44
+ // R8 must rate-limit an unresolved wake in the past through its restart budget.
45
+ const wake = Math.min(validationAt, candidate.dueAt ?? validationAt);
46
+ earliest = earliest === null ? wake : Math.min(earliest, wake);
47
+ }
48
+ return earliest;
49
+ }
@@ -0,0 +1,385 @@
1
+ import { activatesRoutine } from "../native/reminders/routine-guard.ts";
2
+ import type { MissedRuns, RoutineOverlap } from "../native/reminders/routine-schedule.ts";
3
+ import type { TimezoneMigration } from "../native/reminders/routine-wire.ts";
4
+ import type { WireChange } from "../native/reminders/wire.ts";
5
+ import type { ReminderExpiry, ReminderExpiryPolicy, ReminderSchedule } from "../native/reminders/schedule.ts";
6
+ import { defaultReminderLimits } from "../native/reminders/limits.ts";
7
+ import { compareReminderDeadline, deriveReminderWake, type ReminderDeadline, type ReminderDeadlineDecision } from "./reminder-wake.ts";
8
+
9
+ export interface Reminder {
10
+ readonly id: string;
11
+ readonly conversationId: string;
12
+ readonly text: string;
13
+ readonly schedule: ReminderSchedule;
14
+ readonly expiryPolicy: ReminderExpiryPolicy;
15
+ readonly expiry: ReminderExpiry;
16
+ readonly status: "active" | "paused" | "cancelled" | "completed" | "expired" | "blocked";
17
+ readonly policyNames?: readonly string[];
18
+ readonly nextRunAt?: number | null;
19
+ readonly lastRunAt?: number;
20
+ readonly revision?: number;
21
+ readonly scheduleAcceptedAt?: number;
22
+ readonly createdBy?: "agent" | "host";
23
+ readonly creatorId?: string;
24
+ readonly lastOccurrenceId?: string;
25
+ readonly noticeId?: string;
26
+ readonly blockedReason?: string;
27
+ readonly remainingCount?: number;
28
+ readonly missedRuns?: MissedRuns;
29
+ readonly overlap?: RoutineOverlap;
30
+ readonly timezoneVersion?: string;
31
+ readonly timezoneMigration?: TimezoneMigration;
32
+ readonly unreconciled?: boolean;
33
+ readonly missing?: boolean;
34
+ }
35
+
36
+ export interface ReminderChangeInput {
37
+ readonly reminder: Reminder;
38
+ readonly acceptedAt: number;
39
+ readonly retryKey?: string;
40
+ readonly op: "create" | "update" | "cancel";
41
+ readonly fields?: readonly ("text" | "schedule" | "expiry" | "status" | "policyNames" | "missedRuns" | "overlap")[];
42
+ }
43
+
44
+ export interface ReminderChange extends ReminderChangeInput {
45
+ readonly changeId: number;
46
+ readonly stagingOrder: number;
47
+ readonly observedAtSend?: number;
48
+ readonly frozenWire?: WireChange;
49
+ readonly state: "pending" | "maybe_sent" | "applied" | "blocked";
50
+ readonly reason?: string;
51
+ }
52
+
53
+ export interface ReminderJournal {
54
+ readonly id: string;
55
+ readonly conversationId: string;
56
+ readonly highWater: number;
57
+ readonly confirmed?: Reminder;
58
+ readonly observation?: number;
59
+ readonly receiptVersion?: number;
60
+ readonly changes: readonly ReminderChange[];
61
+ }
62
+
63
+ export interface ReminderWakeIndex {
64
+ readonly reported: ReminderDeadline | null;
65
+ readonly effectiveAt: number | null;
66
+ readonly supported?: boolean;
67
+ readonly replacementAttempted?: string;
68
+ readonly startupRetry?: { sessionId: string; entries: readonly WireChange[]; exhausted?: true };
69
+ }
70
+
71
+ export interface ReminderStorage {
72
+ nextOrder(): number;
73
+ get(id: string): ReminderJournal | undefined;
74
+ list(): ReminderJournal[];
75
+ save(journal: ReminderJournal): void;
76
+ remove(id: string): void;
77
+ suspended(conversationId: string): boolean;
78
+ setSuspended(conversationId: string, suspended: boolean): void;
79
+ wake(): ReminderWakeIndex;
80
+ saveWake(wake: ReminderWakeIndex): void;
81
+ }
82
+
83
+ type Runner = <T>(operation: () => T) => Promise<T>;
84
+
85
+ export interface ReminderPersistence {
86
+ readonly durable: boolean;
87
+ list(): Promise<readonly ReminderJournal[]>;
88
+ wake(routineGuardConfirmed?: boolean): Promise<ReminderWakeIndex>;
89
+ updateDeadline(deadline: ReminderDeadline, replaceSession?: boolean): Promise<ReminderDeadlineDecision>;
90
+ setConversationSuspended(conversationId: string, suspended: boolean): Promise<void>;
91
+ deleteConversation(conversationId: string): Promise<void>;
92
+ enqueue(change: ReminderChangeInput): Promise<ReminderChange | undefined>;
93
+ markMaybeSent(id: string, changeId: number, wire?: WireChange): Promise<ReminderChange | undefined>;
94
+ acknowledge(id: string, changeId: number, outcome: { confirmed: Reminder } | { reason: string }): Promise<boolean>;
95
+ discardBlocked(id: string): Promise<void>;
96
+ discardExhausted(id: string, conversationId: string): Promise<boolean>;
97
+ observe(reminder: Reminder): Promise<void>;
98
+ restoreStaged(change: ReminderChange): Promise<void>;
99
+ quarantine(id: string, changeId: number, reason: string): Promise<void>;
100
+ deferStorageFailure(id: string, changeId: number): Promise<void>;
101
+ setSupported(supported: boolean): Promise<void>;
102
+ setReplacementAttempted(sessionId: string | undefined): Promise<void>;
103
+ setStartupRetry(retry: ReminderWakeIndex["startupRetry"]): Promise<void>;
104
+ replaceSession(sessionId: string): Promise<void>;
105
+ completeSweep(seen: ReadonlySet<string>): Promise<void>;
106
+ }
107
+
108
+ function isWakeSchedule(schedule: ReminderSchedule): boolean {
109
+ return !!schedule && "at" in schedule && Number.isSafeInteger(schedule.at);
110
+ }
111
+
112
+ export class StoredReminderPersistence implements ReminderPersistence {
113
+ constructor(
114
+ readonly durable: boolean,
115
+ private readonly store: ReminderStorage,
116
+ private readonly write: Runner,
117
+ private readonly read: Runner,
118
+ ) {}
119
+
120
+ list(): Promise<readonly ReminderJournal[]> {
121
+ return this.read(() => this.store.list());
122
+ }
123
+
124
+ wake(routineGuardConfirmed = false): Promise<ReminderWakeIndex> {
125
+ return this.read(() => routineGuardConfirmed ? this.deriveWake(this.store.wake().reported, true) : this.store.wake());
126
+ }
127
+
128
+ private deriveWake(reported: ReminderWakeIndex["reported"], routineGuardConfirmed: boolean): ReminderWakeIndex {
129
+ const { supported, replacementAttempted, startupRetry } = this.store.wake();
130
+ const candidates = supported === false ? [] : this.store.list().flatMap(journal => journal.changes.filter(change => {
131
+ const schedule = change.reminder.schedule;
132
+ return isWakeSchedule(schedule) || (routineGuardConfirmed && change.op === "create" && activatesRoutine(change));
133
+ }).map(change => {
134
+ const latest = journal.changes.at(-1)?.reminder ?? change.reminder;
135
+ const { schedule } = change.reminder;
136
+ return {
137
+ ...change,
138
+ dueAt: "at" in schedule ? schedule.at : "startAt" in schedule ? schedule.startAt : null,
139
+ paused: latest.status === "paused" || change.reminder.status === "paused",
140
+ suspended: this.store.suspended(journal.conversationId),
141
+ retiring: false,
142
+ };
143
+ }));
144
+ return {
145
+ reported,
146
+ ...(supported === undefined ? {} : { supported }),
147
+ ...(replacementAttempted === undefined ? {} : { replacementAttempted }),
148
+ ...(startupRetry === undefined ? {} : { startupRetry }),
149
+ effectiveAt: supported === false ? null : deriveReminderWake(reported, candidates, defaultReminderLimits.oneShotLeadMs),
150
+ };
151
+ }
152
+
153
+ private recompute(reported = this.store.wake().reported): void {
154
+ this.store.saveWake(this.deriveWake(reported, false));
155
+ }
156
+
157
+ updateDeadline(deadline: ReminderDeadline, replaceSession = false): Promise<ReminderDeadlineDecision> {
158
+ return this.write(() => {
159
+ const result = compareReminderDeadline(this.store.wake().reported, deadline, replaceSession);
160
+ if (result === "accepted") this.recompute(deadline);
161
+ return result;
162
+ });
163
+ }
164
+
165
+ setConversationSuspended(conversationId: string, suspended: boolean): Promise<void> {
166
+ return this.write(() => {
167
+ this.store.setSuspended(conversationId, suspended);
168
+ this.recompute();
169
+ });
170
+ }
171
+
172
+ deleteConversation(conversationId: string): Promise<void> {
173
+ return this.write(() => {
174
+ for (const journal of this.store.list()) {
175
+ if (journal.conversationId === conversationId) this.store.remove(journal.id);
176
+ }
177
+ this.store.setSuspended(conversationId, false);
178
+ this.recompute();
179
+ });
180
+ }
181
+
182
+ enqueue(input: ReminderChangeInput): Promise<ReminderChange | undefined> {
183
+ const change = structuredClone(input);
184
+ const { id, conversationId } = change.reminder;
185
+ return this.write(() => {
186
+ const journal = this.store.get(id) ?? { id, conversationId, highWater: 0, changes: [] };
187
+ if (journal.conversationId !== conversationId) throw new Error("Reminder belongs to another conversation");
188
+ const latest = journal.changes.at(-1);
189
+ const separateRoutineStop = latest && activatesRoutine(latest) &&
190
+ (change.op === "cancel" || change.fields?.includes("status") && change.reminder.status === "paused");
191
+ const coalesce = !separateRoutineStop && latest?.state === "pending" && !latest.frozenWire && !(latest.op === "create" && change.reminder.status === "paused");
192
+ const dropCreate = change.op === "cancel" && journal.changes[0]?.op === "create"
193
+ && journal.changes.every(entry => entry.state === "pending");
194
+ const changes = dropCreate ? [] : coalesce ? journal.changes.slice(0, -1) : [...journal.changes];
195
+ const changeId = journal.highWater + 1;
196
+ const next: ReminderChange | undefined = dropCreate
197
+ ? undefined
198
+ : { ...change, op: coalesce && latest.op === "create" ? "create" : change.op, changeId, stagingOrder: coalesce ? latest.stagingOrder : this.store.nextOrder(), state: "pending" };
199
+ const queued = next && coalesce && latest.fields && next.fields && next.op === "update"
200
+ ? { ...next, fields: [...new Set([...latest.fields, ...next.fields])] }
201
+ : next;
202
+ if (queued) changes.push(queued);
203
+ this.store.save({ ...journal, highWater: changeId, changes });
204
+ this.recompute();
205
+ return structuredClone(queued);
206
+ });
207
+ }
208
+
209
+ markMaybeSent(id: string, changeId: number, wire?: WireChange): Promise<ReminderChange | undefined> {
210
+ return this.write(() => {
211
+ const journal = this.store.get(id);
212
+ const entry = journal?.changes.find((change) => change.changeId === changeId);
213
+ if (!journal || !entry || (entry.state !== "pending" && entry.state !== "maybe_sent")) return;
214
+ if (entry.state === "maybe_sent" && (!wire || entry.frozenWire)) return structuredClone(entry);
215
+ const next: ReminderChange = { ...entry, state: "maybe_sent", observedAtSend: entry.observedAtSend ?? journal.observation ?? 0, frozenWire: wire ?? entry.frozenWire };
216
+ this.store.save({ ...journal, changes: journal.changes.map((change) => change === entry ? next : change) });
217
+ return structuredClone(next);
218
+ });
219
+ }
220
+
221
+ acknowledge(
222
+ id: string,
223
+ changeId: number,
224
+ outcome: { confirmed: Reminder } | { reason: string },
225
+ ): Promise<boolean> {
226
+ const receipt = structuredClone(outcome);
227
+ return this.write(() => {
228
+ const journal = this.store.get(id);
229
+ const sent = journal?.changes.filter((change) => change.state !== "pending");
230
+ const entry = sent?.find((change) => change.changeId === changeId);
231
+ if (!journal || entry?.state !== "maybe_sent") return false;
232
+ if ("reason" in receipt) {
233
+ this.store.save({
234
+ ...journal,
235
+ changes: journal.changes.map((change) => change === entry
236
+ ? { ...change, state: "blocked", reason: receipt.reason }
237
+ : change),
238
+ });
239
+ } else {
240
+ const confirmed = journal.confirmed;
241
+ const newer = !confirmed || ((journal.observation ?? 0) === entry.observedAtSend
242
+ && changeId >= (journal.receiptVersion ?? 0));
243
+ this.store.save({
244
+ ...journal,
245
+ confirmed: newer ? receipt.confirmed : confirmed,
246
+ receiptVersion: newer ? changeId : journal.receiptVersion,
247
+ changes: sent?.at(-1) === entry
248
+ ? journal.changes.filter((change) => change.changeId > changeId)
249
+ : journal.changes.map((change) => change === entry ? { ...change, state: "applied" } : change),
250
+ });
251
+ }
252
+ this.recompute();
253
+ return true;
254
+ });
255
+ }
256
+
257
+ observe(reminder: Reminder): Promise<void> {
258
+ return this.write(() => {
259
+ const current = this.store.get(reminder.id) ?? {
260
+ id: reminder.id, conversationId: reminder.conversationId, highWater: 0, changes: [],
261
+ };
262
+ if (current.conversationId !== reminder.conversationId) return;
263
+ this.store.save({ ...current, observation: (current.observation ?? 0) + 1, confirmed: reminder });
264
+ });
265
+ }
266
+
267
+ restoreStaged(original: ReminderChange): Promise<void> {
268
+ return this.write(() => {
269
+ const journal = this.store.get(original.reminder.id);
270
+ if (!journal) return;
271
+ this.store.save({
272
+ ...journal,
273
+ changes: journal.changes.map(change => change.changeId === original.changeId && change.state === "maybe_sent"
274
+ ? original : change),
275
+ });
276
+ this.recompute();
277
+ });
278
+ }
279
+
280
+ quarantine(id: string, changeId: number, reason: string): Promise<void> {
281
+ return this.write(() => {
282
+ const journal = this.store.get(id);
283
+ if (!journal) return;
284
+ this.store.save({ ...journal, changes: journal.changes.map(change => change.changeId === changeId
285
+ ? { ...change, state: "blocked", reason } : change) });
286
+ this.recompute();
287
+ });
288
+ }
289
+
290
+ deferStorageFailure(id: string, changeId: number): Promise<void> {
291
+ return this.write(() => {
292
+ const journal = this.store.get(id);
293
+ if (!journal) return;
294
+ this.store.save({ ...journal, changes: journal.changes.map(change =>
295
+ change.changeId === changeId && change.state === "maybe_sent" ? { ...change, reason: "storage_failure" } : change) });
296
+ });
297
+ }
298
+
299
+ setSupported(supported: boolean): Promise<void> {
300
+ return this.write(() => {
301
+ this.store.saveWake({ ...this.store.wake(), supported });
302
+ this.recompute();
303
+ });
304
+ }
305
+
306
+ setReplacementAttempted(sessionId: string | undefined): Promise<void> {
307
+ return this.write(() => {
308
+ const { replacementAttempted: _previous, ...wake } = this.store.wake();
309
+ this.store.saveWake(sessionId === undefined ? wake : { ...wake, replacementAttempted: sessionId });
310
+ });
311
+ }
312
+
313
+ setStartupRetry(startupRetry: ReminderWakeIndex["startupRetry"]): Promise<void> {
314
+ return this.write(() => {
315
+ const { startupRetry: _previous, ...wake } = this.store.wake();
316
+ this.store.saveWake(startupRetry ? { ...wake, startupRetry } : wake);
317
+ });
318
+ }
319
+
320
+ replaceSession(sessionId: string): Promise<void> {
321
+ return this.write(() => {
322
+ for (const row of this.store.list()) {
323
+ this.store.save({
324
+ ...row,
325
+ changes: row.changes.map(change => change.state === "maybe_sent" ? { ...change, state: "pending", observedAtSend: undefined } : change),
326
+ ...(row.confirmed ? { confirmed: { ...row.confirmed, unreconciled: true }, receiptVersion: undefined } : {}),
327
+ });
328
+ }
329
+ const { replacementAttempted: _attempted, ...wake } = this.deriveWake({ sessionId, revision: 0, nextDueAt: null }, false);
330
+ this.store.saveWake(wake);
331
+ });
332
+ }
333
+
334
+ completeSweep(seen: ReadonlySet<string>): Promise<void> {
335
+ return this.write(() => {
336
+ for (const row of this.store.list()) {
337
+ if (!row.confirmed || seen.has(row.id) || row.changes.some(change => change.state === "pending" || change.state === "maybe_sent")) continue;
338
+ this.store.save({ ...row, confirmed: { ...row.confirmed, unreconciled: false, missing: true } });
339
+ }
340
+ });
341
+ }
342
+
343
+ discardExhausted(id: string, conversationId: string): Promise<boolean> {
344
+ return this.write(() => {
345
+ const journal = this.store.get(id);
346
+ const { startupRetry, ...wake } = this.store.wake();
347
+ if (!startupRetry?.exhausted || journal?.conversationId !== conversationId) return false;
348
+ const discarded = new Set(startupRetry.entries.filter(entry => entry.reminderId === id).map(entry => entry.changeId));
349
+ if (!discarded.size) return false;
350
+ const remaining = startupRetry.entries.filter(entry => entry.reminderId !== id);
351
+ this.store.save({ ...journal, changes: journal.changes.filter(change => !discarded.has(change.changeId)) });
352
+ this.store.saveWake(remaining.length ? { ...wake, startupRetry: { ...startupRetry, entries: remaining } } : wake);
353
+ this.recompute();
354
+ return true;
355
+ });
356
+ }
357
+
358
+ discardBlocked(id: string): Promise<void> {
359
+ return this.write(() => {
360
+ const journal = this.store.get(id);
361
+ if (!journal) return;
362
+ this.store.save({ ...journal, changes: journal.changes.filter((change) => change.state !== "blocked") });
363
+ this.recompute();
364
+ });
365
+ }
366
+ }
367
+
368
+ export function createMemoryReminderPersistence(): ReminderPersistence {
369
+ let order = 0;
370
+ const journals = new Map<string, ReminderJournal>();
371
+ const suspended = new Set<string>();
372
+ let wake: ReminderWakeIndex = { reported: null, effectiveAt: null };
373
+ const run: Runner = async (operation) => operation();
374
+ return new StoredReminderPersistence(false, {
375
+ nextOrder: () => ++order,
376
+ get: (id) => structuredClone(journals.get(id)),
377
+ list: () => structuredClone([...journals.values()]),
378
+ save: (journal) => { journals.set(journal.id, structuredClone(journal)); },
379
+ remove: (id) => { journals.delete(id); },
380
+ suspended: (id) => suspended.has(id),
381
+ setSuspended: (id, value) => { if (value) suspended.add(id); else suspended.delete(id); },
382
+ wake: () => structuredClone(wake),
383
+ saveWake: (value) => { wake = structuredClone(value); },
384
+ }, run, run);
385
+ }
@@ -1,3 +1,9 @@
1
+ import { createSqliteReminderPersistence } from "./sqlite-reminders.ts";
2
+ import type { ReminderPersistence } from "./reminders.ts";
3
+ import { serializeNativeMeteringProof } from "../metering/native/proof.ts";
4
+ import { SqliteWorkers } from "./sqlite-workers.ts";
5
+ import { randomUUID } from "node:crypto";
6
+ import { SqliteWorkerDelivery } from "./sqlite-worker-delivery.ts";
1
7
  import { Database, type Changes } from "bun:sqlite";
2
8
  import { createHash } from "node:crypto";
3
9
  import { mkdir, realpath } from "node:fs/promises";
@@ -45,6 +51,7 @@ import {
45
51
  type MessageRecord,
46
52
  type MeteringCommitInput,
47
53
  type MeteringPersistence,
54
+ type MeteringOperationIdentity,
48
55
  type MeteringRecordListOptions,
49
56
  type MeteringRecordPage,
50
57
  type NewConversationRecord,
@@ -100,6 +107,8 @@ import { SqliteSharedFiles } from "./sqlite-files.ts";
100
107
  import type { SharedFilesPersistence } from "../media/files.ts";
101
108
  import { SqliteMediaStore } from "./sqlite-media-store.ts";
102
109
  import type { MediaStore } from "../media/store.ts";
110
+ import type { ChannelPersistence } from "./channels.ts";
111
+ import { SqliteChannelPersistence } from "./sqlite-channels.ts";
103
112
 
104
113
  type SqlValue = string | number | bigint | boolean | Uint8Array | null;
105
114
  type WriteRunner = <T>(work: () => T) => Promise<T>;
@@ -116,6 +125,8 @@ interface ConversationRow {
116
125
  metadata: string | null;
117
126
  adopted: number;
118
127
  adopt_provider_session_id: string | null;
128
+ controller_kind: NonNullable<AgentConversationSummary["controllerKind"]> | null;
129
+ role: NonNullable<AgentConversationSummary["role"]> | null;
119
130
  }
120
131
 
121
132
  interface IdentityRow {
@@ -164,6 +175,12 @@ export class SqliteAgentPersistence implements PersistenceBackend {
164
175
  readonly internalInferences: InternalInferenceRepository;
165
176
  readonly recoveryCheckpoints: ConversationRecoveryCheckpointRepository;
166
177
  readonly identity: IdentityPersistence;
178
+ readonly channels: ChannelPersistence;
179
+ readonly reminders: ReminderPersistence;
180
+ readonly workerDelivery?: SqliteWorkerDelivery;
181
+ readonly workers: NonNullable<PersistenceScope["workers"]>;
182
+ private readonly workerOwnerId = randomUUID();
183
+ private readonly workerOwnerCutoff: number;
167
184
  readonly identityDelivery: IdentityDeliveryPersistence;
168
185
  readonly search?: SearchPersistence;
169
186
  readonly auditOutbox: AuditOutboxPersistence;
@@ -173,6 +190,16 @@ export class SqliteAgentPersistence implements PersistenceBackend {
173
190
  private readonly installedExtensions: PersistenceExtension[] = [];
174
191
  private writeTail: Promise<void> = Promise.resolve();
175
192
  private closed = false;
193
+ private readonly reminderWakeListeners = new Set<() => void>();
194
+
195
+ get ownsReminderWake(): boolean { return this.ownerLock !== undefined; }
196
+ subscribeReminderWake(listener: () => void): () => void {
197
+ this.reminderWakeListeners.add(listener);
198
+ return () => { this.reminderWakeListeners.delete(listener); };
199
+ }
200
+ private notifyReminderWake(): void {
201
+ for (const listener of this.reminderWakeListeners) { try { listener(); } catch { /* Observer isolation. */ } }
202
+ }
176
203
 
177
204
  private constructor(
178
205
  path: string,
@@ -183,17 +210,32 @@ export class SqliteAgentPersistence implements PersistenceBackend {
183
210
  ) {
184
211
  this.path = path;
185
212
  this.database = database;
213
+ this.workerOwnerCutoff = ownerLock ? database.query<{ seq: number }, []>(
214
+ "SELECT COALESCE(MAX(reservation_seq), 0) AS seq FROM worker_assignments",
215
+ ).get()!.seq : 0;
186
216
  this.identityRecord = identityRecord;
187
217
  this.capabilities = Object.freeze({
188
218
  transactions: true as const,
189
219
  fullTextSearch,
190
220
  identity: true,
221
+ channels: true,
222
+ reminders: true,
223
+ workers: true,
224
+ workerDelivery: Boolean(ownerLock),
191
225
  auditOutbox: true,
192
226
  extensions: true,
193
227
  vectorSearch: false,
194
228
  metering: true,
195
229
  });
196
- const scope = this.createScope((work) => this.autoWrite(work), (records) => this.notifyRecordsCommitted(records));
230
+ const scope = this.createScope(
231
+ (work) => this.autoWrite(work),
232
+ (records) => this.notifyRecordsCommitted(records),
233
+ // Root intent reads must not see a retirement inside an uncommitted delete.
234
+ (work) => {
235
+ this.assertOpen();
236
+ return this.enqueueWrite(async () => work());
237
+ },
238
+ );
197
239
  this.media = scope.media!;
198
240
  this.files = scope.files!;
199
241
  this.outOfBandDelivery = scope.outOfBandDelivery!;
@@ -206,6 +248,10 @@ export class SqliteAgentPersistence implements PersistenceBackend {
206
248
  this.internalInferences = scope.internalInferences!;
207
249
  this.recoveryCheckpoints = scope.recoveryCheckpoints!;
208
250
  this.identity = scope.identity!;
251
+ this.channels = scope.channels!;
252
+ this.reminders = scope.reminders!;
253
+ this.workers = scope.workers!;
254
+ this.workerDelivery = scope.workerDelivery as SqliteWorkerDelivery | undefined;
209
255
  this.identityDelivery = scope.identityDelivery!;
210
256
  this.search = fullTextSearch ? new SqliteSearchPersistence(database) : undefined;
211
257
  this.auditOutbox = scope.auditOutbox!;
@@ -282,13 +328,15 @@ export class SqliteAgentPersistence implements PersistenceBackend {
282
328
  this.assertOpen();
283
329
  return await this.enqueueWrite(async () => {
284
330
  const committed: ConversationRecord[] = [];
331
+ let wakeChanged = false;
285
332
  this.database.exec("BEGIN IMMEDIATE");
286
333
  try {
287
334
  const scope = this.createScope(async (operation) => operation(), (records) => {
288
335
  committed.push(...records);
289
- });
336
+ }, undefined, () => { wakeChanged = true; });
290
337
  const result = await work(scope);
291
338
  this.database.exec("COMMIT");
339
+ if (wakeChanged) this.notifyReminderWake();
292
340
  await this.notifyRecordsCommitted(committed);
293
341
  return result;
294
342
  } catch (error) {
@@ -331,6 +379,8 @@ export class SqliteAgentPersistence implements PersistenceBackend {
331
379
  private createScope(
332
380
  runWrite: WriteRunner,
333
381
  onAppended: (records: readonly ConversationRecord[]) => void | Promise<void>,
382
+ readChannels: WriteRunner = runWrite,
383
+ scopedWakeChanged?: () => void,
334
384
  ): PersistenceScope {
335
385
  return Object.freeze({
336
386
  media: new SqliteMediaStore(this.database, runWrite),
@@ -355,6 +405,18 @@ export class SqliteAgentPersistence implements PersistenceBackend {
355
405
  runWrite,
356
406
  ),
357
407
  identityDelivery: new SqliteIdentityDeliveryPersistence(this.database, runWrite),
408
+ reminders: scopedWakeChanged
409
+ ? createSqliteReminderPersistence(this.database, runWrite, readChannels, scopedWakeChanged)
410
+ : createSqliteReminderPersistence(this.database, async operation => {
411
+ const result = await runWrite(operation);
412
+ this.notifyReminderWake();
413
+ return result;
414
+ }, readChannels),
415
+ channels: new SqliteChannelPersistence(this.database, runWrite, readChannels),
416
+ workers: new SqliteWorkers(this.database, runWrite, readChannels),
417
+ ...(this.ownerLock ? { workerDelivery: new SqliteWorkerDelivery(
418
+ this.database, runWrite, readChannels, this.workerOwnerId, this.workerOwnerCutoff,
419
+ ) } : {}),
358
420
  ...(this.capabilities.fullTextSearch
359
421
  ? { search: new SqliteSearchPersistence(this.database) }
360
422
  : {}),
@@ -463,8 +525,8 @@ class SqliteConversationPersistence implements ConversationPersistence {
463
525
  runSql(this.database,
464
526
  `INSERT INTO conversations(
465
527
  agent_conversation_id, agent_session_id, title, created_at, updated_at, metadata,
466
- adopted, adopt_provider_session_id
467
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
528
+ adopted, adopt_provider_session_id, controller_kind, role
529
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
468
530
  input.agentConversationId,
469
531
  input.agentSessionId,
470
532
  input.title ?? null,
@@ -473,6 +535,8 @@ class SqliteConversationPersistence implements ConversationPersistence {
473
535
  input.metadata ?? null,
474
536
  input.adoptProviderSessionId === undefined ? 0 : 1,
475
537
  input.adoptProviderSessionId ?? null,
538
+ input.controllerKind ?? null,
539
+ input.role ?? null,
476
540
  );
477
541
  const participants = input.participants?.length
478
542
  ? input.participants
@@ -1188,8 +1252,8 @@ class SqliteMeteringPersistence implements MeteringPersistence {
1188
1252
  runSql(this.database,
1189
1253
  `INSERT INTO metering_records(
1190
1254
  agent_conversation_id, operation_id, internal_session_id, adapter_id,
1191
- operation_kind, outcome, completed_at, record_json
1192
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
1255
+ operation_kind, outcome, completed_at, record_json, native_metering_proof_json
1256
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1193
1257
  input.agentConversationId,
1194
1258
  operationId,
1195
1259
  input.record.internalSessionId,
@@ -1198,6 +1262,7 @@ class SqliteMeteringPersistence implements MeteringPersistence {
1198
1262
  input.record.outcome,
1199
1263
  input.record.completedAt,
1200
1264
  input.meteringRecords === "none" ? null : serializedRecord,
1265
+ serializeNativeMeteringProof(input.record),
1201
1266
  );
1202
1267
 
1203
1268
  const revision = (current?.revision ?? 0) + 1;
@@ -1306,6 +1371,17 @@ class SqliteMeteringPersistence implements MeteringPersistence {
1306
1371
  });
1307
1372
  }
1308
1373
 
1374
+ async operationIdentity(agentConversationId: AgentConversationId, operationId: string): Promise<MeteringOperationIdentity | null> {
1375
+ const row = this.database.query<MeteringOperationIdentity & { proof: string | null }, [string, string]>(
1376
+ `SELECT outcome, adapter_id AS adapterId, completed_at AS completedAt,
1377
+ native_metering_proof_json AS proof FROM metering_records
1378
+ WHERE agent_conversation_id = ? AND operation_id = ?`,
1379
+ ).get(agentConversationId, nonblank(operationId, "metering operationId"));
1380
+ if (!row) return null;
1381
+ const { proof, ...identity } = row;
1382
+ return proof === null ? identity : { ...identity, ...JSON.parse(proof) };
1383
+ }
1384
+
1309
1385
  async get(
1310
1386
  agentConversationId: AgentConversationId,
1311
1387
  operationId: string,
@@ -2080,6 +2156,8 @@ function summaryFromRowWithParticipants(
2080
2156
  agentConversationId: row.agent_conversation_id as AgentConversationId,
2081
2157
  agentSessionId: row.agent_session_id as AgentSessionId,
2082
2158
  ...(row.title !== null ? { title: row.title } : {}),
2159
+ ...(row.controller_kind !== null ? { controllerKind: row.controller_kind } : {}),
2160
+ ...(row.role !== null ? { role: row.role } : {}),
2083
2161
  participants: Object.freeze(participants),
2084
2162
  createdAt: row.created_at,
2085
2163
  updatedAt: row.updated_at,