@zvada/agent-server 0.3.23 → 0.3.24

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 (246) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +686 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +330 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +28 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +434 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +329 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +141 -0
  141. package/dist/protocol/errors.js +181 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +291 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  207. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  208. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/options.d.ts +24 -11
  210. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  212. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  213. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  214. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  216. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  218. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  219. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  220. package/dist/types/core/agents/process-pool.d.ts +8 -0
  221. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  222. package/dist/types/core/presets.d.ts +2 -2
  223. package/dist/types/core/presets.d.ts.map +1 -1
  224. package/dist/types/server/bin.d.ts +3 -0
  225. package/dist/types/server/bin.d.ts.map +1 -0
  226. package/dist/types/server/transports.d.ts +2 -1
  227. package/dist/types/server/transports.d.ts.map +1 -1
  228. package/dist/types/sync/node-sqlite.d.ts +4 -1
  229. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  230. package/docs/consuming.md +30 -4
  231. package/docs/deploy.md +28 -0
  232. package/docs/harnesses.md +13 -1
  233. package/package.json +43 -18
  234. package/src/core/agents/claude-code/approvals.ts +5 -1
  235. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  236. package/src/core/agents/claude-code/options.ts +24 -11
  237. package/src/core/agents/claude-code/session.ts +13 -0
  238. package/src/core/agents/codex-app-server/homes.ts +11 -2
  239. package/src/core/agents/codex-app-server/login.ts +30 -0
  240. package/src/core/agents/codex-app-server/requests.ts +7 -6
  241. package/src/core/agents/codex-app-server/session.ts +11 -2
  242. package/src/core/agents/process-pool.ts +30 -4
  243. package/src/core/presets.ts +3 -2
  244. package/src/server/bin.ts +25 -10
  245. package/src/server/transports.ts +6 -1
  246. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,202 @@
