@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,562 @@
1
+ import { z } from "zod";
2
+ import { ReportedPermissionModeSchema } from "./config.js";
3
+ import { ErrorCategorySchema, ErrorInfoSchema } from "./errors.js";
4
+ import { TurnExecutionSchema } from "./execution.js";
5
+ import { isKnownLifecycleEventType } from "./guards.js";
6
+ import { HarnessIdSchema } from "./harness.js";
7
+ import { MetaSchema } from "./meta.js";
8
+ import { PartSchema, decodePart } from "./parts.js";
9
+ import { EpochMsSchema } from "./time.js";
10
+ import { TokenUsageSchema } from "./tokens.js";
11
+ import { McpToolSchema, ToolKindSchema, ToolLocationSchema } from "./tool-state.js";
12
+ import { openVocabulary } from "./vocabulary.js";
13
+ /**
14
+ * The normalized event stream every harness is funneled into. Consumers (a WS
15
+ * bridge, an SSE endpoint, a CLI, a test sink) subscribe to these and never see
16
+ * raw SDK payloads. All keys are camelCase; serialize at your transport edge.
17
+ * Every event carries `sessionId`, `timestamp` (epoch ms), and `_meta`.
18
+ *
19
+ * Ordering within a turn:
20
+ * turn.started
21
+ * -> [ USER ECHO: message.started{role:"user", outputIndex:0}
22
+ * -> message.part* -> message.ended ]
23
+ * -> ( message.started{role:"assistant"} -> message.part*
24
+ * / message.part.delta* -> message.ended )*
25
+ * -> turn.ended
26
+ * session.created lands WHEN THE HARNESS FIRST REPORTS its native session id
27
+ * — its first yield — so arriving MID-TURN, after the echo and before the
28
+ * first assistant message, is the normal case rather than an anomaly. It
29
+ * cannot be hoisted: the id does not exist until the harness produces it,
30
+ * and holding the echo back for it would delay the transcript of every turn
31
+ * on a subprocess spawn. It comes when it says something new (the session's
32
+ * first native id, a new one, or a resume that did not continue), not on
33
+ * every turn. Persist it whenever it arrives; never treat it as a turn
34
+ * preamble.
35
+ * session.compaction may appear anywhere within a turn (position = first
36
+ * appearance). permission.*, elicitation.* and raw interleave anywhere
37
+ * within a turn.
38
+ * session.ended may follow at any later point.
39
+ *
40
+ * Exceptions to strict message bracketing:
41
+ * - a `message.part` may arrive after its message (or turn) ended — a tool
42
+ * completing late. The event's `messageId` names the ORIGINAL message and
43
+ * the upsert lands there.
44
+ * - snapshots are authoritative over deltas: a content-bearing `message.part`
45
+ * wipes the delta accumulator for that part; later deltas append to the
46
+ * replacement. A non-terminal snapshot carries the complete content so far,
47
+ * including earlier deltas, rather than a fragment to append.
48
+ */
49
+ /**
50
+ * Why a turn stopped (ACP StopReason verbatim, plus `error`). Normalized
51
+ * terminal status; the raw provider string travels in `finishReason`.
52
+ *
53
+ * OPEN: `_`-prefixed values are adapter extensions; unknown non-`_` values are
54
+ * reserved for this protocol and MUST be preserved. `refusal` covers provider
55
+ * content-filter/safety stops.
56
+ */
57
+ export const STOP_REASONS = [
58
+ "end_turn",
59
+ "max_tokens",
60
+ "max_turn_requests",
61
+ "refusal",
62
+ "cancelled",
63
+ "error",
64
+ ];
65
+ export const StopReasonSchema = openVocabulary(STOP_REASONS);
66
+ /** Why a session ended. OPEN. `closed`: `session/close` released it. */
67
+ export const SESSION_END_REASONS = ["closed"];
68
+ export const SessionEndReasonSchema = openVocabulary(SESSION_END_REASONS);
69
+ /** Compaction entity status. OPEN. */
70
+ export const COMPACTION_STATUSES = ["in_progress", "completed", "failed", "cancelled"];
71
+ export const CompactionStatusSchema = openVocabulary(COMPACTION_STATUSES);
72
+ /** What caused a compaction (Claude: `auto` | `manual`). OPEN. */
73
+ export const COMPACTION_TRIGGERS = ["auto", "manual"];
74
+ export const CompactionTriggerSchema = openVocabulary(COMPACTION_TRIGGERS);
75
+ /** The session and turn an event belongs to, after its `type`. */
76
+ const inTurn = { sessionId: z.string(), turnId: z.string() };
77
+ /** What every event ends with: when it happened, and its extensions. */
78
+ const stamped = { timestamp: EpochMsSchema, _meta: MetaSchema };
79
+ // ---- session events ---------------------------------------------------------
80
+ /** Emitted once the harness-native session id is known — persist it to resume later. */
81
+ export const SessionCreatedEventSchema = z.object({
82
+ type: z.literal("session.created"),
83
+ sessionId: z.string(),
84
+ /** Native id to pass back as `resumeSessionId` (Claude session_id / Codex threadId). */
85
+ nativeSessionId: z.string(),
86
+ harness: HarnessIdSchema,
87
+ model: z.string().optional(),
88
+ /**
89
+ * Present only when this turn requested a resume: whether the harness
90
+ * actually continued that conversation. `false` = it fell back to a fresh
91
+ * session (context lost) — surface this, never swallow it. Compare with
92
+ * this flag, not ids: some harnesses mint a NEW nativeSessionId on a
93
+ * successful resume (Claude). Built-in harnesses fail instead of starting
94
+ * fresh; `false` remains readable for older engines and custom harnesses.
95
+ */
96
+ resumed: z.boolean().optional(),
97
+ ...stamped,
98
+ });
99
+ /** The session is over: nothing more arrives for it, and its id is not reused. */
100
+ export const SessionEndedEventSchema = z.object({
101
+ type: z.literal("session.ended"),
102
+ sessionId: z.string(),
103
+ reason: SessionEndReasonSchema,
104
+ ...stamped,
105
+ });
106
+ /**
107
+ * Context-window gauge, emitted whenever the harness reports fresh numbers
108
+ * (per model message on Claude, per token-count update on Codex, per ACP
109
+ * `usage_update`). Vocabulary tracks ACP's stable `usage_update` shape:
110
+ * `used`/`size`/`cost`. Distinct from `turn.ended.tokens`, which is the
111
+ * turn's billing total — this is "how full is the session right now".
112
+ */
113
+ export const SessionUsageEventSchema = z.object({
114
+ type: z.literal("session.usage"),
115
+ ...inTurn,
116
+ /** Tokens currently occupying the context window (prompt + output). */
117
+ used: z.number(),
118
+ /** The model's context-window size, when the harness reports it. */
119
+ size: z.number().optional(),
120
+ /** Cumulative session cost in USD, when the harness reports it. */
121
+ cost: z.number().optional(),
122
+ ...stamped,
123
+ });
124
+ /** OPEN. `limited`: the account has hit a window and turns will fail until it resets. */
125
+ export const LIMIT_STATUSES = ["ok", "warning", "limited"];
126
+ export const LimitStatusSchema = openVocabulary(LIMIT_STATUSES);
127
+ /** One usage window of the account's plan, as the provider last reported it. */
128
+ export const LimitWindowSchema = z.object({
129
+ /** The provider's name for the window: `five_hour`, `seven_day`, … */
130
+ id: z.string(),
131
+ /** How much of the window is used, 0–100. */
132
+ usedPercent: z.number().optional(),
133
+ /** When the window resets. */
134
+ resetsAt: EpochMsSchema.optional(),
135
+ /** The window's length, when the provider says. */
136
+ windowMinutes: z.number().optional(),
137
+ /** This window's own status, when the provider reports one per window (Claude). */
138
+ status: LimitStatusSchema.optional(),
139
+ });
140
+ /**
141
+ * The account's plan usage, whenever the harness reports it (Claude's
142
+ * `rate_limit_event`, Codex's `account/rateLimits/updated`): how much of each
143
+ * window is used and when it resets. A report may carry only the windows that
144
+ * changed; consumers merge by `id` (the reducer does).
145
+ */
146
+ export const SessionLimitsEventSchema = z.object({
147
+ type: z.literal("session.limits"),
148
+ ...inTurn,
149
+ /** The account's overall status, when the provider reports one for the whole report (Codex). */
150
+ status: LimitStatusSchema.optional(),
151
+ windows: z.array(LimitWindowSchema),
152
+ /** The plan the account is on, when the harness says (`plus`, `max`, …). */
153
+ planType: z.string().optional(),
154
+ ...stamped,
155
+ });
156
+ /**
157
+ * The agent changed the session's permission mode during the turn: it left
158
+ * plan mode when the user approved its plan, or entered it by itself. Later
159
+ * turns run in the mode they ask for, so a client that follows the agent asks
160
+ * for this one (ACP's `current_mode_update`).
161
+ */
162
+ export const SessionModeEventSchema = z.object({
163
+ type: z.literal("session.mode"),
164
+ ...inTurn,
165
+ permissionMode: ReportedPermissionModeSchema,
166
+ ...stamped,
167
+ });
168
+ /**
169
+ * The compaction entity: an ID-addressed, POSITIONAL timeline entity — UPSERT
170
+ * by `compactionId`. The first event for an id anchors the entity's position
171
+ * in the ordered stream (the reducer places it there in the timeline); later
172
+ * upserts advance `status` and stream `summary` without moving it. Neither a
173
+ * part nor a bare notification: a replayed transcript needs the divider IN the
174
+ * order (Codex deprecated their session-level notification for exactly this;
175
+ * matches ACP's session-compaction draft so a future binding is a passthrough).
176
+ */
177
+ export const SessionCompactionEventSchema = z.object({
178
+ type: z.literal("session.compaction"),
179
+ ...inTurn,
180
+ compactionId: z.string(),
181
+ status: CompactionStatusSchema,
182
+ /** What triggered it, when known (Claude: `manual` | `auto`). */
183
+ trigger: CompactionTriggerSchema.optional(),
184
+ /** Context tokens before/after the compaction, when reported. */
185
+ preTokens: z.number().optional(),
186
+ postTokens: z.number().optional(),
187
+ /** User-displayable summary; may stream via successive upserts. */
188
+ summary: z.string().optional(),
189
+ /** Part ids the summary subsumed — auditable compaction lineage. */
190
+ abstractsIds: z.array(z.string()).optional(),
191
+ ...stamped,
192
+ });
193
+ // ---- turn events ------------------------------------------------------------
194
+ export const TurnStartedEventSchema = z.object({
195
+ type: z.literal("turn.started"),
196
+ ...inTurn,
197
+ execution: TurnExecutionSchema.optional(),
198
+ ...stamped,
199
+ });
200
+ export const TurnEndedEventSchema = z.object({
201
+ type: z.literal("turn.ended"),
202
+ ...inTurn,
203
+ execution: TurnExecutionSchema.optional(),
204
+ /** Normalized terminal status — `cancelled` and `error` are first-class. */
205
+ stopReason: StopReasonSchema,
206
+ /** Raw provider finish string (`end_turn`, `completed`, …), always preserved when reported. */
207
+ finishReason: z.string().optional(),
208
+ /** The turn's BILLING total (never the context gauge — that is session.usage). */
209
+ tokens: TokenUsageSchema.optional(),
210
+ /** USD for this turn, when reported. */
211
+ cost: z.number().optional(),
212
+ /** Present when stopReason === "error". */
213
+ error: ErrorInfoSchema.optional(),
214
+ /**
215
+ * Steers this turn accepted (`turn/steer`) that never reached the agent:
216
+ * the turn ended — completed, failed or was cancelled — before its next
217
+ * step. Each delivered steer is a user message in the turn instead.
218
+ */
219
+ undeliveredSteers: z.array(z.string()).optional(),
220
+ ...stamped,
221
+ });
222
+ // ---- message + part events --------------------------------------------------
223
+ export const MessageStartedEventSchema = z.object({
224
+ type: z.literal("message.started"),
225
+ ...inTurn,
226
+ messageId: z.string(),
227
+ /**
228
+ * Position of this message within the turn. The user echo is 0; the
229
+ * agent's messages, and a user message for each steer the agent read, follow.
230
+ */
231
+ outputIndex: z.number(),
232
+ role: z.enum(["user", "assistant"]),
233
+ /**
234
+ * Set when this message is a sub-agent's output: the `toolCallId` of the
235
+ * tool (e.g. Task) that spawned it. Such a message is NOT a top-level model
236
+ * message — consumers nest it under that tool call. Absent for top-level
237
+ * messages.
238
+ */
239
+ parentToolCallId: z.string().optional(),
240
+ /**
241
+ * An assistant message's model: the one the harness said wrote it
242
+ * (Claude's API model, a sub-agent's own), else the one it runs the turn on
243
+ * (the model Codex reports for its thread, or rerouted to), else the one
244
+ * the turn asked for.
245
+ */
246
+ model: z.string().optional(),
247
+ ...stamped,
248
+ });
249
+ /**
250
+ * A full part snapshot. UPSERT by `part.id` — authoritative, idempotent,
251
+ * re-delivery-safe. Full-snapshot semantics, never field patches: "clear a
252
+ * field" = omit it from the next snapshot.
253
+ */
254
+ export const MessagePartEventSchema = z.object({
255
+ type: z.literal("message.part"),
256
+ ...inTurn,
257
+ messageId: z.string(),
258
+ outputIndex: z.number(),
259
+ /** Position of this part within its message — persist as the ordering key. */
260
+ partIndex: z.number(),
261
+ part: PartSchema,
262
+ ...stamped,
263
+ });
264
+ export const DeltaSchema = z.discriminatedUnion("type", [
265
+ z.object({ type: z.literal("text"), text: z.string() }),
266
+ z.object({ type: z.literal("reasoning"), text: z.string() }),
267
+ z.object({
268
+ type: z.literal("tool_input"),
269
+ toolCallId: z.string(),
270
+ toolName: z.string(),
271
+ input: z.string(),
272
+ }),
273
+ ]);
274
+ /**
275
+ * An additive streaming aid for a streaming part field. Advisory: snapshots
276
+ * are authoritative and wipe accumulated deltas. Deltas are LIVE ONLY: a
277
+ * server never keeps one, so replay, journals and history never return it, and
278
+ * its envelope carries the `seq` of the session's last kept event instead of
279
+ * one of its own. A streaming part is kept at its opening, the changes its
280
+ * harness reports and its end; the engine flushes what streamed into it before
281
+ * the turn ends, and a client that subscribes mid-part receives the part as it
282
+ * stands (a live `message.part`). A journal keeps what streamed since a
283
+ * part's last snapshot, a row per delta, before the delta is delivered, so a
284
+ * server process that dies loses none of what was shown (power loss can); a
285
+ * server without a journal can lose it.
286
+ */
287
+ export const MessagePartDeltaEventSchema = z.object({
288
+ type: z.literal("message.part.delta"),
289
+ ...inTurn,
290
+ messageId: z.string(),
291
+ outputIndex: z.number(),
292
+ partIndex: z.number(),
293
+ partId: z.string(),
294
+ delta: DeltaSchema,
295
+ ...stamped,
296
+ });
297
+ /** Bracket marker ONLY — billing lives on turn.ended, never here. */
298
+ export const MessageEndedEventSchema = z.object({
299
+ type: z.literal("message.ended"),
300
+ ...inTurn,
301
+ messageId: z.string(),
302
+ ...stamped,
303
+ });
304
+ // ---- permissions (ACP request_permission-shaped) ----------------------------
305
+ /** OPEN — but unknown outcomes/kinds MUST be handled conservatively: never treated as approval. */
306
+ export const PERMISSION_OPTION_KINDS = [
307
+ "allow_once",
308
+ "allow_always",
309
+ "reject_once",
310
+ "reject_always",
311
+ ];
312
+ export const PermissionOptionKindSchema = openVocabulary(PERMISSION_OPTION_KINDS);
313
+ export const PermissionOptionSchema = z.object({
314
+ optionId: z.string(),
315
+ name: z.string(),
316
+ kind: PermissionOptionKindSchema,
317
+ });
318
+ /** The tool call a permission request is about (snapshot, not a live part). */
319
+ export const PermissionToolCallSchema = z.object({
320
+ /**
321
+ * The `toolCallId` of the in-flight tool part this request gates. Real for
322
+ * codex approvals AND Claude (`canUseTool` exposes `toolUseID` since SDK
323
+ * 0.2.138). Optional only for harnesses that genuinely cannot correlate.
324
+ */
325
+ toolCallId: z.string().optional(),
326
+ toolName: z.string(),
327
+ kind: ToolKindSchema.optional(),
328
+ /** A call to an MCP tool: its server and tool, as on its tool part. */
329
+ mcp: McpToolSchema.optional(),
330
+ /** The label the engine or the agent gives the call, on every harness. */
331
+ title: z.string().optional(),
332
+ /** A command's line, as on its tool part. */
333
+ command: z.string().optional(),
334
+ /** A fetch's address, as on its tool part. */
335
+ url: z.string().optional(),
336
+ locations: z.array(ToolLocationSchema).optional(),
337
+ /** Why this call needs the person, in the harness's or the model's words, when it says. */
338
+ reason: z.string().optional(),
339
+ rawInput: z.record(z.string(), z.unknown()).optional(),
340
+ });
341
+ export const PermissionOutcomeSchema = z.discriminatedUnion("outcome", [
342
+ z.object({
343
+ outcome: z.literal("selected"),
344
+ optionId: z.string(),
345
+ /**
346
+ * Allow-with-modified-input. Without this, products bypass the broker
347
+ * entirely (Claude's canUseTool supports it; ACP v1's outcome could not
348
+ * carry it).
349
+ */
350
+ updatedInput: z.record(z.string(), z.unknown()).optional(),
351
+ /**
352
+ * What the user said with their choice. A rejection's message reaches
353
+ * the agent as why where the harness says so
354
+ * (`AgentCapabilities.rejectionMessages`; a Codex plan is revised by
355
+ * it); a harness whose answer has no room for it drops it.
356
+ */
357
+ message: z.string().optional(),
358
+ }),
359
+ z.object({ outcome: z.literal("cancelled") }),
360
+ ]);
361
+ /**
362
+ * The harness is blocked waiting for a decision. Answer via
363
+ * `AgentRuntime.respondPermission(sessionId, requestId, outcome)`. Pending
364
+ * requests resolve as `cancelled` when the turn is cancelled or ends.
365
+ * `options` is THE source of buttons — clients render the server's list,
366
+ * never derive affordances from local policy.
367
+ */
368
+ export const PermissionRequestedEventSchema = z.object({
369
+ type: z.literal("permission.requested"),
370
+ ...inTurn,
371
+ requestId: z.string(),
372
+ /** Human-readable one-line prompt, always present (render this). */
373
+ title: z.string(),
374
+ /**
375
+ * Structured context when the request gates a tool call. Every built-in
376
+ * harness's permission is tool-scoped; the field is optional because an ACP
377
+ * agent can raise a request with no tool call.
378
+ */
379
+ toolCall: PermissionToolCallSchema.optional(),
380
+ options: z.array(PermissionOptionSchema),
381
+ ...stamped,
382
+ });
383
+ /** A pending permission request was answered (or cancelled). Resolves exactly once. */
384
+ export const PermissionResolvedEventSchema = z.object({
385
+ type: z.literal("permission.resolved"),
386
+ ...inTurn,
387
+ requestId: z.string(),
388
+ outcome: PermissionOutcomeSchema,
389
+ ...stamped,
390
+ });
391
+ // ---- elicitation (ACP elicitation/create-shaped) -----------------------------
392
+ /**
393
+ * How the agent asks. OPEN: `question` is the agent's own question with
394
+ * choices (Claude's AskUserQuestion, Codex's request_user_input); `form` and
395
+ * `url` are MCP and ACP elicitation modes. A harness declines a mode it does
396
+ * not know.
397
+ */
398
+ export const ELICITATION_MODES = ["question", "form", "url"];
399
+ export const ElicitationModeSchema = openVocabulary(ELICITATION_MODES);
400
+ /** One question of a `question` elicitation. */
401
+ export const ElicitationQuestionSchema = z.object({
402
+ /** The answer is keyed by this id. */
403
+ id: z.string(),
404
+ question: z.string(),
405
+ /** A short label for the question (a chip or tag). */
406
+ header: z.string().optional(),
407
+ /** The choices to offer; absent means a free-text answer. */
408
+ options: z.array(z.object({ label: z.string(), description: z.string().optional() })).optional(),
409
+ /** More than one option may be chosen. */
410
+ multiSelect: z.boolean().optional(),
411
+ /** The user may answer in their own words instead of choosing an option. */
412
+ allowOther: z.boolean().optional(),
413
+ /** The answer is a secret (a password, a token): mask it and never echo it. */
414
+ secret: z.boolean().optional(),
415
+ });
416
+ /**
417
+ * The agent, or one of its MCP servers, waits for the user's input. Answer via
418
+ * `AgentRuntime.respondElicitation(sessionId, requestId, outcome)`; pending
419
+ * requests resolve as `cancel` when the turn is cancelled or ends. Raised only
420
+ * in a turn whose `config.elicitation` says its client answers them — otherwise
421
+ * the harness declines on the user's behalf and the agent carries on.
422
+ */
423
+ export const ElicitationRequestedEventSchema = z.object({
424
+ type: z.literal("elicitation.requested"),
425
+ ...inTurn,
426
+ requestId: z.string(),
427
+ mode: ElicitationModeSchema,
428
+ /** Human-readable prompt, always present (render this). */
429
+ message: z.string(),
430
+ /** The MCP server asking; absent when the agent itself asks. */
431
+ serverName: z.string().optional(),
432
+ /** The tool part this request belongs to, when the harness can tell. */
433
+ toolCallId: z.string().optional(),
434
+ /** `question` mode: what to ask. */
435
+ questions: z.array(ElicitationQuestionSchema).optional(),
436
+ /** `form` mode: the MCP elicitation schema, a flat object of primitive properties. */
437
+ requestedSchema: z.record(z.string(), z.unknown()).optional(),
438
+ /** `url` mode: where the user completes the request. */
439
+ url: z.string().optional(),
440
+ /** `url` mode: the id a later completion notice refers to. */
441
+ elicitationId: z.string().optional(),
442
+ ...stamped,
443
+ });
444
+ /**
445
+ * The user's answer, ACP's three actions. `accept` carries `content`: in
446
+ * `question` mode each question id maps to an array of answers (chosen labels
447
+ * or the user's own words), in `form` mode the schema's properties map to
448
+ * their values, and `url` mode has none. `decline` is an explicit no; `cancel`
449
+ * dismisses without one, and is what a turn's end resolves a pending request as.
450
+ */
451
+ export const ElicitationOutcomeSchema = z.discriminatedUnion("action", [
452
+ z.object({
453
+ action: z.literal("accept"),
454
+ content: z.record(z.string(), z.unknown()).optional(),
455
+ }),
456
+ z.object({ action: z.literal("decline") }),
457
+ z.object({ action: z.literal("cancel") }),
458
+ ]);
459
+ /** A pending elicitation was answered (or cancelled). Resolves exactly once. */
460
+ export const ElicitationResolvedEventSchema = z.object({
461
+ type: z.literal("elicitation.resolved"),
462
+ ...inTurn,
463
+ requestId: z.string(),
464
+ outcome: ElicitationOutcomeSchema,
465
+ ...stamped,
466
+ });
467
+ // ---- error + raw ------------------------------------------------------------
468
+ export const ErrorEventSchema = z.object({
469
+ type: z.literal("error"),
470
+ /** Absent only for pre-session failures. */
471
+ sessionId: z.string().optional(),
472
+ turnId: z.string().optional(),
473
+ category: ErrorCategorySchema,
474
+ message: z.string(),
475
+ /**
476
+ * true = the turn continues (retry/backoff in flight). Consumers MUST NOT
477
+ * flip UI to an error state on recoverable errors — surface as diagnostics.
478
+ */
479
+ recoverable: z.boolean(),
480
+ /** A recoverable error the harness is retrying: which attempt, of how many, after what wait. */
481
+ retry: z
482
+ .object({
483
+ attempt: z.number().optional(),
484
+ maxAttempts: z.number().optional(),
485
+ delayMs: z.number().optional(),
486
+ })
487
+ .optional(),
488
+ stack: z.string().optional(),
489
+ ...stamped,
490
+ });
491
+ /**
492
+ * Opt-in (`RunConfig.includeRaw`) passthrough of the harness's raw event,
493
+ * interleaved with the normalized stream. Escape hatch for debugging and
494
+ * fixture recording — `data` carries NO stability guarantees and is not part
495
+ * of the contract. Building a product pipeline on `raw` is a bug.
496
+ */
497
+ export const RawEventSchema = z.object({
498
+ type: z.literal("raw"),
499
+ ...inTurn,
500
+ harness: HarnessIdSchema,
501
+ data: z.unknown(),
502
+ ...stamped,
503
+ });
504
+ // ---- the union --------------------------------------------------------------
505
+ export const LifecycleEventSchema = z.discriminatedUnion("type", [
506
+ SessionCreatedEventSchema,
507
+ SessionEndedEventSchema,
508
+ TurnStartedEventSchema,
509
+ MessageStartedEventSchema,
510
+ MessagePartEventSchema,
511
+ MessagePartDeltaEventSchema,
512
+ MessageEndedEventSchema,
513
+ TurnEndedEventSchema,
514
+ SessionUsageEventSchema,
515
+ SessionLimitsEventSchema,
516
+ SessionModeEventSchema,
517
+ SessionCompactionEventSchema,
518
+ ErrorEventSchema,
519
+ PermissionRequestedEventSchema,
520
+ PermissionResolvedEventSchema,
521
+ ElicitationRequestedEventSchema,
522
+ ElicitationResolvedEventSchema,
523
+ RawEventSchema,
524
+ ]);
525
+ /** A preserved unknown event as persisted state holds it, everything it carried kept. */
526
+ export const UnknownEventSchema = z.looseObject({
527
+ type: z.string(),
528
+ sessionId: z.string().optional(),
529
+ raw: z.record(z.string(), z.unknown()),
530
+ });
531
+ /** The `message.part` envelope without its part — decoded separately, leniently. */
532
+ const MessagePartEnvelopeSchema = MessagePartEventSchema.omit({ part: true });
533
+ /**
534
+ * Decode a wire value into a LifecycleEvent, preserving unknown event types
535
+ * (and unknown PART types inside `message.part`) instead of dropping them.
536
+ * Throws on a known type with a malformed body.
537
+ *
538
+ * This is the decoder every wire consumer should use — dropping an event a
539
+ * newer server sent is not a graceful degradation, it is a hole in the
540
+ * transcript and, for a seq-tracking client, a fabricated gap.
541
+ */
542
+ export function decodeLifecycleEvent(value) {
543
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
544
+ throw new Error("lifecycle event must be an object");
545
+ }
546
+ const record = value;
547
+ const type = record.type;
548
+ if (typeof type !== "string" || type.length === 0) {
549
+ throw new Error("lifecycle event is missing its type");
550
+ }
551
+ if (!isKnownLifecycleEventType(type)) {
552
+ const sessionId = typeof record.sessionId === "string" ? record.sessionId : undefined;
553
+ return { type, ...(sessionId !== undefined ? { sessionId } : {}), raw: record };
554
+ }
555
+ if (type === "message.part") {
556
+ return { ...MessagePartEnvelopeSchema.parse(record), part: decodePart(record.part) };
557
+ }
558
+ return LifecycleEventSchema.parse(value);
559
+ }
560
+ // `LIFECYCLE_EVENT_TYPES`, `isKnownLifecycleEventType` and `isUnknownEvent`
561
+ // live in `./guards.ts` — same exports from the barrel, but reachable without
562
+ // loading zod.
@@ -0,0 +1,17 @@
1
+ // Zod-free, so the factories can name the keys they write.
2
+ /**
3
+ * The `_meta` keys the engine itself writes, all under `agent-server/`
4
+ * (camelCase after the slash, like every wire field).
5
+ */
6
+ export const META_KEYS = {
7
+ /**
8
+ * The partial JSON a pending tool call was still streaming when its turn
9
+ * closed it: its closed state carries a parsed `input` the call never had,
10
+ * and without this a UI would render an empty tool card.
11
+ */
12
+ partialInput: "agent-server/partialInput",
13
+ /** The text element spans (mentions, pills) of a user message's text, echoed from its input. */
14
+ elements: "agent-server/elements",
15
+ /** Over ACP: the failure of a turn that ended, which ACP's stop reasons cannot carry. */
16
+ error: "agent-server/error",
17
+ };
@@ -0,0 +1,13 @@
1
+ import { z } from "zod";
2
+ // @ref LLP 0002#extensions-live-in-_meta — root names stay the protocol's
3
+ /**
4
+ * The extension slot (ACP's pattern): present on every event, part,
5
+ * tool state, and result-content item. Adapters and products MUST NOT add
6
+ * root-level fields to canonical types — all root names are reserved for
7
+ * future protocol versions; extensions live here under namespaced keys
8
+ * (`product/...`).
9
+ *
10
+ * Reserved keys (W3C trace context, MCP-compatible): `traceparent`,
11
+ * `tracestate`, `baggage`.
12
+ */
13
+ export const MetaSchema = z.record(z.string(), z.unknown()).optional();