@zvada/agent-server 0.3.23 → 0.3.25

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 (280) hide show
  1. package/CHANGELOG.md +64 -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 +745 -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 +331 -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 +92 -0
  91. package/dist/core/processes/lifeline.js +218 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +164 -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 +29 -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 +437 -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 +339 -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 +142 -0
  141. package/dist/protocol/errors.js +190 -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 +292 -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/client/client.d.ts +6 -1
  207. package/dist/types/client/client.d.ts.map +1 -1
  208. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  210. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/options.d.ts +28 -11
  212. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  213. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  214. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  216. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  218. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  219. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  220. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  221. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  222. package/dist/types/core/agents/process-pool.d.ts +8 -0
  223. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  224. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  225. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  226. package/dist/types/core/presets.d.ts +2 -2
  227. package/dist/types/core/presets.d.ts.map +1 -1
  228. package/dist/types/core/processes/identity.d.ts.map +1 -1
  229. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  230. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  231. package/dist/types/core/provision/extract.d.ts.map +1 -1
  232. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  233. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  234. package/dist/types/core/runtime/turn.d.ts +12 -7
  235. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  236. package/dist/types/protocol/clis.d.ts +3 -3
  237. package/dist/types/protocol/conversation.d.ts +6 -6
  238. package/dist/types/protocol/credentials.d.ts +13 -1
  239. package/dist/types/protocol/credentials.d.ts.map +1 -1
  240. package/dist/types/protocol/errors.d.ts +6 -4
  241. package/dist/types/protocol/errors.d.ts.map +1 -1
  242. package/dist/types/protocol/lifecycle.d.ts +4 -4
  243. package/dist/types/protocol/wire-api.d.ts +12 -12
  244. package/dist/types/protocol/wire.d.ts +8 -8
  245. package/dist/types/server/bin.d.ts +3 -0
  246. package/dist/types/server/bin.d.ts.map +1 -0
  247. package/dist/types/server/routes.d.ts.map +1 -1
  248. package/dist/types/server/transports.d.ts +2 -1
  249. package/dist/types/server/transports.d.ts.map +1 -1
  250. package/dist/types/sync/node-sqlite.d.ts +4 -1
  251. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  252. package/docs/consuming.md +56 -7
  253. package/docs/deploy.md +35 -0
  254. package/docs/harnesses.md +30 -5
  255. package/package.json +43 -18
  256. package/src/client/client.ts +114 -44
  257. package/src/core/agents/claude-code/approvals.ts +5 -1
  258. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  259. package/src/core/agents/claude-code/options.ts +28 -11
  260. package/src/core/agents/claude-code/session.ts +13 -0
  261. package/src/core/agents/codex-app-server/homes.ts +11 -2
  262. package/src/core/agents/codex-app-server/login.ts +30 -0
  263. package/src/core/agents/codex-app-server/requests.ts +7 -6
  264. package/src/core/agents/codex-app-server/session.ts +11 -2
  265. package/src/core/agents/process-pool.ts +30 -4
  266. package/src/core/agents/scripted/scripted-agent.ts +2 -1
  267. package/src/core/agents/scripted/steps.ts +1 -1
  268. package/src/core/presets.ts +3 -2
  269. package/src/core/processes/identity.ts +1 -0
  270. package/src/core/processes/lifeline.ts +10 -1
  271. package/src/core/processes/process-table.ts +1 -0
  272. package/src/core/provision/extract.ts +1 -0
  273. package/src/core/runtime/agent-runtime.ts +6 -3
  274. package/src/core/runtime/turn.ts +21 -9
  275. package/src/protocol/credentials.ts +19 -5
  276. package/src/protocol/errors.ts +12 -3
  277. package/src/server/bin.ts +25 -10
  278. package/src/server/routes.ts +3 -2
  279. package/src/server/transports.ts +6 -1
  280. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,142 @@