1
+ import { HISTORY_MAX_BYTES, HistoryError, OMITTED_BINARY_META_KEY, canonicalJson, decodeLifecycleEvent, jsonBytes, validateHistoryEvent, } from "../protocol/index.js";
2
+ // Every event a journal stores fits in any page either reader builds, a
3
+ // history page or a replay page: these margins keep that true together.
4
+ /** The largest event a journal stores: a page of `HISTORY_MAX_BYTES` still fits around it. */
5
+ export const MAX_EVENT_BYTES = HISTORY_MAX_BYTES - 32 * 1024;
6
+ /** What a history page leaves for its `next` cursor's digits and `hasMore` to change as records join it. */
7
+ export const PAGE_SLACK_BYTES = 128;
8
+ /**
9
+ * What a replay page's envelopes fill before the next waits for another page:
10
+ * the result around them fits in what remains. An event alone may be larger
11
+ * (up to `MAX_EVENT_BYTES`), and comes alone.
12
+ */
13
+ export const REPLAY_PAGE_BYTES = HISTORY_MAX_BYTES - 64 * 1024;
14
+ const encoder = new TextEncoder();
15
+ const decoder = new TextDecoder();
16
+ /** An image or file as the protocol carries one: base64 `data` beside its `mimeType`. */
17
+ function isBinary(value) {
18
+ const entry = value;
19
+ return ((entry.type === "image" || entry.type === "file") &&
20
+ typeof entry.data === "string" &&
21
+ typeof entry.mimeType === "string");
22
+ }
23
+ /** The size of what base64 `data` encodes. */
24
+ function decodedBytes(data) {
25
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
26
+ return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
27
+ }
28
+ /** The part fields that address a part, which its stand-in keeps. */
29
+ const ADDRESS = ["id", "sessionId", "messageId", "parentToolCallId"];
30
+ /**
31
+ * What a store keeps in place of `binary`: text saying what it was, in words
32
+ * and under `OMITTED_BINARY_META_KEY`. A part stays at its address as a text
33
+ * part; a tool result's entry becomes a text entry.
34
+ */
35
+ function omittedBinary(binary, where) {
36
+ const facts = {
37
+ type: binary.type,
38
+ mimeType: binary.mimeType,
39
+ bytes: decodedBytes(binary.data),
40
+ ...(typeof binary.filename === "string" && { filename: binary.filename }),
41
+ };
42
+ const meta = binary._meta && typeof binary._meta === "object" && !Array.isArray(binary._meta)
43
+ ? binary._meta
44
+ : {};
45
+ const named = facts.filename === undefined ? "" : ` ${facts.filename}`;
46
+ return {
47
+ type: "text",
48
+ ...Object.fromEntries(ADDRESS.filter((key) => typeof binary[key] === "string").map((key) => [key, binary[key]])),
49
+ text: `[agent-server: ${facts.mimeType} ${facts.type}${named} of ${facts.bytes} bytes omitted to fit ${where}]`,
50
+ _meta: { ...meta, [OMITTED_BINARY_META_KEY]: facts },
51
+ };
52
+ }
53
+ // @ref LLP 0002#tool-output-has-three-audiences — a cut binary is no display at all: kept whole or replaced
54
+ /**
55
+ * `value` brought down to `maxBytes` by its longest strings, one at a time: a
56
+ * binary's `data` (an image or file, `isBinary`) is never cut, its whole entry
57
+ * is replaced by a text one saying what it was (`omittedBinary`); any other
58
+ * string is cut with a visible marker, when `cutText`. It stops when only
59
+ * short strings remain, so what it returns may still not fit. A value that
60
+ * already fits is returned as is.
61
+ */
62
+ function shrink(value, maxBytes, where, cutText) {
63
+ let size = jsonBytes(value);
64
+ if (size <= maxBytes)
65
+ return value;
66
+ const copy = structuredClone(value);
67
+ // Each replacement removes a binary; cuts are bounded as they always were.
68
+ let cuts = 0;
69
+ while (size > maxBytes) {
70
+ let longest;
71
+ const consider = (holder, key, bytes, binary) => {
72
+ if (!longest || bytes > longest.bytes)
73
+ longest = { holder: holder, key, bytes, binary };
74
+ };
75
+ const visit = (node) => {
76
+ for (const [key, child] of Object.entries(node)) {
77
+ if (child && typeof child === "object") {
78
+ // Base64 is ASCII: its length is its size.
79
+ if (isBinary(child))
80
+ consider(node, key, child.data.length, true);
81
+ else
82
+ visit(child);
83
+ }
84
+ else if (cutText && typeof child === "string")
85
+ consider(node, key, encoder.encode(child).byteLength, false);
86
+ }
87
+ };
88
+ if (copy && typeof copy === "object")
89
+ visit(copy);
90
+ if (!longest || longest.bytes < 1024)
91
+ break;
92
+ const { holder, key, bytes } = longest;
93
+ if (longest.binary)
94
+ holder[key] = omittedBinary(holder[key], where);
95
+ else {
96
+ if (++cuts > 8)
97
+ break;
98
+ const keep = Math.max(0, bytes - (size - maxBytes) - 256);
99
+ const head = decoder
100
+ .decode(encoder.encode(holder[key]).slice(0, keep))
101
+ .replace(/�$/, "");
102
+ holder[key] = `${head}\n[agent-server: ${bytes - keep} bytes omitted to fit ${where}]`;
103
+ }
104
+ size = jsonBytes(copy);
105
+ }
106
+ return copy;
107
+ }
108
+ /**
109
+ * `event` cut down to `maxBytes`: its longest strings (usually a tool's
110
+ * output) are truncated with a visible marker until it fits, and an image or
111
+ * file it cannot keep whole is replaced by text saying what it was. `undefined`
112
+ * when only short strings remain. An event that already fits is returned as is.
113
+ */
114
+ export function fitEvent(event, maxBytes = MAX_EVENT_BYTES) {
115
+ const fitted = shrink(event, maxBytes, "the journal", true);
116
+ return jsonBytes(fitted) <= maxBytes ? fitted : undefined;
117
+ }
118
+ /**
119
+ * `value` with its largest images and files replaced by text saying what they
120
+ * were (as `fitEvent` replaces them) until it fits `maxBytes`, or until none
121
+ * is left. Nothing else is changed. A value that already fits is returned as is.
122
+ */
123
+ export function omitBinaries(value, maxBytes, where) {
124
+ return shrink(value, maxBytes, where, false);
125
+ }
126
+ /**
127
+ * What a journal stores in place of an event it cannot record, so the turn and
128
+ * every other session keep going. A turn or session end keeps its meaning;
129
+ * anything else becomes a recoverable error notice naming what was lost.
130
+ */
131
+ function unrecordedEvent(event, reason) {
132
+ const message = `agent-server could not record a ${event.type} event: ${reason.slice(0, 300)}`;
133
+ const timestamp = Date.now();
134
+ if (event.type === "turn.ended")
135
+ return {
136
+ type: "turn.ended",
137
+ sessionId: event.sessionId,
138
+ turnId: event.turnId,
139
+ stopReason: "error",
140
+ error: { category: "internal", message },
141
+ timestamp,
142
+ };
143
+ if (event.type === "session.ended")
144
+ return { type: "session.ended", sessionId: event.sessionId, reason: event.reason, timestamp };
145
+ const turnId = event.turnId;
146
+ return {
147
+ type: "error",
148
+ sessionId: event.sessionId,
149
+ ...(typeof turnId === "string" && { turnId }),
150
+ category: "internal",
151
+ message,
152
+ recoverable: true,
153
+ timestamp,
154
+ };
155
+ }
156
+ /** Why no history holds `event` as it is: malformed, or not a history event. */
157
+ function refusal(event) {
158
+ try {
159
+ validateHistoryEvent(event.sessionId, decodeLifecycleEvent(event));
160
+ }
161
+ catch (error) {
162
+ return error instanceof HistoryError ? error.message : "Malformed event";
163
+ }
164
+ }
165
+ /** An event's canonical body, when a journal can store it as it is. */
166
+ function storable(event) {
167
+ const refused = refusal(event);
168
+ if (refused)
169
+ return { tooLarge: false, reason: refused };
170
+ const body = canonicalJson(event);
171
+ if (encoder.encode(body).byteLength > MAX_EVENT_BYTES)
172
+ return { tooLarge: true, reason: "Event exceeds durable record byte limit" };
173
+ return { event, body };
174
+ }
175
+ /**
176
+ * What a journal stores for `event`, with its canonical body: the event, a
177
+ * copy cut down to fit (`fitEvent`), or a notice in its place
178
+ * (`unrecordedEvent`). Decided before writing: one event a journal cannot
179
+ * store must not stop its turn or any other session.
180
+ */
181
+ export function recordable(event) {
182
+ const checked = storable(event);
183
+ if ("body" in checked)
184
+ return checked;
185
+ if (checked.tooLarge) {
186
+ const fitted = fitEvent(event);
187
+ const refitted = fitted && storable(fitted);
188
+ if (refitted && "body" in refitted)
189
+ return refitted;
190
+ // A prompt replaced by a notice could never be answered: keep it, without its input.
191
+ if (event.type === "permission.requested" && event.toolCall) {
192
+ const { rawInput: _input, ...toolCall } = event.toolCall;
193
+ const bare = storable({ ...event, toolCall });
194
+ if ("body" in bare)
195
+ return bare;
196
+ }
197
+ }
198
+ const notice = storable(unrecordedEvent(event, checked.reason));
199
+ if (!("body" in notice))
200
+ throw new Error(`Unstorable notice: ${notice.reason}`);
201
+ return notice;
202
+ }
@@ -0,0 +1,33 @@
1
+ import { HistoryError, sameHistory, sameVersion, validateHistorySlice, } from "../protocol/index.js";
2
+ /** Pin the leaf once and walk immutable parent cuts. Return ancestors before
3
+ * descendants so every reader/importer uses the same ordering and depth bound. */
4
+ export async function historyPath(source, leaf, signal) {
5
+ const versions = [];
6
+ const seen = new Set();
7
+ let ref = leaf;
8
+ let pinned;
9
+ while (ref) {
10
+ signal?.throwIfAborted();
11
+ const key = JSON.stringify([ref.sourceId, ref.sessionId]);
12
+ if (seen.has(key) || seen.size >= 64)
13
+ throw new HistoryError("invalidParams", "History ancestry cycle or depth limit");
14
+ seen.add(key);
15
+ const head = await source.head(ref);
16
+ if (!sameHistory(head.descriptor, ref) || !sameHistory(head.version, ref))
17
+ throw new HistoryError("invalidParams", "History head identity mismatch");
18
+ versions.push(pinned ?? head.version);
19
+ pinned = head.descriptor.parent;
20
+ ref = pinned;
21
+ }
22
+ return versions.reverse();
23
+ }
24
+ /** A valid slice is not enough: bind it to the caller's identity and requested
25
+ * range before importing, yielding or reducing it. */
26
+ export async function readHistoryPage(source, request) {
27
+ const page = validateHistorySlice(await source.read(request));
28
+ if (!sameHistory(page.descriptor, request) ||
29
+ (request.through && !sameVersion(page.head, request.through)) ||
30
+ (request.after ? !sameVersion(page.base, request.after) : page.base.seq !== 0))
31
+ throw new HistoryError("historyConflict", "History page does not match the requested prefix or revision");
32
+ return page;
33
+ }
@@ -0,0 +1,281 @@
1
+ import { CONVERSATION_CHECKPOINT_FORMAT, ConversationStateSchema, HISTORY_MAX_BYTES, HistoryCheckpointRequestSchema, HistoryCheckpointSchema, HistoryCommitSchema, HistoryError, HistoryForkSchema, HistoryListSchema, HistoryReadSchema, HistoryWaitSchema, canonicalJson as canonical, emptyConversation, jsonBytes, parseHistoryRequest, sameHistory, sameVersion, validateHistoryRecords, validateHistorySlice, } from "../protocol/index.js";
2
+ import { sha256 } from "./event-log.js";
3
+ import { MAX_EVENT_BYTES, PAGE_SLACK_BYTES } from "./fit.js";
4
+ import { checkCheckpointBytes, fitCheckpoint, projectionFold } from "./projection.js";
5
+ const conflict = (message) => new HistoryError("historyConflict", message);
6
+ const missing = (message) => new HistoryError("unknownHistory", message);
7
+ const invalid = (message) => new HistoryError("invalidParams", message);
8
+ const digest = (value) => sha256(canonical(value));
9
+ /** What a page puts around a record's stored body, `{"seq":N,"event":BODY}`, and a comma between records. */
10
+ const recordOverhead = (row, index) => 17 + String(row.seq).length + (index ? 1 : 0);
11
+ /** Every history one journal file holds: those it ran, branched or copied in.
12
+ * Each mutation is one transaction; wakeups run after it commits. */
13
+ export class SqliteHistory {
14
+ sourceId;
15
+ db;
16
+ log;
17
+ closed = new AbortController();
18
+ listeners = new Set();
19
+ constructor(sourceId, db, log) {
20
+ this.sourceId = sourceId;
21
+ this.db = db;
22
+ this.log = log;
23
+ }
24
+ /** A fork reserves its ID from the executable session namespace. */
25
+ isBranch(sessionId) {
26
+ return this.log.head({ sourceId: this.sourceId, sessionId })?.descriptor.kind === "branch";
27
+ }
28
+ changed(ref) {
29
+ for (const listener of this.listeners) {
30
+ try {
31
+ listener(ref);
32
+ }
33
+ catch {
34
+ /* wakeups cannot undo a commit */
35
+ }
36
+ }
37
+ }
38
+ onChange(listener) {
39
+ this.listeners.add(listener);
40
+ return () => {
41
+ this.listeners.delete(listener);
42
+ };
43
+ }
44
+ close() {
45
+ this.closed.abort(new Error("History store closed"));
46
+ this.listeners.clear();
47
+ }
48
+ head(ref) {
49
+ const head = this.log.head(ref);
50
+ if (!head)
51
+ throw missing("Unknown history");
52
+ return head;
53
+ }
54
+ /** The head of a history that holds `expected` exactly. */
55
+ holding(expected) {
56
+ const head = this.head(expected);
57
+ if (expected.seq > head.version.seq)
58
+ throw missing("History does not reach the requested version");
59
+ const version = expected.seq === 0 ? this.log.root(head.descriptor) : this.log.at(expected, expected.seq);
60
+ if (version?.hash !== expected.hash)
61
+ throw conflict("History version does not match the committed prefix");
62
+ return head;
63
+ }
64
+ list(request = {}) {
65
+ const { after, limit } = parseHistoryRequest(HistoryListSchema, request);
66
+ if (after && after.storeId !== this.sourceId)
67
+ throw invalid("Catalog cursor belongs to another store");
68
+ const heads = this.log.heads(after?.ref, limit + 1);
69
+ const entries = heads.slice(0, limit);
70
+ const last = entries.at(-1)?.version;
71
+ return {
72
+ entries,
73
+ next: heads.length > limit && last
74
+ ? { storeId: this.sourceId, ref: { sourceId: last.sourceId, sessionId: last.sessionId } }
75
+ : null,
76
+ };
77
+ }
78
+ read(request) {
79
+ const params = parseHistoryRequest(HistoryReadSchema, request);
80
+ const current = this.head(params);
81
+ const { descriptor } = current;
82
+ const base = params.after ?? this.log.root(descriptor);
83
+ const head = params.through ?? current.version;
84
+ if (!sameHistory(base, descriptor) || !sameHistory(head, descriptor) || base.seq > head.seq)
85
+ throw invalid("History range belongs to another history or revision");
86
+ this.holding(base);
87
+ this.holding(head);
88
+ const empty = {
89
+ descriptor,
90
+ base,
91
+ head,
92
+ next: base,
93
+ records: [],
94
+ hasMore: base.seq < head.seq,
95
+ };
96
+ const budget = params.maxBytes - jsonBytes(empty) - PAGE_SLACK_BYTES;
97
+ if (budget < 0)
98
+ throw invalid("History metadata exceeds page budget");
99
+ const rows = this.log.page(descriptor, base.seq, head.seq, {
100
+ limit: params.limit,
101
+ maxBytes: budget,
102
+ overhead: recordOverhead,
103
+ oversizedFirst: false,
104
+ });
105
+ if (!rows.length && empty.hasMore)
106
+ throw invalid("Increase history page maxBytes or use blob references");
107
+ const last = rows.at(-1);
108
+ const next = last ? { ...base, seq: last.seq, hash: last.hash } : base;
109
+ return {
110
+ ...empty,
111
+ next,
112
+ records: rows.map((row) => ({ seq: row.seq, event: JSON.parse(row.body) })),
113
+ hasMore: next.seq < head.seq,
114
+ };
115
+ }
116
+ fork(value) {
117
+ const request = parseHistoryRequest(HistoryForkSchema, value);
118
+ const ref = { sourceId: this.sourceId, sessionId: request.sessionId };
119
+ const descriptor = {
120
+ ...ref,
121
+ format: 1,
122
+ kind: "branch",
123
+ ...(request.from && { parent: request.from }),
124
+ };
125
+ this.db.atomic(() => {
126
+ const existing = this.log.head(ref)?.descriptor;
127
+ if (existing?.kind === "execution")
128
+ throw conflict("Cannot fork over an execution session");
129
+ if (request.from) {
130
+ if (sameHistory(request.from, ref))
131
+ throw invalid("A history cannot be its own parent");
132
+ this.holding(request.from);
133
+ }
134
+ if (!existing)
135
+ this.log.create(descriptor);
136
+ else if (canonical(existing) !== canonical(descriptor))
137
+ throw conflict("History descriptor cannot change");
138
+ });
139
+ this.changed(ref);
140
+ return this.head(ref);
141
+ }
142
+ commit(value) {
143
+ const request = parseHistoryRequest(HistoryCommitSchema, value);
144
+ if (jsonBytes(request) > HISTORY_MAX_BYTES)
145
+ throw invalid("History commit exceeds byte limit");
146
+ const ref = request.expected;
147
+ const fingerprint = digest(request);
148
+ const result = this.db.atomic(() => {
149
+ const current = this.log.head(ref);
150
+ if (ref.sourceId !== this.sourceId || current?.descriptor.kind !== "branch")
151
+ throw invalid("Only locally owned branches accept explicit commits");
152
+ const receipt = this.db.one("SELECT fingerprint,version FROM commits WHERE session_id=? AND commit_id=?", ref.sessionId, request.commitId);
153
+ if (receipt) {
154
+ if (receipt.fingerprint !== fingerprint)
155
+ throw conflict("Commit ID was reused with different content");
156
+ return JSON.parse(receipt.version);
157
+ }
158
+ if (!sameVersion(current.version, request.expected))
159
+ throw conflict("Commit expected head is stale; pull and fork or retry from the current version");
160
+ const first = current.version.seq + 1;
161
+ validateHistoryRecords(ref.sessionId, request.events.map((event, i) => ({ seq: first + i, event })));
162
+ const bodies = request.events.map((event) => canonical(event));
163
+ if (bodies.some((body) => Buffer.byteLength(body) > MAX_EVENT_BYTES))
164
+ throw invalid("History event exceeds readable page size");
165
+ const next = this.log.append(current.version, bodies);
166
+ this.db.run("INSERT INTO commits(session_id,commit_id,fingerprint,version) VALUES (?,?,?,?)", ref.sessionId, request.commitId, fingerprint, canonical(next));
167
+ return next;
168
+ });
169
+ this.changed(ref);
170
+ return result;
171
+ }
172
+ import(value) {
173
+ // The trust boundary for every caller, in process or over the wire.
174
+ const page = validateHistorySlice(value);
175
+ const ref = page.descriptor;
176
+ if (ref.sourceId === this.sourceId)
177
+ throw conflict("Cannot import over a locally owned history");
178
+ this.db.atomic(() => {
179
+ if (ref.parent)
180
+ this.holding(ref.parent);
181
+ const existing = this.log.head(ref);
182
+ if (existing && canonical(existing.descriptor) !== canonical(page.descriptor))
183
+ throw conflict("History descriptor cannot change");
184
+ let head = existing?.version ?? this.log.create(page.descriptor);
185
+ this.holding(page.base);
186
+ // Records this store already holds must be identical; the rest extend it.
187
+ const held = new Map();
188
+ for (const row of this.log.records(ref, page.base.seq, Math.min(head.seq, page.next.seq)))
189
+ held.set(row.seq, row.body);
190
+ const suffix = [];
191
+ for (const record of page.records) {
192
+ const body = canonical(record.event);
193
+ if (record.seq > head.seq)
194
+ suffix.push(body);
195
+ else if (held.get(record.seq) !== body)
196
+ throw conflict("History record conflict");
197
+ }
198
+ if (suffix.length)
199
+ head = this.log.append(head, suffix);
200
+ const committed = head.seq === page.next.seq ? head : this.log.at(ref, page.next.seq);
201
+ if (!committed || !sameVersion(committed, page.next))
202
+ throw conflict("History payload does not match its committed version");
203
+ });
204
+ this.changed(ref);
205
+ return page.next;
206
+ }
207
+ async wait(value, signal) {
208
+ const request = parseHistoryRequest(HistoryWaitSchema, value);
209
+ const stop = AbortSignal.any([this.closed.signal, ...(signal ? [signal] : [])]);
210
+ stop.throwIfAborted();
211
+ const current = this.holding(request.after);
212
+ if (!sameVersion(current.version, request.after) || !request.timeoutMs)
213
+ return current;
214
+ return new Promise((resolve, reject) => {
215
+ let dispose = () => { };
216
+ const cleanup = () => {
217
+ clearTimeout(timer);
218
+ dispose();
219
+ stop.removeEventListener("abort", abort);
220
+ };
221
+ const finish = () => {
222
+ cleanup();
223
+ try {
224
+ resolve(this.head(request.after));
225
+ }
226
+ catch (error) {
227
+ reject(error);
228
+ }
229
+ };
230
+ const abort = () => {
231
+ cleanup();
232
+ reject(stop.reason);
233
+ };
234
+ const timer = setTimeout(finish, request.timeoutMs);
235
+ dispose = this.onChange((ref) => {
236
+ if (sameHistory(ref, request.after))
237
+ finish();
238
+ });
239
+ stop.addEventListener("abort", abort, { once: true });
240
+ if (stop.aborted)
241
+ abort();
242
+ else if (!sameVersion(this.head(request.after).version, request.after))
243
+ finish();
244
+ });
245
+ }
246
+ /** Return only a compatible, previously built cache. Older pinned forks fall
247
+ * back to canonical replay when the single retained cache is beyond their cut. */
248
+ checkpoint(request) {
249
+ const { through } = parseHistoryRequest(HistoryCheckpointRequestSchema, request);
250
+ this.holding(through);
251
+ const row = this.db.one("SELECT body FROM checkpoints WHERE source_id=? AND session_id=? AND seq<=? AND format=?", through.sourceId, through.sessionId, through.seq, CONVERSATION_CHECKPOINT_FORMAT);
252
+ if (!row)
253
+ return null;
254
+ const checkpoint = HistoryCheckpointSchema.parse(JSON.parse(row.body));
255
+ this.holding(checkpoint.version);
256
+ return checkpoint;
257
+ }
258
+ /** Host-only bounded cache construction. No RPC accepts uploaded projections.
259
+ * Advance incrementally (e.g. every 1000 events); keep all original events. */
260
+ createCheckpoint(ref, options = {}) {
261
+ const fold = projectionFold(options.maxRecords);
262
+ const target = options.through ?? this.head(ref).version;
263
+ if (!sameHistory(target, ref))
264
+ throw invalid("Checkpoint belongs to another history");
265
+ this.holding(target);
266
+ const prior = this.checkpoint({ through: target });
267
+ let conversation = prior
268
+ ? ConversationStateSchema.parse(prior.conversation)
269
+ : emptyConversation();
270
+ for (const row of this.log.records(ref, prior?.version.seq ?? 0, target.seq))
271
+ conversation = fold(conversation, JSON.parse(row.body));
272
+ const checkpoint = fitCheckpoint({
273
+ version: target,
274
+ format: CONVERSATION_CHECKPOINT_FORMAT,
275
+ conversation,
276
+ });
277
+ checkCheckpointBytes(checkpoint);
278
+ this.db.atomic(() => this.db.run("INSERT INTO checkpoints(source_id,session_id,format,seq,body) VALUES (?,?,?,?,?) ON CONFLICT(source_id,session_id,format) DO UPDATE SET seq=excluded.seq,body=excluded.body WHERE excluded.seq>=checkpoints.seq", ref.sourceId, ref.sessionId, CONVERSATION_CHECKPOINT_FORMAT, target.seq, canonical(checkpoint)));
279
+ return checkpoint;
280
+ }
281
+ }
@@ -0,0 +1,163 @@
1
+ import { CONVERSATION_CHECKPOINT_FORMAT, ConversationStateSchema, HistoryCheckpointSchema, HistoryError, emptyConversation, jsonBytes, sameHistory, sameVersion, } from "../protocol/index.js";
2
+ import { historyPath, readHistoryPage } from "./history-reader.js";
3
+ import { checkCheckpointBytes, projectionFold } from "./projection.js";
4
+ import { RetryBudget, idleAfter, pause } from "./retry.js";
5
+ function checkBudget(name, value) {
6
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0))
7
+ throw new Error(`${name} must be a nonnegative safe integer`);
8
+ }
9
+ const missing = (error) => error instanceof HistoryError && error.code === "unknownHistory";
10
+ export async function transferHistory(source, destination, ref, options = {}) {
11
+ checkBudget("maxPages", options.maxPages);
12
+ checkBudget("maxBytes", options.maxBytes);
13
+ const stats = { pages: 0, bytes: 0, records: 0 };
14
+ let version;
15
+ for (const target of await historyPath(source, ref, options.signal)) {
16
+ const leaf = sameHistory(target, ref);
17
+ let after;
18
+ try {
19
+ after = (await destination.head(target)).version;
20
+ }
21
+ catch (error) {
22
+ if (!missing(error))
23
+ throw error;
24
+ }
25
+ if (leaf)
26
+ version = after;
27
+ // A destination may already hold later parent history; verify the pinned cut.
28
+ if (after && after.seq >= target.seq) {
29
+ await source.read({ ...target, after: target, through: target });
30
+ await destination.read({ ...target, after: target, through: target });
31
+ if (leaf)
32
+ version = target;
33
+ continue;
34
+ }
35
+ for (;;) {
36
+ options.signal?.throwIfAborted();
37
+ if (stats.pages >= (options.maxPages ?? Number.POSITIVE_INFINITY))
38
+ return { version, complete: false, ...stats };
39
+ const page = await readHistoryPage(source, {
40
+ ...target,
41
+ after,
42
+ through: target,
43
+ limit: options.pageSize,
44
+ maxBytes: options.pageBytes,
45
+ });
46
+ const bytes = jsonBytes(page);
47
+ if (stats.bytes + bytes > (options.maxBytes ?? Number.POSITIVE_INFINITY))
48
+ return { version, complete: false, ...stats };
49
+ options.signal?.throwIfAborted();
50
+ const receipt = await destination.import(page);
51
+ if (!sameVersion(receipt, page.next))
52
+ throw new HistoryError("historyConflict", "History receipt mismatch");
53
+ stats.pages++;
54
+ stats.bytes += bytes;
55
+ stats.records += page.records.length;
56
+ after = page.next;
57
+ if (leaf)
58
+ version = after;
59
+ options.onPage?.(page, bytes);
60
+ if (!page.hasMore)
61
+ break;
62
+ }
63
+ }
64
+ // The leaf comes last on the path, and every way through it sets its version.
65
+ if (!version)
66
+ throw new Error("History transfer ended before its leaf");
67
+ return { version, complete: true, ...stats };
68
+ }
69
+ /** Snapshot pages, then live suffixes. A wakeup is only a hint: the next pull
70
+ * starts at the last yielded version, covering changes between read and wait.
71
+ * Sequential consumption provides backpressure without an unbounded event queue. */
72
+ export async function* followHistory(source, ref, options = {}) {
73
+ let after = options.after;
74
+ if (after && !sameHistory(after, ref))
75
+ throw new Error("Follow cursor belongs to another history");
76
+ const budget = new RetryBudget(options.retry);
77
+ let following = false;
78
+ const retry = async (error) => {
79
+ const ms = budget.fail(error);
80
+ following = false;
81
+ options.onState?.("reconnecting", error);
82
+ await pause(ms, options.signal);
83
+ };
84
+ while (!options.signal?.aborted) {
85
+ let page;
86
+ try {
87
+ page = await readHistoryPage(source, {
88
+ ...ref,
89
+ after,
90
+ limit: options.pageSize,
91
+ maxBytes: options.pageBytes,
92
+ });
93
+ if (options.signal?.aborted)
94
+ return;
95
+ // A successful empty read does not repair a persistently failing wait RPC.
96
+ if (page.records.length)
97
+ budget.progressed();
98
+ if (!following)
99
+ options.onState?.("following");
100
+ following = true;
101
+ }
102
+ catch (error) {
103
+ if (options.signal?.aborted)
104
+ return;
105
+ await retry(error);
106
+ continue;
107
+ }
108
+ const initial = !after;
109
+ after = page.next;
110
+ if (initial || page.records.length)
111
+ yield page;
112
+ if (page.hasMore)
113
+ continue;
114
+ try {
115
+ const waited = Date.now();
116
+ const head = await source.wait({ after, timeoutMs: options.waitMs }, options.signal);
117
+ budget.progressed();
118
+ if (sameVersion(head.version, after))
119
+ await idleAfter(waited, options.signal);
120
+ }
121
+ catch (error) {
122
+ if (options.signal?.aborted)
123
+ return;
124
+ await retry(error);
125
+ }
126
+ }
127
+ }
128
+ /** Ancestors remain separate, namespaced segments so provider-local turn/message
129
+ * IDs cannot collide. Render segments in order; only the leaf is followed live. */
130
+ export async function openHistory(source, ref, options = {}) {
131
+ const fold = projectionFold(options.maxRecords);
132
+ const segments = [];
133
+ for (const target of await historyPath(source, ref, options.signal)) {
134
+ let after;
135
+ let conversation = emptyConversation();
136
+ if (options.checkpoints !== false && source.checkpoint) {
137
+ const value = await source.checkpoint({ through: target });
138
+ if (value) {
139
+ const checkpoint = HistoryCheckpointSchema.parse(value);
140
+ checkCheckpointBytes(checkpoint);
141
+ if (!sameHistory(checkpoint.version, target) || checkpoint.version.seq > target.seq)
142
+ throw new HistoryError("invalidParams", "Checkpoint is outside the requested history");
143
+ if (checkpoint.format === CONVERSATION_CHECKPOINT_FORMAT) {
144
+ // Bind the cached state to an available prefix before applying its tail.
145
+ await source.read({ ...target, after: checkpoint.version, through: checkpoint.version });
146
+ conversation = ConversationStateSchema.parse(checkpoint.conversation);
147
+ after = checkpoint.version;
148
+ }
149
+ }
150
+ }
151
+ for (;;) {
152
+ options.signal?.throwIfAborted();
153
+ const page = await readHistoryPage(source, { ...target, after, through: target });
154
+ for (const record of page.records)
155
+ conversation = fold(conversation, record.event);
156
+ after = page.next;
157
+ if (!page.hasMore)
158
+ break;
159
+ }
160
+ segments.push({ version: after, conversation });
161
+ }
162
+ return { segments, version: segments.at(-1).version };
163
+ }
@@ -0,0 +1,5 @@
1
+ // Storage/transport-neutral host contracts. SQLite is an optional subpath.
2
+ export { JournalError } from "./journal.js";
3
+ export { JOURNAL_SCHEMA_VERSION } from "./schema.js";
4
+ export { followHistory, openHistory, transferHistory, } from "./history.js";
5
+ export { startHistorySync, } from "./worker.js";