@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,93 @@
1
+ import { z } from "zod";
2
+ import { openVocabulary } from "./vocabulary.js";
3
+ /**
4
+ * The agent harnesses this engine can drive:
5
+ * - `claude-code` — Claude Code via @anthropic-ai/claude-agent-sdk (CLI under the hood)
6
+ * - `codex-app-server` — OpenAI Codex via `codex app-server` (long-lived JSON-RPC subprocess)
7
+ * - `acp` — any Agent Client Protocol v1 agent subprocess (`gemini --acp`,
8
+ * `claude-code-acp`, `codex-acp`, ACP registry agents); the launch
9
+ * command is operator-configured, never taken from the wire
10
+ * - `scripted` — a script the operator gives plays the agent (a product's
11
+ * free test double); registered only with its script
12
+ */
13
+ export const AGENT_HARNESSES = ["claude-code", "codex-app-server", "acp", "scripted"];
14
+ export const AgentHarnessSchema = z.enum(AGENT_HARNESSES);
15
+ export const HarnessIdSchema = openVocabulary(AGENT_HARNESSES);
16
+ export function isAgentHarness(value) {
17
+ return AGENT_HARNESSES.includes(value);
18
+ }
19
+ /**
20
+ * How a harness handles changing the model mid-conversation:
21
+ * - `in_session` — swap live without losing context (Claude `setModel`)
22
+ * - `restart_session` — must start a fresh underlying session (no built-in
23
+ * harness does; a custom one may)
24
+ * - `unsupported` — model is fixed for the life of the session
25
+ * OPEN: a mode a newer engine reports decodes intact; treat one this build
26
+ * does not know as `unsupported`.
27
+ */
28
+ export const MODEL_SWITCH_MODES = ["in_session", "restart_session", "unsupported"];
29
+ export const ModelSwitchModeSchema = openVocabulary(MODEL_SWITCH_MODES);
30
+ /**
31
+ * What a file sent as data is, to the harness that reads it (`fileKind`):
32
+ * - `text` — a text media type (`text/*`, JSON, XML, YAML, TOML, scripts,
33
+ * `+json`, `+xml`), which a harness may inline as prompt text
34
+ * - `pdf` — `application/pdf`
35
+ * - `binary` — any other media type
36
+ * OPEN: a newer engine may name a kind this build does not classify.
37
+ */
38
+ export const FILE_KINDS = ["text", "pdf", "binary"];
39
+ export const FileKindSchema = openVocabulary(FILE_KINDS);
40
+ const TEXT_MEDIA = /^text\/|^application\/(json|xml|yaml|x-yaml|toml|javascript|typescript|x-sh|sql|graphql)$|\+(json|xml)$/;
41
+ /** The kind of a file of this media type, as every harness tells them apart. */
42
+ export function fileKind(mimeType) {
43
+ if (mimeType === "application/pdf")
44
+ return "pdf";
45
+ return TEXT_MEDIA.test(mimeType) ? "text" : "binary";
46
+ }
47
+ /**
48
+ * Declarative feature matrix per harness. Callers consult this to decide what
49
+ * is safe to ask for (e.g. whether to expect resume, or whether a model change
50
+ * forces a restart). Returned in the engine's session snapshot.
51
+ */
52
+ export const AgentCapabilitiesSchema = z.object({
53
+ /** Can feed multiple turns into one long-lived underlying session. */
54
+ multiTurn: z.boolean(),
55
+ /** Can resume a prior session from its native id. */
56
+ sessionResume: z.boolean(),
57
+ /** How a model change is handled. */
58
+ modelSwitch: ModelSwitchModeSchema,
59
+ /** Honors a thinking/reasoning-effort level. */
60
+ thinkingLevels: z.boolean(),
61
+ /** Accepts image input parts. */
62
+ images: z.boolean(),
63
+ /**
64
+ * The files it reads when a turn sends one as data, by `fileKind`: a file
65
+ * of a kind not listed fails the turn as `invalid_request`.
66
+ */
67
+ files: z.array(FileKindSchema),
68
+ /** Accepts external MCP servers. */
69
+ mcpServers: z.boolean(),
70
+ /** Can raise interactive `permission.requested` round-trips mid-turn. */
71
+ permissionRequests: z.boolean(),
72
+ /**
73
+ * A refused tool call's `message` (`PermissionOutcome`) reaches the agent
74
+ * as why. Where it does not (a bare verdict, an option id), a client hands
75
+ * the user's words on as the next input.
76
+ */
77
+ rejectionMessages: z.boolean(),
78
+ /** Supports native delegation contained within the current execution. */
79
+ turnScopedSubagents: z.boolean().optional(),
80
+ /**
81
+ * Takes more input while a turn runs (`turn/steer`): the agent reads it at
82
+ * its next step, inside the same turn.
83
+ */
84
+ steering: z.boolean().optional(),
85
+ /**
86
+ * The `RunConfig` fields this harness never applies: a turn that sets one
87
+ * runs without it, and says so (`turn.started.execution.notApplied`). A
88
+ * setting applied with another meaning is not listed, nor one the harness
89
+ * refuses (the turn fails). Always present from this engine; absent from
90
+ * an older one, which says nothing either way.
91
+ */
92
+ ignoredSettings: z.array(z.string()).optional(),
93
+ });
@@ -0,0 +1,201 @@
1
+ import { z } from "zod";
2
+ import { canonicalJson } from "./canonical.js";
3
+ import { isLiveOnlyEvent, isUnknownEvent } from "./guards.js";
4
+ import { decodeLifecycleEvent, } from "./lifecycle.js";
5
+ import { WireRefusal } from "./wire.js";
6
+ /** Portable session history: versioned, append-only event logs that any host
7
+ * can pull, import, fork and follow. These methods never execute agent work. */
8
+ export const HISTORY_METHODS = {
9
+ list: "history/list",
10
+ head: "history/head",
11
+ read: "history/read",
12
+ import: "history/import",
13
+ fork: "history/fork",
14
+ commit: "history/commit",
15
+ wait: "history/wait",
16
+ checkpoint: "history/checkpoint",
17
+ };
18
+ export const HISTORY_MAX_RECORDS = 256;
19
+ /** How long `history/wait` waits by default before answering with an unchanged head. */
20
+ export const HISTORY_WAIT_TIMEOUT_MS = 15_000;
21
+ export const HISTORY_MAX_BYTES = 8 * 1024 * 1024;
22
+ /**
23
+ * The `_meta` key on what a durable store kept in place of a binary it could
24
+ * not keep whole: an image or file whose base64 `data` would not fit an
25
+ * event's record or a checkpoint. The entry is text, so every reader renders
26
+ * it as it is: a tool result's `content` image becomes a `text` entry, an
27
+ * image or file part a `text` part at the same address. Under this key it
28
+ * says what was there (`OmittedBinary`). Every client receives this entry,
29
+ * live and on replay alike: the stream delivers what the store kept.
30
+ */
31
+ export const OMITTED_BINARY_META_KEY = "agent-server/omittedBinary";
32
+ const id = z.string().min(1).max(512);
33
+ const seq = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
34
+ /** A history: the store that writes it (`sourceId`) and its session. */
35
+ export const SessionRefSchema = z.object({ sourceId: id, sessionId: id });
36
+ /** Keep the original JSON intact. Decoding for display is a separate operation,
37
+ * so an older relay cannot strip a newer producer's fields or unknown parts. */
38
+ export const HistoryRecordSchema = z.object({ seq: seq.min(1), event: z.unknown() });
39
+ /**
40
+ * Why a history operation was refused. Stores throw it and the wire carries
41
+ * its code unchanged, so a remote store fails the way a local one does:
42
+ * - `unknownHistory`: no such history, or not at the requested version;
43
+ * - `historyConflict`: the request contradicts committed history (another
44
+ * payload or hash for a committed version, a stale expected head, a reused
45
+ * commit id);
46
+ * - `notAuthorized`: the host refused this caller;
47
+ * - `invalidParams`: a malformed request, or one this store cannot hold.
48
+ * None of these succeed when retried unchanged.
49
+ */
50
+ export class HistoryError extends WireRefusal {
51
+ name = "HistoryError";
52
+ }
53
+ export const HISTORY_REFUSALS = [
54
+ "unknownHistory",
55
+ "historyConflict",
56
+ "notAuthorized",
57
+ "invalidParams",
58
+ ];
59
+ const REFUSALS = new Set(HISTORY_REFUSALS);
60
+ /** Whether a wire error name is one a history store refuses with. */
61
+ export function isHistoryRefusal(name) {
62
+ return name !== undefined && REFUSALS.has(name);
63
+ }
64
+ /** Parse a history request or slice, refusing a malformed one as `invalidParams`,
65
+ * the way a remote store refuses it. */
66
+ export function parseHistoryRequest(schema, value) {
67
+ const parsed = schema.safeParse(value);
68
+ if (!parsed.success)
69
+ throw new HistoryError("invalidParams", parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; "));
70
+ return parsed.data;
71
+ }
72
+ export function jsonBytes(value) {
73
+ return new TextEncoder().encode(JSON.stringify(value)).byteLength;
74
+ }
75
+ /** Records a history holds: contiguous, well formed where their type is known, and history events. */
76
+ export function validateHistoryRecords(sessionId, records) {
77
+ let previous;
78
+ for (const record of records) {
79
+ if (previous !== undefined && record.seq !== previous + 1)
80
+ throw new HistoryError("invalidParams", "History records must be contiguous and ordered");
81
+ // Unknown event types are kept as they are; a known type must be well formed.
82
+ let event;
83
+ try {
84
+ event = decodeLifecycleEvent(record.event);
85
+ }
86
+ catch {
87
+ throw new HistoryError("invalidParams", `History record ${record.seq} is a malformed event`);
88
+ }
89
+ validateHistoryEvent(sessionId, event);
90
+ previous = record.seq;
91
+ }
92
+ }
93
+ /** An event a history of `sessionId` holds: its session's, a part of its own message, and never
94
+ * raw harness output or a token delta. Throws `invalidParams` for any other. */
95
+ export function validateHistoryEvent(sessionId, event) {
96
+ if (event.sessionId !== sessionId)
97
+ throw new HistoryError("invalidParams", "History event belongs to a different session");
98
+ if (isUnknownEvent(event))
99
+ return;
100
+ if (event.type === "raw")
101
+ throw new HistoryError("invalidParams", "Raw harness records are not part of session history");
102
+ if (isLiveOnlyEvent(event))
103
+ throw new HistoryError("invalidParams", "Token deltas are live only, never part of session history");
104
+ if (event.type === "message.part" &&
105
+ (event.part.sessionId !== sessionId || event.part.messageId !== event.messageId))
106
+ throw new HistoryError("invalidParams", "History part belongs to a different message or session");
107
+ }
108
+ export const HistoryVersionSchema = SessionRefSchema.extend({
109
+ seq,
110
+ hash: z.string().regex(/^[a-f0-9]{64}$/),
111
+ });
112
+ export const HistoryDescriptorSchema = SessionRefSchema.extend({
113
+ format: z.literal(1),
114
+ kind: z.enum(["execution", "branch"]),
115
+ parent: HistoryVersionSchema.optional(),
116
+ });
117
+ export const HistoryHeadSchema = z.object({
118
+ descriptor: HistoryDescriptorSchema,
119
+ version: HistoryVersionSchema,
120
+ });
121
+ export const HistoryListSchema = z.object({
122
+ after: z.object({ storeId: z.string(), ref: SessionRefSchema }).optional(),
123
+ limit: z.number().int().min(1).max(100).default(50),
124
+ });
125
+ export const HistoryCatalogSchema = z.object({
126
+ entries: z.array(HistoryHeadSchema).max(100),
127
+ next: z.object({ storeId: z.string(), ref: SessionRefSchema }).nullable(),
128
+ });
129
+ export const HistoryReadSchema = SessionRefSchema.extend({
130
+ after: HistoryVersionSchema.optional(),
131
+ through: HistoryVersionSchema.optional(),
132
+ limit: z.number().int().min(1).max(HISTORY_MAX_RECORDS).default(HISTORY_MAX_RECORDS),
133
+ maxBytes: z.number().int().min(2048).max(HISTORY_MAX_BYTES).default(HISTORY_MAX_BYTES),
134
+ });
135
+ export const HistorySliceSchema = z.object({
136
+ descriptor: HistoryDescriptorSchema,
137
+ base: HistoryVersionSchema,
138
+ next: HistoryVersionSchema,
139
+ head: HistoryVersionSchema,
140
+ records: z.array(HistoryRecordSchema).max(HISTORY_MAX_RECORDS),
141
+ hasMore: z.boolean(),
142
+ });
143
+ export const HistoryForkSchema = z.object({
144
+ sessionId: id,
145
+ from: HistoryVersionSchema.optional(),
146
+ });
147
+ export const HistoryCommitSchema = z.object({
148
+ commitId: id,
149
+ expected: HistoryVersionSchema,
150
+ events: z.array(z.unknown()).min(1).max(HISTORY_MAX_RECORDS),
151
+ });
152
+ export const HistoryWaitSchema = z.object({
153
+ after: HistoryVersionSchema,
154
+ timeoutMs: z.number().int().min(0).max(20_000).default(HISTORY_WAIT_TIMEOUT_MS),
155
+ });
156
+ /** Projection cache format changes whenever reducer semantics become incompatible.
157
+ * Raw canonical events remain authoritative and are never pruned by this cache. */
158
+ export const CONVERSATION_CHECKPOINT_FORMAT = "agent-server.conversation.v1";
159
+ export const HistoryCheckpointRequestSchema = z.object({ through: HistoryVersionSchema });
160
+ export const HistoryCheckpointSchema = z.object({
161
+ version: HistoryVersionSchema,
162
+ format: z.string().min(1).max(128),
163
+ /** Unknown formats are ignored by older readers, who replay the canonical log. */
164
+ conversation: z.unknown(),
165
+ });
166
+ /**
167
+ * The hash chain every store computes alike. A history's version 0 hashes its
168
+ * canonical descriptor; each record's version hashes
169
+ * `canonicalJson({ event, previous, seq })` — built here from the
170
+ * record's canonical event JSON, so stored bodies hash without re-encoding.
171
+ * A version is the lowercase hex sha256 of its preimage.
172
+ */
173
+ export function historyRootPreimage(descriptor) {
174
+ return canonicalJson(descriptor);
175
+ }
176
+ export function historyRecordPreimage(previous, seq, body) {
177
+ return `{"event":${body},"previous":${JSON.stringify(previous)},"seq":${seq}}`;
178
+ }
179
+ export function sameHistory(a, b) {
180
+ return a.sourceId === b.sourceId && a.sessionId === b.sessionId;
181
+ }
182
+ export function sameVersion(a, b) {
183
+ return sameHistory(a, b) && a.seq === b.seq && a.hash === b.hash;
184
+ }
185
+ export function validateHistorySlice(value) {
186
+ const page = parseHistoryRequest(HistorySliceSchema, value);
187
+ if (jsonBytes(page) > HISTORY_MAX_BYTES)
188
+ throw new HistoryError("invalidParams", "History slice exceeds byte limit");
189
+ if (![page.base, page.next, page.head].every((v) => sameHistory(v, page.descriptor)))
190
+ throw new HistoryError("invalidParams", "History identity mismatch");
191
+ validateHistoryRecords(page.descriptor.sessionId, page.records);
192
+ const end = page.records.at(-1)?.seq ?? page.base.seq;
193
+ if ((page.records.length && page.records[0].seq !== page.base.seq + 1) ||
194
+ page.next.seq !== end ||
195
+ end > page.head.seq ||
196
+ page.hasMore !== end < page.head.seq ||
197
+ (!page.records.length && (!sameVersion(page.base, page.next) || page.hasMore)) ||
198
+ (end === page.head.seq && !sameVersion(page.next, page.head)))
199
+ throw new HistoryError("invalidParams", "Invalid history slice boundaries");
200
+ return page;
201
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * UUIDv7 — time-ordered identifiers. The leading 48 bits are a millisecond
3
+ * timestamp, so ids sort chronologically (handy for ordering parts/messages
4
+ * without a separate createdAt column). Pass `timestamp` when the id names
5
+ * something whose time you also report, so the two agree. Uses Web Crypto,
6
+ * available on both Bun and Node >= 20 via `globalThis.crypto`.
7
+ */
8
+ export function generateUUIDv7(timestamp = Date.now()) {
9
+ const rand = new Uint8Array(10);
10
+ crypto.getRandomValues(rand);
11
+ const bytes = new Uint8Array(16);
12
+ // 48-bit big-endian timestamp.
13
+ bytes[0] = (timestamp / 2 ** 40) & 0xff;
14
+ bytes[1] = (timestamp / 2 ** 32) & 0xff;
15
+ bytes[2] = (timestamp / 2 ** 24) & 0xff;
16
+ bytes[3] = (timestamp / 2 ** 16) & 0xff;
17
+ bytes[4] = (timestamp / 2 ** 8) & 0xff;
18
+ bytes[5] = timestamp & 0xff;
19
+ // version (7) + 4 bits random
20
+ bytes[6] = 0x70 | (rand[0] & 0x0f);
21
+ bytes[7] = rand[1];
22
+ // variant (10xx) + 6 bits random
23
+ bytes[8] = 0x80 | (rand[2] & 0x3f);
24
+ bytes[9] = rand[3];
25
+ bytes[10] = rand[4];
26
+ bytes[11] = rand[5];
27
+ bytes[12] = rand[6];
28
+ bytes[13] = rand[7];
29
+ bytes[14] = rand[8];
30
+ bytes[15] = rand[9];
31
+ const hex = [];
32
+ for (let i = 0; i < 16; i++)
33
+ hex.push(bytes[i].toString(16).padStart(2, "0"));
34
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex
35
+ .slice(6, 8)
36
+ .join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
37
+ }
@@ -0,0 +1,36 @@
1
+ // @zvada/agent-server/protocol — the wire contract.
2
+ // Normalized data shapes shared by the engine and every consumer.
3
+ export * from "./ids.js";
4
+ export * from "./async-queue.js";
5
+ export * from "./meta.js";
6
+ export * from "./meta-keys.js";
7
+ export * from "./time.js";
8
+ export * from "./vocabulary.js";
9
+ export * from "./errors.js";
10
+ export * from "./tokens.js";
11
+ export * from "./tool-state.js";
12
+ export * from "./guards.js";
13
+ export * from "./parts.js";
14
+ export * from "./part-input.js";
15
+ export * from "./factories.js";
16
+ export * from "./harness.js";
17
+ export * from "./thinking.js";
18
+ export * from "./models.js";
19
+ export * from "./clis.js";
20
+ export * from "./account.js";
21
+ export * from "./auth.js";
22
+ export * from "./credentials.js";
23
+ export * from "./config.js";
24
+ export * from "./execution.js";
25
+ export * from "./lifecycle.js";
26
+ export * from "./stop-reasons.js";
27
+ export * from "./seq-cursor.js";
28
+ export * from "./conversation.js";
29
+ export * from "./tool-closure.js";
30
+ export * from "./reduce.js";
31
+ export * from "./selectors.js";
32
+ export * from "./verify.js";
33
+ export * from "./wire.js";
34
+ export * from "./wire-api.js";
35
+ export * from "./canonical.js";
36
+ export * from "./history.js";