1
+ import { z } from "zod";
2
+ import { AccountInfoSchema } from "./account.js";
3
+ import { AgentHarnessSchema } from "./harness.js";
4
+ const ApiKeySchema = z.object({
5
+ type: z.literal("api_key"),
6
+ apiKey: z.string().min(1),
7
+ /** A gateway the key is for, in place of the provider's own API (Claude only). */
8
+ baseUrl: z.string().url().optional(),
9
+ });
10
+ const OAuthTokenSchema = z.object({
11
+ type: z.literal("oauth_token"),
12
+ accessToken: z.string().min(1),
13
+ /** Epoch ms; absent when unknown. */
14
+ expiresAt: z.number().int().optional(),
15
+ });
16
+ const ChatGptSchema = z.object({
17
+ type: z.literal("chatgpt"),
18
+ accessToken: z.string().min(1),
19
+ accountId: z.string().min(1),
20
+ plan: z.string().optional(),
21
+ expiresAt: z.number().int().optional(),
22
+ });
23
+ /**
24
+ * What a turn runs with when the product holds the login (LLP 0012), not the
25
+ * CLI: an `api_key` (either harness), Claude's `oauth_token` (the one-year
26
+ * token `setup-token` makes, or an access token), or Codex's `chatgpt` access
27
+ * token with its account. Secret: never answered back, logged or journaled.
28
+ */
29
+ export const HarnessCredentialSchema = z.discriminatedUnion("type", [
30
+ ApiKeySchema,
31
+ OAuthTokenSchema,
32
+ ChatGptSchema,
33
+ ]);
34
+ /** What Claude Code runs on: a key (to a gateway, too) or an OAuth token. */
35
+ export const ClaudeCredentialSchema = z.discriminatedUnion("type", [
36
+ ApiKeySchema,
37
+ OAuthTokenSchema,
38
+ ]);
39
+ /** What Codex runs on: a key to OpenAI's own API, or a ChatGPT token. */
40
+ export const CodexCredentialSchema = z.discriminatedUnion("type", [
41
+ // A key for another endpoint is Claude's alone; one whose `baseUrl` is there but undefined is not one.
42
+ ApiKeySchema.extend({ baseUrl: z.undefined().optional() }),
43
+ ChatGptSchema,
44
+ ]);
45
+ const RUNS_ON = {
46
+ "claude-code": ClaudeCredentialSchema,
47
+ "codex-app-server": CodexCredentialSchema,
48
+ };
49
+ export function credentialRunsOn(harness, credential) {
50
+ if (!Object.hasOwn(RUNS_ON, harness))
51
+ return { ok: false, error: `${harness} runs on no credential a product holds.` };
52
+ const parsed = RUNS_ON[harness].safeParse(credential);
53
+ if (parsed.success)
54
+ return { ok: true, credential: parsed.data };
55
+ const what = credential.type === "api_key" && credential.baseUrl
56
+ ? "a key for another endpoint"
57
+ : `a ${credential.type} credential`;
58
+ return { ok: false, error: `${harness} does not run on ${what}.` };
59
+ }
60
+ /**
61
+ * The SHA-256 (hex) a credential request names a refused token by
62
+ * (`rejectedSha256`): an engine sends it, a product compares it, never the token.
63
+ */
64
+ export async function tokenDigest(token) {
65
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
66
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
67
+ }
68
+ /**
69
+ * A JWT's claims, read, not verified: only ever of a token its issuer just
70
+ * answered over TLS, or the CLI that holds it. `{}` for anything else.
71
+ */
72
+ export function claimsOf(jwt) {
73
+ try {
74
+ const payload = (jwt.split(".")[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
75
+ const binary = atob(payload.padEnd(Math.ceil(payload.length / 4) * 4, "="));
76
+ // UTF-8, so an email in another script reads as it was written.
77
+ const text = new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
78
+ const parsed = JSON.parse(text);
79
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
80
+ ? parsed
81
+ : {};
82
+ }
83
+ catch {
84
+ return {};
85
+ }
86
+ }
87
+ /**
88
+ * What a product stores for an account it holds: who it is (`AccountInfo`),
89
+ * the credential a turn gets, and what renews it (a ChatGPT login's refresh
90
+ * token; nothing renews a key or Claude's one-year token). Secret, as its
91
+ * credential; `grantAuth` is what to show of it.
92
+ */
93
+ export const CredentialGrantSchema = AccountInfoSchema.extend({
94
+ harness: AgentHarnessSchema,
95
+ credential: HarnessCredentialSchema,
96
+ refreshToken: z.string().min(1).optional(),
97
+ /** Epoch ms, when it was obtained or last renewed. */
98
+ obtainedAt: z.number().int(),
99
+ });
100
+ /**
101
+ * What an engine asks a product's credential endpoint before a turn: whose
102
+ * credential (the session, the harness), and, when the harness refused the
103
+ * last one, its SHA-256 (hex), never the token: answer a fresher one.
104
+ */
105
+ export const CredentialRequestSchema = z.object({
106
+ harness: AgentHarnessSchema,
107
+ sessionId: z.string().min(1),
108
+ /** The turn it is for, where the engine knows it: a product that picks who pays per turn reads it. */
109
+ turnId: z.string().min(1).optional(),
110
+ rejectedSha256: z
111
+ .string()
112
+ .regex(/^[0-9a-f]{64}$/)
113
+ .optional(),
114
+ });
115
+ /** The endpoint's answer: the credential, or none (the engine's own CLI login runs the turn). */
116
+ export const CredentialAnswerSchema = z.object({
117
+ credential: HarnessCredentialSchema.nullable(),
118
+ });
119
+ /**
120
+ * The code a sign-in page showed, as pasted: `code#state`, the page's
121
+ * address, or the bare code (the sign-in's own state then goes with it). A
122
+ * state from another sign-in is refused.
123
+ */
124
+ export function pastedSignInCode(pasted, state) {
125
+ const text = pasted.trim();
126
+ let code = text;
127
+ let returned = null;
128
+ if (/^https?:\/\//i.test(text)) {
129
+ const url = URL.canParse(text) ? new URL(text) : undefined;
130
+ code = url?.searchParams.get("code") ?? "";
131
+ returned = url?.searchParams.get("state") ?? null;
132
+ }
133
+ else if (text.includes("#")) {
134
+ [code = "", returned = null] = text.split("#", 2);
135
+ }
136
+ if (returned !== null && returned !== state) {
137
+ throw new Error("This code is from another sign-in: paste the code this sign-in's page shows.");
138
+ }
139
+ if (!code)
140
+ throw new Error("Paste the code the sign-in page shows.");
141
+ return { code, state };
142
+ }
@@ -0,0 +1,190 @@
1
+ import { z } from "zod";
2
+ import { openVocabulary } from "./vocabulary.js";
3
+ /**
4
+ * The one error vocabulary (one shape per concept). Used by
5
+ * `turn.ended.error`, the standalone `error` event, and `RunSummary.error`.
6
+ *
7
+ * OPEN: products may extend it with their own categories (a "db_write", say);
8
+ * unknown non-`_` values are reserved for this protocol.
9
+ * `usage_limit` (plan/quota exhausted) and `rate_limit` (429/backoff) are
10
+ * deliberately distinct — they need different user guidance; collapsing them
11
+ * is a display choice, never a wire merge. So are `resume_failed` (the
12
+ * conversation is gone: offer a fresh start) and `resume_busy` (another
13
+ * process holds it now: try again once that one has let it go).
14
+ */
15
+ export const ERROR_CATEGORIES = [
16
+ "auth",
17
+ "rate_limit",
18
+ "overloaded",
19
+ "usage_limit",
20
+ "context_limit",
21
+ "network",
22
+ "abort",
23
+ "invalid_request",
24
+ "process_exit",
25
+ "resume_failed",
26
+ "resume_busy",
27
+ "mcp_unavailable",
28
+ "server_restart",
29
+ "internal",
30
+ ];
31
+ export const ErrorCategorySchema = openVocabulary(ERROR_CATEGORIES);
32
+ /** A category this build knows, or a product's `_`-prefixed extension. */
33
+ function isErrorCategory(value) {
34
+ return (typeof value === "string" &&
35
+ (ERROR_CATEGORIES.includes(value) || /^_\S/.test(value)));
36
+ }
37
+ export const ErrorInfoSchema = z.object({
38
+ category: ErrorCategorySchema,
39
+ message: z.string(),
40
+ });
41
+ /**
42
+ * Maps a raw harness error into a stable category, so callers can react
43
+ * (retry on `network`/`rate_limit`, surface `auth` prominently, treat `abort`
44
+ * as success). Rule order matters. Distilled from deus-machine's lifecycle
45
+ * classifier; lives in /protocol because categories are vocabulary.
46
+ */
47
+ const RULES = [
48
+ // Codex 0.160 and newer: another app-server holds the thread warm.
49
+ ["resume_busy", ["already has an active writer"]],
50
+ ["resume_failed", ["no conversation found with session id", "no rollout found for thread id"]],
51
+ ["abort", ["aborted", "aborterror", "cancelled", "canceled", "interrupted", "sigint"]],
52
+ [
53
+ "auth",
54
+ [
55
+ "unauthorized",
56
+ "401",
57
+ "authentication",
58
+ "invalid api key",
59
+ "invalid_api_key",
60
+ "not logged in",
61
+ "login required",
62
+ "forbidden",
63
+ "403",
64
+ ],
65
+ ],
66
+ ["rate_limit", ["rate limit", "rate_limit", "429", "too many requests"]],
67
+ ["overloaded", ["overloaded", "at capacity", "server_overloaded"]],
68
+ [
69
+ "usage_limit",
70
+ [
71
+ "usage limit",
72
+ "quota",
73
+ "insufficient_quota",
74
+ "billing",
75
+ "credit",
76
+ // Claude Code's "You've hit your session limit · resets …" and the like.
77
+ "ve hit your",
78
+ ],
79
+ ],
80
+ [
81
+ "context_limit",
82
+ [
83
+ "context length",
84
+ "context_length",
85
+ "maximum context",
86
+ "too many tokens",
87
+ "prompt is too long",
88
+ ],
89
+ ],
90
+ [
91
+ "network",
92
+ [
93
+ "econnrefused",
94
+ "econnreset",
95
+ "etimedout",
96
+ "enotfound",
97
+ "network",
98
+ "fetch failed",
99
+ "socket hang up",
100
+ ],
101
+ ],
102
+ [
103
+ "invalid_request",
104
+ [
105
+ "invalid request",
106
+ "invalid_request_error",
107
+ "status 400",
108
+ "http 400",
109
+ "bad request",
110
+ // Claude Code's wording for an unknown or inaccessible model.
111
+ "issue with the selected model",
112
+ ],
113
+ ],
114
+ [
115
+ "process_exit",
116
+ [
117
+ "exited with code",
118
+ "process exited",
119
+ // Claude's SDK when its CLI died to a signal (SIGKILL, an OOM kill).
120
+ "terminated by signal",
121
+ "spawn",
122
+ "enoent",
123
+ "killed",
124
+ ],
125
+ ],
126
+ ];
127
+ export function classifyError(error) {
128
+ // An error that names its own category (the engine's typed errors do) is
129
+ // already classified: an agent's exit carries its stderr, whose words
130
+ // ("aborted", a "429" in a stack trace) must not pass for a cancel or a
131
+ // rate limit, and an MCP server's cause is not the model provider's.
132
+ if (error instanceof Error && "category" in error && isErrorCategory(error.category))
133
+ return error.category;
134
+ const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
135
+ for (const [category, needles] of RULES) {
136
+ if (needles.some((n) => mentions(message, n)))
137
+ return category;
138
+ }
139
+ return "internal";
140
+ }
141
+ /**
142
+ * A status code counts where it stands as a number of its own, never inside
143
+ * a longer number ("240129 tokens") or an identifier's alphanumeric run (a
144
+ * thread id's "-b401-" or "-a429-"): no letter or digit touches it.
145
+ */
146
+ function mentions(message, needle) {
147
+ if (!/\d$/.test(needle))
148
+ return message.includes(needle);
149
+ for (let at = message.indexOf(needle); at >= 0; at = message.indexOf(needle, at + 1)) {
150
+ const before = message[at - 1] ?? "";
151
+ const after = message[at + needle.length] ?? "";
152
+ if (!/[a-z0-9]/.test(before) && !/[a-z0-9]/.test(after))
153
+ return true;
154
+ }
155
+ return false;
156
+ }
157
+ /**
158
+ * The message to show for a failure. Providers often answer with a JSON
159
+ * envelope (`{"error":{"message":…}}`), sometimes behind a transport prefix;
160
+ * its message is the readable part. Classify the raw text first: the envelope
161
+ * carries the status and error type the rules match on.
162
+ */
163
+ export function readableErrorMessage(message) {
164
+ const start = message.indexOf("{");
165
+ if (start < 0)
166
+ return message;
167
+ try {
168
+ const body = JSON.parse(message.slice(start));
169
+ const inner = body.error?.message ?? body.message;
170
+ return typeof inner === "string" && inner ? inner : message;
171
+ }
172
+ catch {
173
+ return message;
174
+ }
175
+ }
176
+ /**
177
+ * The one mapping from a failure to the `ErrorInfo` the stream carries: its
178
+ * category, from the harness's typed code when it has one (that beats its
179
+ * text), else classified from its raw text, and its readable message.
180
+ */
181
+ export function errorInfo(error, typedCategory) {
182
+ return {
183
+ category: typedCategory ?? classifyError(error),
184
+ message: readableErrorMessage(error instanceof Error ? error.message : String(error)),
185
+ };
186
+ }
187
+ /** Abort is a user action, not a failure to report. */
188
+ export function isCancellation(error) {
189
+ return classifyError(error) === "abort";
190
+ }
@@ -0,0 +1,28 @@
1
+ import { z } from "zod";
2
+ import { ReportedPermissionModeSchema } from "./config.js";
3
+ import { HarnessIdSchema } from "./harness.js";
4
+ import { ThinkingLevelSchema } from "./thinking.js";
5
+ /** Safe, per-turn execution metadata. Never serialize the full RunConfig here. */
6
+ export const TurnExecutionSchema = z.object({
7
+ harness: HarnessIdSchema,
8
+ /** Model id/alias passed to the harness. Absent means the harness chose its default. */
9
+ model: z.string().optional(),
10
+ /** Requested setting, not a measurement of the model's internal reasoning. */
11
+ thinkingLevel: ThinkingLevelSchema.optional(),
12
+ /** The permission mode the turn asked for; the agent may switch it (`session.mode`). */
13
+ permissionMode: ReportedPermissionModeSchema.optional(),
14
+ /** The level the harness ran this turn at: the request fitted to the model's levels
15
+ * (`ultra` on a model topping out at `max` runs `max`), or the harness's own setting
16
+ * when the turn requested none. Only on `turn.ended`; absent when unknown or when the
17
+ * turn failed or was cancelled before the model answered. */
18
+ appliedThinkingLevel: ThinkingLevelSchema.optional(),
19
+ /** Distinct models the primary harness reported for this turn, in observation order:
20
+ * those its stream named, else the model Codex reported for the thread. Excludes
21
+ * subagents. Absence means unreported, never a fallback to the requested alias. */
22
+ reportedModels: z.array(z.string()).optional(),
23
+ /** The `RunConfig` fields this turn set that the harness did not apply: those it
24
+ * never applies (`AgentCapabilities.ignoredSettings`) on `turn.started`, and on
25
+ * `turn.ended` with them those it found it could not apply as it ran (an ACP agent
26
+ * that takes no extra directories). Absent when it applied everything the turn set. */
27
+ notApplied: z.array(z.string()).optional(),
28
+ });
@@ -0,0 +1,231 @@
1
+ import { generateUUIDv7 } from "./ids.js";
2
+ import { META_KEYS } from "./meta-keys.js";
3
+ export function createTextPart(ctx, text, streaming = true) {
4
+ return {
5
+ id: generateUUIDv7(),
6
+ sessionId: ctx.sessionId,
7
+ messageId: ctx.messageId,
8
+ ...(ctx.parentToolCallId && { parentToolCallId: ctx.parentToolCallId }),
9
+ type: "text",
10
+ text,
11
+ state: streaming ? "streaming" : "done",
12
+ };
13
+ }
14
+ export function createReasoningPart(ctx, text, streaming = true) {
15
+ return {
16
+ id: generateUUIDv7(),
17
+ sessionId: ctx.sessionId,
18
+ messageId: ctx.messageId,
19
+ ...(ctx.parentToolCallId && { parentToolCallId: ctx.parentToolCallId }),
20
+ type: "reasoning",
21
+ text,
22
+ state: streaming ? "streaming" : "done",
23
+ };
24
+ }
25
+ function toolBase(ctx, toolCallId, toolName, meta) {
26
+ return {
27
+ id: generateUUIDv7(),
28
+ sessionId: ctx.sessionId,
29
+ messageId: ctx.messageId,
30
+ ...(ctx.parentToolCallId && { parentToolCallId: ctx.parentToolCallId }),
31
+ type: "tool",
32
+ toolCallId,
33
+ toolName,
34
+ ...(meta?.subagent ? { kind: "task" } : meta?.kind ? { kind: meta.kind } : {}),
35
+ ...(meta?.mcp && { mcp: { ...meta.mcp } }),
36
+ ...(meta?.title && { title: meta.title }),
37
+ ...(meta?.command && { command: meta.command }),
38
+ ...(meta?.url && { url: meta.url }),
39
+ ...(meta?.locations?.length && { locations: meta.locations }),
40
+ ...(meta?.subagent && { subagent: meta.subagent }),
41
+ };
42
+ }
43
+ export function createToolPart(ctx, toolCallId, toolName, input, meta) {
44
+ return {
45
+ ...toolBase(ctx, toolCallId, toolName, meta),
46
+ state: { status: "in_progress", input, time: { start: Date.now() } },
47
+ };
48
+ }
49
+ /** A tool call whose input is still streaming in (partial JSON not yet parseable). */
50
+ export function createPendingToolPart(ctx, toolCallId, toolName, meta) {
51
+ return {
52
+ ...toolBase(ctx, toolCallId, toolName, meta),
53
+ state: { status: "pending", partialInput: "" },
54
+ };
55
+ }
56
+ /** Mutates a pending tool part into `in_progress` once its input has fully parsed. */
57
+ export function startToolPart(part, input) {
58
+ if (part.state.status === "pending") {
59
+ part.state = { status: "in_progress", input, time: { start: Date.now() } };
60
+ }
61
+ }
62
+ /** Appends a streamed JSON fragment to a still-pending tool part. */
63
+ export function appendToolInput(part, partialJson) {
64
+ if (part.state.status === "pending") {
65
+ part.state.partialInput += partialJson;
66
+ }
67
+ }
68
+ /**
69
+ * `part` with `delta` applied, as a new part: a text or reasoning part gains
70
+ * the delta's text, a pending tool its streamed input. Undefined for a delta
71
+ * the part does not take (another part type, a tool no longer pending). The
72
+ * engine's processor, the server's open parts and the reducer all extend a
73
+ * part with this one function, so the snapshot a joiner receives equals what
74
+ * a client that saw every delta folded.
75
+ */
76
+ export function extendPart(part, delta) {
77
+ if (delta.type === "tool_input") {
78
+ if (part.type !== "tool" || part.state.status !== "pending")
79
+ return undefined;
80
+ return {
81
+ ...part,
82
+ state: { ...part.state, partialInput: part.state.partialInput + delta.input },
83
+ };
84
+ }
85
+ if ((part.type === "text" || part.type === "reasoning") && part.type === delta.type)
86
+ return { ...part, text: part.text + delta.text };
87
+ return undefined;
88
+ }
89
+ /** Attach/refresh normalized metadata on an existing tool part. */
90
+ export function setToolMeta(part, meta) {
91
+ if (meta.subagent) {
92
+ part.subagent = meta.subagent;
93
+ part.kind = "task";
94
+ }
95
+ else if (meta.kind) {
96
+ part.kind = meta.kind;
97
+ }
98
+ if (meta.mcp)
99
+ part.mcp = { ...meta.mcp };
100
+ if (meta.title)
101
+ part.title = meta.title;
102
+ if (meta.command)
103
+ part.command = meta.command;
104
+ if (meta.url)
105
+ part.url = meta.url;
106
+ if (meta.locations?.length)
107
+ part.locations = meta.locations;
108
+ }
109
+ /**
110
+ * Mutates a tool part into its terminal `completed`/`failed` state. A failure
111
+ * keeps its `metadata` (a command's exit code) and drops its `content`: what
112
+ * a failed call would have shown did not happen.
113
+ */
114
+ export function completeToolPart(part, result) {
115
+ const start = part.state.status === "in_progress" ? part.state.time.start : Date.now();
116
+ const input = "input" in part.state ? part.state.input : {};
117
+ part.state = result.isError
118
+ ? {
119
+ status: "failed",
120
+ input,
121
+ error: result.output,
122
+ ...(result.metadata && { metadata: result.metadata }),
123
+ time: { start, end: Date.now() },
124
+ }
125
+ : {
126
+ status: "completed",
127
+ input,
128
+ output: result.output,
129
+ ...(result.title !== undefined && { title: result.title }),
130
+ ...(result.content?.length && { content: result.content }),
131
+ ...(result.metadata && { metadata: result.metadata }),
132
+ time: { start, end: Date.now() },
133
+ };
134
+ }
135
+ // @ref LLP 0002#engine-minted-ids — the echo is the one exception
136
+ /**
137
+ * The user echo's message id, derived from the turn id.
138
+ *
139
+ * A deliberate exception to engine-minted UUIDv7 ids: the echo
140
+ * is not new information, it is the caller's own input played back, and one
141
+ * turn has exactly one echo message (plus one per steer, see
142
+ * `steerMessageId`). Deriving the id means a consumer can
143
+ * predict the echo byte-for-byte from the `turnId` it minted — so an
144
+ * optimistically-rendered prompt bubble IS the echo (same id, same parts)
145
+ * instead of a look-alike that has to be reconciled and swapped. The
146
+ * reconcile-by-turnId dance every product wrote is what this replaces.
147
+ *
148
+ * Ids stay opaque to peers: nothing may parse structure out of them. This is a
149
+ * PRODUCER rule (how the engine mints), matched by a consumer helper — not a
150
+ * licence to infer turn ids from message ids elsewhere.
151
+ *
152
+ * Two consequences of NOT being UUIDv7, for consumers that leaned on its side
153
+ * effects: echo ids do not TIME-SORT against UUIDv7 ids (`echo-` sorts
154
+ * after every hex digit — never order by id), and they do not fit uuid-typed
155
+ * columns or id-derived timestamps (`createdAtFromUUID7(echoId)` is 0 — derive
156
+ * the echo's time from the `turnId` FIELD the event/row carries, never by
157
+ * parsing the echo id string; ids stay opaque).
158
+ */
159
+ export function echoMessageId(turnId) {
160
+ return `echo-${turnId}`;
161
+ }
162
+ /** The id of the echo part at `index` — same derivation, same predictability. */
163
+ export function echoPartId(turnId, index) {
164
+ return `echo-${turnId}-${index}`;
165
+ }
166
+ /**
167
+ * The message id of a steer's echo: the user message a steer becomes once the
168
+ * agent reads it, derived from the steer id the way the turn's echo is derived
169
+ * from the turn id, so the sender can predict it.
170
+ */
171
+ export function steerMessageId(steerId) {
172
+ return `steer-${steerId}`;
173
+ }
174
+ /** The id of a steer echo's part at `index`. */
175
+ export function steerPartId(steerId, index) {
176
+ return `steer-${steerId}-${index}`;
177
+ }
178
+ /**
179
+ * Build the parts for the user echo from a turn's input. Part ids
180
+ * are derived from the turn (see `echoPartId`), so the whole echo message is
181
+ * predictable from `{turnId, input}` alone. The EventProcessor stamps
182
+ * `sessionId`/`messageId` at emit time. Text `elements` spans ride `_meta`
183
+ * (the part vocabulary stays output-shaped; the spans are UI-authored
184
+ * annotations).
185
+ */
186
+ export function createUserEchoParts(input, turnId) {
187
+ return echoParts(input, (index) => echoPartId(turnId, index));
188
+ }
189
+ /** The parts of a steer's echo, predictable from `{steerId, input}` alone. */
190
+ export function createSteerEchoParts(input, steerId) {
191
+ return echoParts(input, (index) => steerPartId(steerId, index));
192
+ }
193
+ function echoParts(input, partId) {
194
+ const items = typeof input === "string" ? [{ type: "text", text: input }] : input;
195
+ const parts = [];
196
+ for (let index = 0; index < items.length; index++) {
197
+ const item = items[index];
198
+ const base = { id: partId(index), sessionId: "", messageId: "" };
199
+ if (item.type === "text") {
200
+ parts.push({
201
+ ...base,
202
+ type: "text",
203
+ text: item.text,
204
+ state: "done",
205
+ ...("elements" in item && item.elements?.length
206
+ ? { _meta: { [META_KEYS.elements]: item.elements } }
207
+ : {}),
208
+ });
209
+ }
210
+ else if (item.type === "image") {
211
+ parts.push({
212
+ ...base,
213
+ type: "image",
214
+ ...(item.data !== undefined && { data: item.data }),
215
+ ...(item.url !== undefined && { url: item.url }),
216
+ mimeType: item.mimeType,
217
+ });
218
+ }
219
+ else {
220
+ parts.push({
221
+ ...base,
222
+ type: "file",
223
+ ...(item.data !== undefined && { data: item.data }),
224
+ ...(item.url !== undefined && { url: item.url }),
225
+ mimeType: item.mimeType,
226
+ ...(item.filename !== undefined && { filename: item.filename }),
227
+ });
228
+ }
229
+ }
230
+ return parts;
231
+ }
@@ -0,0 +1,71 @@
1
+ export const PART_TYPES = ["text", "reasoning", "tool", "subagent", "image", "file"];
2
+ export function isKnownPartType(type) {
3
+ return typeof type === "string" && PART_TYPES.includes(type);
4
+ }
5
+ export function isUnknownPart(part) {
6
+ return !isKnownPartType(part.type);
7
+ }
8
+ // No per-type guards for known parts: `p.type === "text"` narrows natively.
9
+ export const LIFECYCLE_EVENT_TYPES = [
10
+ "session.created",
11
+ "session.ended",
12
+ "turn.started",
13
+ "message.started",
14
+ "message.part",
15
+ "message.part.delta",
16
+ "message.ended",
17
+ "turn.ended",
18
+ "session.usage",
19
+ "session.limits",
20
+ "session.mode",
21
+ "session.compaction",
22
+ "error",
23
+ "permission.requested",
24
+ "permission.resolved",
25
+ "elicitation.requested",
26
+ "elicitation.resolved",
27
+ "raw",
28
+ ];
29
+ export function isKnownLifecycleEventType(type) {
30
+ return typeof type === "string" && LIFECYCLE_EVENT_TYPES.includes(type);
31
+ }
32
+ export function isUnknownEvent(event) {
33
+ return !isKnownLifecycleEventType(event.type);
34
+ }
35
+ /**
36
+ * Whether a server delivers this event without keeping it: a token delta,
37
+ * which takes no `seq` of its own (see `SeqCursor.advanceLive`) and which
38
+ * replay and history never return.
39
+ */
40
+ export function isLiveOnlyEvent(event) {
41
+ return event.type === "message.part.delta";
42
+ }
43
+ /**
44
+ * Whether the server sent this frame without keeping it: a token delta, or an
45
+ * open part sent after a subscription (`live: true`). Either carries the seq
46
+ * of the last kept event before it: fold it with `SeqCursor.advanceLive`.
47
+ */
48
+ export function isLiveEnvelope(envelope) {
49
+ return envelope.live === true || isLiveOnlyEvent(envelope.event);
50
+ }
51
+ // @ref LLP 0002#permissions — the four ACP option kinds, where the engine keeps "always"
52
+ /**
53
+ * The standard options of a brokered permission request whose harness keeps
54
+ * no "always" of its own: the broker offers the `*_always` kinds the schema
55
+ * advertises, and a "don't ask again" answer becomes a standing per-session
56
+ * rule. A client that renders no options answers with these ids.
57
+ */
58
+ export const STANDARD_PERMISSION_OPTIONS = [
59
+ { optionId: "allow", name: "Allow", kind: "allow_once" },
60
+ { optionId: "allow_always", name: "Always allow", kind: "allow_always" },
61
+ { optionId: "reject", name: "Reject", kind: "reject_once" },
62
+ { optionId: "reject_always", name: "Always reject", kind: "reject_always" },
63
+ ];
64
+ /** Whether an option kind approves the call. Exact: a kind this build does not know never does. */
65
+ export function isAllowKind(kind) {
66
+ return kind === "allow_once" || kind === "allow_always";
67
+ }
68
+ /** Whether an option kind refuses the call. Exact: a kind this build does not know might not. */
69
+ export function isRejectKind(kind) {
70
+ return kind === "reject_once" || kind === "reject_always";
71
+ }