@openllmsh/sdk 0.0.0-stage → 2.10.12-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/ARCHITECTURE.md +43 -0
  2. package/LICENSE +202 -0
  3. package/README.md +142 -2
  4. package/assets/openllm-light.svg +18 -0
  5. package/assets/openllm.svg +18 -0
  6. package/client/chat.ts +140 -0
  7. package/client/devices.ts +269 -0
  8. package/client/http.ts +72 -0
  9. package/client/index.ts +129 -0
  10. package/client/relay-mux.ts +547 -0
  11. package/client/types.ts +51 -0
  12. package/client/vault.ts +239 -0
  13. package/connect/chat.ts +58 -0
  14. package/connect/client.ts +240 -0
  15. package/connect/config.ts +47 -0
  16. package/connect/errors.ts +121 -0
  17. package/connect/index.ts +23 -0
  18. package/connect/oauth.ts +265 -0
  19. package/connect/routes.ts +234 -0
  20. package/connect/store.ts +107 -0
  21. package/mcp/handle.ts +24 -0
  22. package/mcp/index.ts +76 -0
  23. package/mcp/server.ts +319 -0
  24. package/mcp/tools/marketplace.ts +439 -0
  25. package/mcp/tools/memory-client.ts +297 -0
  26. package/mcp/tools/memory-config.ts +32 -0
  27. package/mcp/tools/memory.ts +369 -0
  28. package/mcp/tools/model-priority.ts +88 -0
  29. package/mcp/tools/openllm.ts +883 -0
  30. package/mcp/types.ts +28 -0
  31. package/openapi/call.ts +90 -0
  32. package/openapi/index.ts +8 -0
  33. package/openapi/openapi.json +80213 -0
  34. package/openapi/operations.ts +2075 -0
  35. package/package.json +39 -4
  36. package/protocol/CONTRIBUTING.md +21 -0
  37. package/protocol/README.md +134 -0
  38. package/protocol/access.ts +186 -0
  39. package/protocol/agent-prompt-text.ts +32 -0
  40. package/protocol/agent.ts +991 -0
  41. package/protocol/api-key-syntax.ts +105 -0
  42. package/protocol/assets/openllm-light.svg +18 -0
  43. package/protocol/assets/openllm.svg +18 -0
  44. package/protocol/audio.ts +29 -0
  45. package/protocol/auth.ts +142 -0
  46. package/protocol/changelog.ts +155 -0
  47. package/protocol/chat.ts +458 -0
  48. package/protocol/client-registry.ts +356 -0
  49. package/protocol/config.ts +345 -0
  50. package/protocol/control-channel.ts +115 -0
  51. package/protocol/cooldown-reason.ts +78 -0
  52. package/protocol/cost.ts +10 -0
  53. package/protocol/daemon-port.ts +31 -0
  54. package/protocol/daemon.ts +1524 -0
  55. package/protocol/default-chains.ts +66 -0
  56. package/protocol/device-state.ts +85 -0
  57. package/protocol/doctor-report-local.ts +443 -0
  58. package/protocol/doctor-report-policy.ts +119 -0
  59. package/protocol/doctor-report.ts +947 -0
  60. package/protocol/errors.ts +14 -0
  61. package/protocol/execution-selection.ts +141 -0
  62. package/protocol/hop-grant.ts +33 -0
  63. package/protocol/image-edit-parse.ts +263 -0
  64. package/protocol/images.ts +298 -0
  65. package/protocol/index.ts +74 -0
  66. package/protocol/inference-headers.ts +3 -0
  67. package/protocol/keepalive.ts +69 -0
  68. package/protocol/local-auth.ts +300 -0
  69. package/protocol/local-device-control.ts +133 -0
  70. package/protocol/local-provider.ts +288 -0
  71. package/protocol/local-session.ts +118 -0
  72. package/protocol/marketplace.ts +187 -0
  73. package/protocol/media-attempt.ts +81 -0
  74. package/protocol/media-bytes.ts +28 -0
  75. package/protocol/media-default.ts +357 -0
  76. package/protocol/media-dimensions.ts +132 -0
  77. package/protocol/media-input.ts +61 -0
  78. package/protocol/media-model.ts +142 -0
  79. package/protocol/media-option-issue.ts +90 -0
  80. package/protocol/media-types.ts +70 -0
  81. package/protocol/model-match.ts +1051 -0
  82. package/protocol/model-settings.ts +327 -0
  83. package/protocol/models.ts +767 -0
  84. package/protocol/mux.ts +722 -0
  85. package/protocol/plan-surface.ts +59 -0
  86. package/protocol/provider-models.ts +16 -0
  87. package/protocol/provider-status.ts +206 -0
  88. package/protocol/provider-tier.ts +67 -0
  89. package/protocol/provider-usage.ts +263 -0
  90. package/protocol/providers.ts +901 -0
  91. package/protocol/public-usage-index.ts +354 -0
  92. package/protocol/realtime-generated.ts +31 -0
  93. package/protocol/realtime.ts +324 -0
  94. package/protocol/registry-pointer.ts +118 -0
  95. package/protocol/relay.ts +702 -0
  96. package/protocol/replay-session.ts +11 -0
  97. package/protocol/responses.ts +280 -0
  98. package/protocol/semver.ts +182 -0
  99. package/protocol/setup-mode.ts +22 -0
  100. package/protocol/sha256-hex.ts +98 -0
  101. package/protocol/stats.ts +406 -0
  102. package/protocol/streaming.ts +19 -0
  103. package/protocol/subscription-daemon-floors.ts +33 -0
  104. package/protocol/subscription-provider-compat.ts +104 -0
  105. package/protocol/subscription-provider.ts +32 -0
  106. package/protocol/team-grant.ts +17 -0
  107. package/protocol/team-shareable.ts +61 -0
  108. package/protocol/transcription-encoding.ts +76 -0
  109. package/protocol/url-locality-dns.ts +37 -0
  110. package/protocol/url-locality.ts +288 -0
  111. package/protocol/usage-snapshots.ts +9 -0
  112. package/protocol/vendor-cli-install.ts +29 -0
  113. package/protocol/video-job-plan.ts +50 -0
  114. package/protocol/videos.ts +227 -0
  115. package/tsconfig.json +14 -0
  116. package/tunnel/ARCHITECTURE.md +111 -0
  117. package/tunnel/LICENSE +33 -0
  118. package/tunnel/README.md +45 -0
  119. package/tunnel/assets/openllm-light.svg +18 -0
  120. package/tunnel/assets/openllm.svg +18 -0
  121. package/tunnel/channel-envelope.ts +139 -0
  122. package/tunnel/codec.ts +191 -0
  123. package/tunnel/device-anchor.ts +229 -0
  124. package/tunnel/device-control.ts +118 -0
  125. package/tunnel/device-grant.ts +173 -0
  126. package/tunnel/fleet.ts +77 -0
  127. package/tunnel/index.ts +22 -0
  128. package/tunnel/mux.ts +580 -0
  129. package/tunnel/peer-link.ts +390 -0
  130. package/tunnel/rtc-auth.ts +415 -0
  131. package/tunnel/rtc-duplex.ts +187 -0
  132. package/tunnel/rtc-ice.ts +136 -0
  133. package/tunnel/secure.ts +1298 -0
  134. package/tunnel/stream-reset-error.ts +14 -0
  135. package/tunnel/streams.ts +1430 -0
  136. package/tunnel/team-grant.ts +302 -0
  137. package/tunnel/wire-bytes.ts +102 -0
  138. package/vault/ARCHITECTURE.md +470 -0
  139. package/vault/LICENSE +33 -0
  140. package/vault/api-key.ts +190 -0
  141. package/vault/argon2.ts +106 -0
  142. package/vault/cli-auth-seal.ts +157 -0
  143. package/vault/cred-seal.ts +146 -0
  144. package/vault/credential.ts +55 -0
  145. package/vault/crypto.ts +210 -0
  146. package/vault/daemon-attest.ts +229 -0
  147. package/vault/derive.ts +113 -0
  148. package/vault/device-access.ts +87 -0
  149. package/vault/device-anchor.ts +185 -0
  150. package/vault/device-control.ts +174 -0
  151. package/vault/handoff.ts +396 -0
  152. package/vault/index.ts +21 -0
  153. package/vault/passkey.ts +243 -0
  154. package/vault/phrase.ts +65 -0
  155. package/vault/pin.ts +153 -0
  156. package/vault/public-key-seal.ts +131 -0
  157. package/vault/seed.ts +272 -0
  158. package/vault/team.ts +355 -0
  159. package/vault/vault-item.ts +131 -0
  160. package/vault/vault-migrate-digest.ts +29 -0
  161. package/vault/wrapped.ts +77 -0
  162. package/wire/ARCHITECTURE.md +90 -0
  163. package/wire/CONTRIBUTING.md +19 -0
  164. package/wire/LICENSE +33 -0
  165. package/wire/README.md +51 -0
  166. package/wire/adapters/messages/anthropic-map.ts +37 -0
  167. package/wire/adapters/messages/index.ts +7 -0
  168. package/wire/adapters/messages/reasoning-from-items.ts +38 -0
  169. package/wire/adapters/messages/reasoning-signature.ts +243 -0
  170. package/wire/adapters/messages/request.ts +574 -0
  171. package/wire/adapters/messages/response.ts +215 -0
  172. package/wire/adapters/messages/streaming.ts +1027 -0
  173. package/wire/adapters/messages/usage.ts +43 -0
  174. package/wire/adapters/responses/index.ts +3 -0
  175. package/wire/adapters/responses/request.ts +395 -0
  176. package/wire/adapters/responses/response.ts +88 -0
  177. package/wire/adapters/responses/streaming.ts +344 -0
  178. package/wire/assets/openllm-light.svg +18 -0
  179. package/wire/assets/openllm.svg +18 -0
  180. package/wire/features/account-rank.ts +166 -0
  181. package/wire/features/compaction/compact-request.ts +862 -0
  182. package/wire/features/compaction/compaction-text.ts +43 -0
  183. package/wire/features/context-demote.ts +47 -0
  184. package/wire/features/context-overflow-strategy.ts +26 -0
  185. package/wire/features/context-skip.ts +170 -0
  186. package/wire/features/conversation-affinity.ts +144 -0
  187. package/wire/features/max-tokens-backfill.ts +141 -0
  188. package/wire/features/model-caps.ts +53 -0
  189. package/wire/features/model-settings.ts +24 -0
  190. package/wire/features/output-limit-clamp.ts +64 -0
  191. package/wire/features/quota-gate.ts +85 -0
  192. package/wire/index.ts +44 -0
  193. package/wire/lib/attempt-outcome.ts +43 -0
  194. package/wire/lib/canonical/content-part.ts +38 -0
  195. package/wire/lib/canonical/count-tokens-capability.ts +138 -0
  196. package/wire/lib/canonical/encoding-select.ts +82 -0
  197. package/wire/lib/canonical/image-signature.ts +202 -0
  198. package/wire/lib/canonical/image-sse.ts +216 -0
  199. package/wire/lib/canonical/message.ts +43 -0
  200. package/wire/lib/canonical/token-estimate.ts +266 -0
  201. package/wire/lib/encrypted-content.ts +66 -0
  202. package/wire/lib/error-class.ts +154 -0
  203. package/wire/lib/error-envelope.ts +56 -0
  204. package/wire/lib/forwarded-headers.ts +180 -0
  205. package/wire/lib/provider-error-rules.ts +48 -0
  206. package/wire/lib/refusal.ts +38 -0
  207. package/wire/lib/responses-apply-patch.ts +104 -0
  208. package/wire/lib/responses-namespace.ts +53 -0
  209. package/wire/lib/secret-scrub.ts +101 -0
  210. package/wire/lib/streaming/accumulate.ts +221 -0
  211. package/wire/lib/streaming/finish-reason.ts +33 -0
  212. package/wire/lib/streaming/peek.ts +154 -0
  213. package/wire/lib/streaming/provider-decode.ts +259 -0
  214. package/wire/lib/streaming/response-stream.ts +71 -0
  215. package/wire/lib/streaming/sse.ts +699 -0
  216. package/wire/lib/streaming/strip-tool-calls.ts +95 -0
  217. package/wire/lib/streaming/upstream-error.ts +58 -0
  218. package/wire/lib/strip-subagent-isolation.ts +284 -0
  219. package/wire/lib/thinking-signature.ts +156 -0
  220. package/wire/lib/token-ruler/bpe-core.ts +426 -0
  221. package/wire/lib/token-ruler/index.ts +2 -0
  222. package/wire/lib/token-ruler/ruler.ts +79 -0
  223. package/wire/lib/token-ruler/vocab/claude-ranks.ts +16 -0
  224. package/wire/lib/token-ruler/vocab/claude.ts +22 -0
  225. package/wire/lib/token-ruler/vocab/o200k-ranks.ts +18 -0
  226. package/wire/lib/token-ruler/vocab/o200k.ts +19 -0
  227. package/wire/lib/tool-name-map.ts +271 -0
  228. package/wire/lib/tool-schema.ts +353 -0
  229. package/wire/lib/usage-observer.ts +125 -0
  230. package/wire/providers/anthropic/adaptive-thinking.ts +291 -0
  231. package/wire/providers/anthropic/beta-headers.ts +165 -0
  232. package/wire/providers/anthropic/index.ts +10 -0
  233. package/wire/providers/anthropic/request.ts +607 -0
  234. package/wire/providers/anthropic/response.ts +155 -0
  235. package/wire/providers/anthropic/streaming.ts +315 -0
  236. package/wire/providers/anthropic/web-search-domains.ts +49 -0
  237. package/wire/providers/chatgpt/common.ts +136 -0
  238. package/wire/providers/chatgpt/index.ts +9 -0
  239. package/wire/providers/chatgpt/request.ts +959 -0
  240. package/wire/providers/chatgpt/streaming.ts +1007 -0
  241. package/wire/providers/chatgpt/web-search.ts +63 -0
  242. package/wire/providers/grok/web-search.ts +87 -0
  243. package/wire/providers/kimi/web-search.ts +145 -0
  244. package/wire/providers/upstream-deny.ts +355 -0
  245. package/wire/providers/upstream-request.ts +619 -0
@@ -0,0 +1,991 @@
1
+ /**
2
+ * Agent session protocol — the structured replacement for remote PTY
3
+ * mirroring (docs/plan/2026-10-23-agent-sessions-replace-remote-pty.md).
4
+ *
5
+ * A consumer opens a mux stream with {@link AgentStreamOpenPayload}
6
+ * (`kind:"agent"`, seed-gated on the daemon) or reaches the daemon's loopback
7
+ * agent endpoint, then exchanges NDJSON lines over the flow-controlled DATA
8
+ * channel:
9
+ *
10
+ * consumer → daemon : {@link AgentCommand} (start / attach / send /
11
+ * interrupt / respond / close / attachment_get /
12
+ * set_model / delete_session / history_get)
13
+ * daemon → consumer : {@link AgentEvent} (session / turn / item / content /
14
+ * request / user-input / token-usage / runtime /
15
+ * attachment.data / history.page)
16
+ *
17
+ * History is paged (after t3code's windowed thread detail): an attach replays
18
+ * only the LATEST window of the session, ending on a turn boundary, then a
19
+ * {@link AgentHistoryPageEvent} names the opaque cursor before that window.
20
+ * `history_get{before}` returns the adjacent, strictly older page.
21
+ *
22
+ * The event families are a trimmed subset of t3code's `ProviderRuntimeEvent`:
23
+ * no multi-CLI orchestration, no event-sourcing / checkpoint / git tooling, no
24
+ * terminal drawer, no realtime-audio, account or MCP-OAuth events. Every
25
+ * engine adapter on the daemon emits this one stream, so the UI renders one
26
+ * vocabulary whichever engine runs the session.
27
+ *
28
+ * Forward compatibility: an event whose `type` this build does not know
29
+ * decodes to `null` and is dropped by consumers. Commands are validated
30
+ * strictly by the serving daemon.
31
+ */
32
+ import { Schema as S } from "effect";
33
+ import * as Result from "effect/Result";
34
+ import { SESSION_ID_PATTERN } from "./local-session";
35
+
36
+ /**
37
+ * Capability advertising `kind:"agent"` stream support. Consumers MUST check
38
+ * {@link hasAgentCap} before OPEN; a peer without it gets "update your device".
39
+ */
40
+ export const AGENT_CAP = "agent1";
41
+
42
+ /** Returns whether an open-vocabulary capability list advertises agent sessions. */
43
+ export const hasAgentCap = (caps: readonly string[] | undefined): boolean =>
44
+ caps?.includes(AGENT_CAP) ?? false;
45
+
46
+ /**
47
+ * Bound on ONE NDJSON agent line (JSON-encoded UTF-8 bytes, including the
48
+ * trailing `\n`). Larger than the realtime bound because a `send` command may
49
+ * carry inline attachments; a line (or unterminated remainder) over the bound
50
+ * is an overflow, never a growing buffer.
51
+ */
52
+ export const AGENT_MAX_LINE_BYTES = 8 * 1024 * 1024;
53
+
54
+ const lineEncoder = new TextEncoder();
55
+
56
+ /** Max characters of one prompt. */
57
+ export const AGENT_MAX_PROMPT_LENGTH = 1024 * 1024;
58
+
59
+ /**
60
+ * Daemon loopback route Claude's hooks post to (`openllm exec agent hook`):
61
+ * busy/idle and PermissionRequest for agent sessions. Admitted like the other
62
+ * `/local/*` routes (loopback peer + Host, local control capability).
63
+ * Body: `{session_id, event, payload}`; reply: `{output}` (the hook's stdout
64
+ * JSON) or `{}` for no output.
65
+ */
66
+ export const AGENT_HOOK_LOCAL_PATH = "/local/agent-hook";
67
+ /**
68
+ * Claude hook events `openllm exec agent hook` forwards. `SessionStart` is the
69
+ * engine's readiness signal: Claude runs it once the TUI is up (after any
70
+ * folder-trust dialog), so a queued web prompt is pasted only then.
71
+ */
72
+ export const AGENT_HOOK_EVENTS = [
73
+ "PermissionRequest",
74
+ "PreToolUse",
75
+ "Stop",
76
+ "SessionStart",
77
+ ] as const;
78
+
79
+ /** Max inline attachments on one `send`. */
80
+ export const AGENT_MAX_ATTACHMENTS = 8;
81
+
82
+ /** Max base64 characters of one inline attachment. */
83
+ export const AGENT_MAX_ATTACHMENT_BASE64_LENGTH = 6 * 1024 * 1024;
84
+
85
+ /**
86
+ * Engines an agent session can run. Each id is the `openllm <client>` the
87
+ * daemon launches the engine through (same overlay, gateway URL, key, model
88
+ * mapping), so a session's inference is routed through openllm whatever
89
+ * model the user picked.
90
+ */
91
+ export const AgentEngine = S.Literals(["claude", "codex"]);
92
+ export type TAgentEngine = S.Schema.Type<typeof AgentEngine>;
93
+
94
+ /**
95
+ * Agent session id: daemon-minted (a UUID), the consumer's own record id, or
96
+ * a vendor session id for attach/resume (Claude / Codex ids are UUIDs). The
97
+ * id names the session host's registry dir and its attachments dir, so it is
98
+ * the local session id itself: url-safe, no `.`, so never `.` / `..`.
99
+ */
100
+ export const AGENT_SESSION_ID_PATTERN = SESSION_ID_PATTERN;
101
+ export const AgentSessionId = S.String.check(
102
+ S.isPattern(AGENT_SESSION_ID_PATTERN),
103
+ );
104
+ export type TAgentSessionId = S.Schema.Type<typeof AgentSessionId>;
105
+
106
+ /** Opaque daemon-minted id for turns, items, and requests. */
107
+ const AgentRefId = S.String.check(S.isMinLength(1), S.isMaxLength(128));
108
+
109
+ /** Optional consumer-minted command id, echoed on correlated events. */
110
+ const AgentCommandId = S.String.check(S.isMinLength(1), S.isMaxLength(64));
111
+
112
+ const AgentModel = S.String.check(S.isMinLength(1), S.isMaxLength(256));
113
+
114
+ /** Absolute directory; the daemon validates it exists before starting. */
115
+ const AgentCwd = S.String.check(S.isMinLength(1), S.isMaxLength(1024));
116
+
117
+ /**
118
+ * Length caps (UTF-16 code units, as `String.length`) of an event's short
119
+ * label fields (titles, messages, option labels), its detail text, and a tool
120
+ * call's `tool_name`. An event over one fails to decode and consumers drop it,
121
+ * so builders clip to these.
122
+ */
123
+ export const AGENT_SHORT_TEXT_MAX_LENGTH = 256;
124
+ export const AGENT_DETAIL_TEXT_MAX_LENGTH = 16 * 1024;
125
+ export const AGENT_TOOL_NAME_MAX_LENGTH = 128;
126
+
127
+ const ShortText = S.String.check(S.isMaxLength(AGENT_SHORT_TEXT_MAX_LENGTH));
128
+ const DetailText = S.String.check(S.isMaxLength(AGENT_DETAIL_TEXT_MAX_LENGTH));
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // Stream OPEN
132
+ // ---------------------------------------------------------------------------
133
+
134
+ /**
135
+ * Mux `kind:"agent"` OPEN payload — folded into `StreamOpenPayload` in
136
+ * `./mux`. Carries nothing but the kind: the session itself is driven by
137
+ * {@link AgentCommand} lines on the stream, so one OPEN shape serves start,
138
+ * attach and resume.
139
+ */
140
+ export const AgentStreamOpenPayload = S.Struct({
141
+ kind: S.Literal("agent"),
142
+ });
143
+ export type TAgentStreamOpenPayload = S.Schema.Type<
144
+ typeof AgentStreamOpenPayload
145
+ >;
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // Commands (consumer → daemon)
149
+ // ---------------------------------------------------------------------------
150
+
151
+ export const AgentAttachment = S.Struct({
152
+ kind: S.Literals(["image", "file"]),
153
+ name: S.optional(S.String.check(S.isMinLength(1), S.isMaxLength(256))),
154
+ media_type: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
155
+ /** Base64 bytes. */
156
+ data: S.String.check(S.isMaxLength(AGENT_MAX_ATTACHMENT_BASE64_LENGTH)),
157
+ });
158
+ export type TAgentAttachment = S.Schema.Type<typeof AgentAttachment>;
159
+
160
+ /**
161
+ * Metadata for an attachment that was saved on the device for a turn. The
162
+ * `name` is the on-disk basename under the session's attachments dir (what
163
+ * {@link AgentAttachmentGetCommand} looks up) — not the original upload name
164
+ * when they differ. Optional on `turn.started` so terminal prompts and older
165
+ * daemons stay compatible.
166
+ */
167
+ export const AgentAttachmentMeta = S.Struct({
168
+ name: S.String.check(S.isMinLength(1), S.isMaxLength(256)),
169
+ mime: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
170
+ size: S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0)),
171
+ });
172
+ export type TAgentAttachmentMeta = S.Schema.Type<typeof AgentAttachmentMeta>;
173
+
174
+ /** Decoded-byte cap mirroring {@link AGENT_MAX_ATTACHMENT_BASE64_LENGTH}. */
175
+ export const AGENT_MAX_ATTACHMENT_BYTES = Math.floor(
176
+ (AGENT_MAX_ATTACHMENT_BASE64_LENGTH * 3) / 4,
177
+ );
178
+
179
+ /** Decision on an approval request (`request.opened`). */
180
+ export const AgentRequestDecision = S.Literals([
181
+ "accept",
182
+ "accept_for_session",
183
+ "decline",
184
+ "cancel",
185
+ ]);
186
+ export type TAgentRequestDecision = S.Schema.Type<typeof AgentRequestDecision>;
187
+
188
+ /** Answers to a `user-input.requested`, keyed by question id. */
189
+ export const AgentUserInputAnswers = S.Record(
190
+ S.String.check(S.isMinLength(1), S.isMaxLength(128)),
191
+ S.Union([
192
+ S.String.check(S.isMaxLength(16 * 1024)),
193
+ S.Array(S.String.check(S.isMaxLength(1024))).check(S.isMaxLength(64)),
194
+ ]),
195
+ );
196
+ export type TAgentUserInputAnswers = S.Schema.Type<
197
+ typeof AgentUserInputAnswers
198
+ >;
199
+
200
+ export const AgentStartCommand = S.Struct({
201
+ type: S.Literal("start"),
202
+ id: S.optional(AgentCommandId),
203
+ engine: AgentEngine,
204
+ /** Gateway model id; omitted → the engine's openllm default. */
205
+ model: S.optional(AgentModel),
206
+ /** Omitted → the daemon user's home directory. */
207
+ cwd: S.optional(AgentCwd),
208
+ /**
209
+ * Per-session opt-in to the engine's skip-permissions mode
210
+ * (`--dangerously-skip-permissions` or the vendor equivalent). Default off:
211
+ * approvals surface as `request.opened` events.
212
+ */
213
+ skip_permissions: S.optional(S.Boolean),
214
+ title: S.optional(S.String.check(S.isMaxLength(80))),
215
+ /**
216
+ * The id the new session takes (the consumer's own record id, e.g. the web's
217
+ * cloud session row). Omitted → the daemon mints one. One id end to end (the
218
+ * cloud row, the session host, Claude's transcript) is what lets a reload
219
+ * re-attach and a running row match the daemon's status.
220
+ */
221
+ session_id: S.optional(AgentSessionId),
222
+ });
223
+ export type TAgentStartCommand = S.Schema.Type<typeof AgentStartCommand>;
224
+
225
+ export const AgentAttachCommand = S.Struct({
226
+ type: S.Literal("attach"),
227
+ id: S.optional(AgentCommandId),
228
+ session_id: AgentSessionId,
229
+ /** Engine of the target session when the consumer knows it (local index). */
230
+ engine: S.optional(AgentEngine),
231
+ /**
232
+ * The session was started with skip-permissions: a resume (the session is
233
+ * not running) relaunches the engine the same way. Ignored when joining a
234
+ * live session, which keeps the mode it runs in.
235
+ */
236
+ skip_permissions: S.optional(S.Boolean),
237
+ });
238
+ export type TAgentAttachCommand = S.Schema.Type<typeof AgentAttachCommand>;
239
+
240
+ export const AgentSendCommand = S.Struct({
241
+ type: S.Literal("send"),
242
+ id: S.optional(AgentCommandId),
243
+ prompt: S.String.check(S.isMaxLength(AGENT_MAX_PROMPT_LENGTH)),
244
+ attachments: S.optional(
245
+ S.Array(AgentAttachment).check(S.isMaxLength(AGENT_MAX_ATTACHMENTS)),
246
+ ),
247
+ }).check(
248
+ S.makeFilter(
249
+ (command) =>
250
+ lineEncoder.encode(`${JSON.stringify(command)}\n`).byteLength <=
251
+ AGENT_MAX_LINE_BYTES,
252
+ { message: "send command exceeds the agent line size bound" },
253
+ ),
254
+ );
255
+ export type TAgentSendCommand = S.Schema.Type<typeof AgentSendCommand>;
256
+
257
+ /**
258
+ * Deliver the queued prompts NOW instead of after the running turn. Plain,
259
+ * they join the running turn at its next tool boundary and running tools
260
+ * finish. With `interrupt`, the engine's own send-now (Claude Code's
261
+ * ctrl+enter) runs: running shells move to the background and tools that
262
+ * can't (an MCP call) are stopped — consumers ask the user before setting it.
263
+ * A daemon that predates it rejects the line; consumers offer it only after
264
+ * a `queue.updated` showed the daemon queues.
265
+ */
266
+ export const AgentSendNowCommand = S.Struct({
267
+ type: S.Literal("send_now"),
268
+ id: S.optional(AgentCommandId),
269
+ interrupt: S.optional(S.Boolean),
270
+ });
271
+ export type TAgentSendNowCommand = S.Schema.Type<typeof AgentSendNowCommand>;
272
+
273
+ /** Resume a queue that an interrupt deliberately paused. */
274
+ export const AgentResumeQueueCommand = S.Struct({
275
+ type: S.Literal("resume_queue"),
276
+ id: S.optional(AgentCommandId),
277
+ });
278
+ export type TAgentResumeQueueCommand = S.Schema.Type<
279
+ typeof AgentResumeQueueCommand
280
+ >;
281
+
282
+ /** Remove one queued prompt without affecting the active turn. */
283
+ export const AgentCancelQueuedCommand = S.Struct({
284
+ type: S.Literal("cancel_queued"),
285
+ id: S.optional(AgentCommandId),
286
+ queue_id: AgentRefId,
287
+ });
288
+ export type TAgentCancelQueuedCommand = S.Schema.Type<
289
+ typeof AgentCancelQueuedCommand
290
+ >;
291
+
292
+ export const AgentInterruptCommand = S.Struct({
293
+ type: S.Literal("interrupt"),
294
+ id: S.optional(AgentCommandId),
295
+ /** Omitted → the active turn. */
296
+ turn_id: S.optional(AgentRefId),
297
+ });
298
+ export type TAgentInterruptCommand = S.Schema.Type<
299
+ typeof AgentInterruptCommand
300
+ >;
301
+
302
+ /**
303
+ * Answer a pending approval (`decision`) or user-input request (`answers`).
304
+ * Exactly one of the two is present.
305
+ */
306
+ export const AgentRespondCommand = S.Struct({
307
+ type: S.Literal("respond"),
308
+ id: S.optional(AgentCommandId),
309
+ request_id: AgentRefId,
310
+ decision: S.optional(AgentRequestDecision),
311
+ answers: S.optional(AgentUserInputAnswers),
312
+ }).check(
313
+ S.makeFilter(
314
+ (command) =>
315
+ (command.decision === undefined) !== (command.answers === undefined),
316
+ {
317
+ message: "respond carries exactly one of decision / answers",
318
+ },
319
+ ),
320
+ );
321
+ export type TAgentRespondCommand = S.Schema.Type<typeof AgentRespondCommand>;
322
+
323
+ export const AgentCloseCommand = S.Struct({
324
+ type: S.Literal("close"),
325
+ id: S.optional(AgentCommandId),
326
+ });
327
+ export type TAgentCloseCommand = S.Schema.Type<typeof AgentCloseCommand>;
328
+
329
+ /**
330
+ * Fetch one attachment from the current session's on-device attachments dir.
331
+ * `name` is the basename recorded on `turn.started.attachments` (no path
332
+ * separators). The daemon refuses traversal / absolute / symlink-escape names
333
+ * and streams the bytes back as one or more {@link AgentAttachmentDataEvent}
334
+ * lines under the same `command_id`.
335
+ */
336
+ export const AgentAttachmentGetCommand = S.Struct({
337
+ type: S.Literal("attachment_get"),
338
+ id: S.optional(AgentCommandId),
339
+ name: S.String.check(S.isMinLength(1), S.isMaxLength(256)),
340
+ });
341
+ export type TAgentAttachmentGetCommand = S.Schema.Type<
342
+ typeof AgentAttachmentGetCommand
343
+ >;
344
+
345
+ /**
346
+ * A model id a running session can switch to: gateway ids and Claude aliases
347
+ * (`ultra`, `sonnet`, `openai/gpt-5`, `claude-opus-4-5[1m]`). No whitespace or
348
+ * control characters: it is typed into the engine's own `/model` command.
349
+ */
350
+ export const AGENT_SWITCH_MODEL_PATTERN =
351
+ /^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]{0,255}$/;
352
+
353
+ /**
354
+ * Switch the running session's model (Claude: its own `/model <id>`, applied
355
+ * when the session is idle, queued while a turn runs). Confirmed by a
356
+ * `session.configured` event once the engine reports the change.
357
+ */
358
+ export const AgentSetModelCommand = S.Struct({
359
+ type: S.Literal("set_model"),
360
+ id: S.optional(AgentCommandId),
361
+ model: S.String.check(S.isPattern(AGENT_SWITCH_MODEL_PATTERN)),
362
+ });
363
+ export type TAgentSetModelCommand = S.Schema.Type<typeof AgentSetModelCommand>;
364
+
365
+ /**
366
+ * Delete one session from this device: stop its process if it runs (here or
367
+ * in a terminal), then remove its attachments, Claude's transcript
368
+ * (`~/.claude/projects/<slug of its cwd>/<id>.jsonl`) and its lines in
369
+ * `~/.claude/history.jsonl`. Stream-level (needs no bound session). Answered
370
+ * by `session.deleted`, or a `runtime.error`. `close` is the non-destructive
371
+ * Stop: it kills the process and keeps the history.
372
+ */
373
+ export const AgentDeleteSessionCommand = S.Struct({
374
+ type: S.Literal("delete_session"),
375
+ id: S.optional(AgentCommandId),
376
+ session_id: AgentSessionId,
377
+ });
378
+ export type TAgentDeleteSessionCommand = S.Schema.Type<
379
+ typeof AgentDeleteSessionCommand
380
+ >;
381
+
382
+ /** Turns one `history_get` page holds at most. */
383
+ export const AGENT_HISTORY_MAX_PAGE_TURNS = 100;
384
+ /** Events one `history.page` carries at most. */
385
+ export const AGENT_HISTORY_MAX_PAGE_EVENTS = 4_000;
386
+
387
+ /** Opaque daemon-minted history cursor (consumers never parse it). */
388
+ const AgentHistoryCursor = S.String.check(S.isMinLength(1), S.isMaxLength(128));
389
+
390
+ /**
391
+ * Older history of the bound session: the turns strictly before `before`
392
+ * (a cursor from an earlier `history.page`), newest `limit` of them. Answered
393
+ * by one `history.page` carrying the events, under the same `command_id`.
394
+ */
395
+ export const AgentHistoryGetCommand = S.Struct({
396
+ type: S.Literal("history_get"),
397
+ id: S.optional(AgentCommandId),
398
+ before: AgentHistoryCursor,
399
+ limit: S.optional(
400
+ S.Number.check(
401
+ S.isInt(),
402
+ S.isGreaterThan(0),
403
+ S.isLessThanOrEqualTo(AGENT_HISTORY_MAX_PAGE_TURNS),
404
+ ),
405
+ ),
406
+ });
407
+ export type TAgentHistoryGetCommand = S.Schema.Type<
408
+ typeof AgentHistoryGetCommand
409
+ >;
410
+
411
+ /** One consumer → daemon command line. */
412
+ export const AgentCommand = S.Union([
413
+ AgentStartCommand,
414
+ AgentAttachCommand,
415
+ AgentSendCommand,
416
+ AgentSendNowCommand,
417
+ AgentResumeQueueCommand,
418
+ AgentCancelQueuedCommand,
419
+ AgentInterruptCommand,
420
+ AgentRespondCommand,
421
+ AgentCloseCommand,
422
+ AgentAttachmentGetCommand,
423
+ AgentSetModelCommand,
424
+ AgentDeleteSessionCommand,
425
+ AgentHistoryGetCommand,
426
+ ]);
427
+ export type TAgentCommand = S.Schema.Type<typeof AgentCommand>;
428
+ export type TAgentCommandType = TAgentCommand["type"];
429
+
430
+ // ---------------------------------------------------------------------------
431
+ // Events (daemon → consumer)
432
+ // ---------------------------------------------------------------------------
433
+
434
+ /** Fields every event may carry. */
435
+ const eventBase = {
436
+ /** The session this event belongs to (absent only before one exists). */
437
+ session_id: S.optional(AgentSessionId),
438
+ /** Daemon-assigned ordinal, monotonically increasing per session. */
439
+ seq: S.optional(S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0))),
440
+ /** Epoch milliseconds on the daemon. */
441
+ at: S.optional(S.Number.check(S.isGreaterThanOrEqualTo(0))),
442
+ /** Echo of the {@link AgentCommand} `id` this event answers, if any. */
443
+ command_id: S.optional(AgentCommandId),
444
+ } as const;
445
+
446
+ const TokenCount = S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0));
447
+
448
+ export const AgentTokenUsage = S.Struct({
449
+ input_tokens: TokenCount,
450
+ output_tokens: TokenCount,
451
+ cached_input_tokens: S.optional(TokenCount),
452
+ reasoning_tokens: S.optional(TokenCount),
453
+ total_tokens: S.optional(TokenCount),
454
+ /** The model's context window, when known, for a fill gauge. */
455
+ context_window: S.optional(TokenCount),
456
+ });
457
+ export type TAgentTokenUsage = S.Schema.Type<typeof AgentTokenUsage>;
458
+
459
+ export const AgentSessionExitReason = S.Literals([
460
+ "closed",
461
+ "completed",
462
+ "killed",
463
+ "error",
464
+ ]);
465
+ export type TAgentSessionExitReason = S.Schema.Type<
466
+ typeof AgentSessionExitReason
467
+ >;
468
+
469
+ export const AgentSessionStartedEvent = S.Struct({
470
+ ...eventBase,
471
+ type: S.Literal("session.started"),
472
+ session_id: AgentSessionId,
473
+ engine: AgentEngine,
474
+ model: S.optional(AgentModel),
475
+ cwd: S.optional(AgentCwd),
476
+ /** True when this is an attach/resume of an existing engine session. */
477
+ resumed: S.optional(S.Boolean),
478
+ skip_permissions: S.optional(S.Boolean),
479
+ });
480
+
481
+ /**
482
+ * The engine began a new conversation in the same live TUI (for example,
483
+ * Claude Code's `/new`). The consumer must discard the prior transcript; the
484
+ * daemon also starts its replay buffer over so a later attach stays clean.
485
+ */
486
+ export const AgentSessionResetEvent = S.Struct({
487
+ ...eventBase,
488
+ type: S.Literal("session.reset"),
489
+ });
490
+
491
+ /**
492
+ * The session's configuration changed (today: its model), from whichever side
493
+ * changed it (a web `set_model`, or `/model` typed in the terminal). Read from
494
+ * the engine's own record, so every viewer converges on the same value.
495
+ */
496
+ export const AgentSessionConfiguredEvent = S.Struct({
497
+ ...eventBase,
498
+ type: S.Literal("session.configured"),
499
+ model: S.optional(AgentModel),
500
+ /**
501
+ * The conversation's title, from the engine's own record (Claude's
502
+ * `ai-title`). Optional: older daemons omit it, older consumers ignore it.
503
+ */
504
+ title: S.optional(ShortText),
505
+ });
506
+
507
+ export const AgentSessionExitedEvent = S.Struct({
508
+ ...eventBase,
509
+ type: S.Literal("session.exited"),
510
+ session_id: AgentSessionId,
511
+ reason: AgentSessionExitReason,
512
+ message: S.optional(ShortText),
513
+ });
514
+
515
+ export const AgentTurnStartedEvent = S.Struct({
516
+ ...eventBase,
517
+ type: S.Literal("turn.started"),
518
+ turn_id: AgentRefId,
519
+ model: S.optional(AgentModel),
520
+ /**
521
+ * The prompt text that opened the turn. Lets a consumer that attaches later
522
+ * (replay) render the user's side of the transcript. Optional: older daemons
523
+ * omit it and older consumers ignore it.
524
+ */
525
+ prompt: S.optional(S.String.check(S.isMaxLength(AGENT_MAX_PROMPT_LENGTH))),
526
+ /**
527
+ * Attachments saved for this turn (on-disk basename + mime + size). Optional:
528
+ * terminal prompts and older daemons omit it; older consumers ignore it.
529
+ */
530
+ attachments: S.optional(
531
+ S.Array(AgentAttachmentMeta).check(S.isMaxLength(AGENT_MAX_ATTACHMENTS)),
532
+ ),
533
+ });
534
+
535
+ /** Most prompts a session holds behind its running turn. */
536
+ export const AGENT_MAX_QUEUED_PROMPTS = 16;
537
+
538
+ /**
539
+ * The prompts waiting behind the running turn, oldest first — the whole
540
+ * queue, so the latest event is the state. A `send` that lands mid-turn is
541
+ * queued on the daemon and goes out as the turn ends (or on `send_now`).
542
+ * Older consumers ignore it.
543
+ */
544
+ export const AgentQueuedPrompt = S.Struct({
545
+ /** Stable while the prompt is queued; used for a targeted cancel. */
546
+ id: AgentRefId,
547
+ /** Clipped preview, never the complete prompt. */
548
+ prompt: ShortText,
549
+ attachment_count: S.Number.check(
550
+ S.isInt(),
551
+ S.isGreaterThanOrEqualTo(0),
552
+ S.isLessThanOrEqualTo(AGENT_MAX_ATTACHMENTS),
553
+ ),
554
+ });
555
+ export type TAgentQueuedPrompt = S.Schema.Type<typeof AgentQueuedPrompt>;
556
+
557
+ export const AgentQueueUpdatedEvent = S.Struct({
558
+ ...eventBase,
559
+ type: S.Literal("queue.updated"),
560
+ /**
561
+ * Identified entries, oldest first. `string[]` remains valid on the browser
562
+ * boundary for daemons predating this protocol shape.
563
+ */
564
+ prompts: S.Array(S.Union([AgentQueuedPrompt, ShortText])).check(
565
+ S.isMaxLength(AGENT_MAX_QUEUED_PROMPTS),
566
+ ),
567
+ /** An interrupt pauses automatic draining until `resume_queue`. */
568
+ held: S.optional(S.Boolean),
569
+ });
570
+
571
+ export const AgentTurnCompletedEvent = S.Struct({
572
+ ...eventBase,
573
+ type: S.Literal("turn.completed"),
574
+ turn_id: AgentRefId,
575
+ stop_reason: S.optional(S.String.check(S.isMaxLength(64))),
576
+ /**
577
+ * What the turn cost, from the engine's own record: `input_tokens` is the
578
+ * context the turn's last request carried, `output_tokens` the sum the turn
579
+ * generated. Optional: older daemons omit it, older consumers ignore it.
580
+ */
581
+ usage: S.optional(AgentTokenUsage),
582
+ });
583
+
584
+ export const AgentTurnAbortedEvent = S.Struct({
585
+ ...eventBase,
586
+ type: S.Literal("turn.aborted"),
587
+ turn_id: AgentRefId,
588
+ reason: S.Literals(["interrupted", "failed", "cancelled"]),
589
+ message: S.optional(ShortText),
590
+ });
591
+
592
+ export const AgentToolStatus = S.Literals([
593
+ "in_progress",
594
+ "completed",
595
+ "failed",
596
+ ]);
597
+ export type TAgentToolStatus = S.Schema.Type<typeof AgentToolStatus>;
598
+
599
+ export const AgentNoticeKind = S.Literals([
600
+ "compacted",
601
+ "interrupted",
602
+ "model_changed",
603
+ "error",
604
+ /** A background subagent reported completion (`ref_item_id` is its call). */
605
+ "subagent_finished",
606
+ ]);
607
+ export type TAgentNoticeKind = S.Schema.Type<typeof AgentNoticeKind>;
608
+
609
+ /** The renderable unit of a turn. */
610
+ export const AgentItem = S.Union([
611
+ S.Struct({
612
+ kind: S.Literal("assistant_message"),
613
+ text: S.String,
614
+ }),
615
+ S.Struct({
616
+ kind: S.Literal("reasoning"),
617
+ text: S.String,
618
+ }),
619
+ S.Struct({
620
+ kind: S.Literal("tool_call"),
621
+ tool_name: S.String.check(
622
+ S.isMinLength(1),
623
+ S.isMaxLength(AGENT_TOOL_NAME_MAX_LENGTH),
624
+ ),
625
+ title: S.optional(ShortText),
626
+ /** The tool's input as the engine reported it (JSON). */
627
+ input: S.optional(S.Unknown),
628
+ status: AgentToolStatus,
629
+ /** Result text, truncated by the daemon to fit one line. */
630
+ output: S.optional(S.String),
631
+ is_error: S.optional(S.Boolean),
632
+ /** The user (or a policy) refused the call; optional, additive. */
633
+ denied: S.optional(S.Boolean),
634
+ /** Wall time from call to result, when the engine recorded both. */
635
+ duration_ms: S.optional(
636
+ S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0)),
637
+ ),
638
+ /** A shell command's exit status, when the engine reported it. */
639
+ exit_code: S.optional(S.Number.check(S.isInt())),
640
+ /**
641
+ * A subagent launched in the background: the call's own result is only
642
+ * the launch ack, so it stays in progress past its turn until the
643
+ * subagent finishes. Optional, additive.
644
+ */
645
+ background: S.optional(S.Boolean),
646
+ }),
647
+ /**
648
+ * A marker in the conversation that is neither speech nor a tool: context
649
+ * compacted, a turn interrupted, the model switched, an engine error. Older
650
+ * consumers drop the whole event (unknown kind), which loses only the line.
651
+ */
652
+ S.Struct({
653
+ kind: S.Literal("notice"),
654
+ notice: AgentNoticeKind,
655
+ text: S.optional(DetailText),
656
+ /** The item the notice is about (a subagent's call). Optional, additive. */
657
+ ref_item_id: S.optional(AgentRefId),
658
+ }),
659
+ ]);
660
+ export type TAgentItem = S.Schema.Type<typeof AgentItem>;
661
+
662
+ /** `item.updated` carries the item's full current state, not a diff. */
663
+ const itemEventFields = {
664
+ ...eventBase,
665
+ turn_id: S.optional(AgentRefId),
666
+ item_id: AgentRefId,
667
+ item: AgentItem,
668
+ /**
669
+ * The tool call (a Task / Agent subagent) this item belongs to: a
670
+ * subagent's own text and tool calls nest under the call that spawned it.
671
+ * Absent → a top-level item of the turn. Older consumers ignore it.
672
+ */
673
+ parent_item_id: S.optional(AgentRefId),
674
+ } as const;
675
+
676
+ export const AgentItemStartedEvent = S.Struct({
677
+ ...itemEventFields,
678
+ type: S.Literal("item.started"),
679
+ });
680
+ export const AgentItemUpdatedEvent = S.Struct({
681
+ ...itemEventFields,
682
+ type: S.Literal("item.updated"),
683
+ });
684
+ export const AgentItemCompletedEvent = S.Struct({
685
+ ...itemEventFields,
686
+ type: S.Literal("item.completed"),
687
+ });
688
+
689
+ export const AgentContentStream = S.Literals([
690
+ "assistant_text",
691
+ "reasoning_text",
692
+ "tool_output",
693
+ ]);
694
+ export type TAgentContentStream = S.Schema.Type<typeof AgentContentStream>;
695
+
696
+ export const AgentContentDeltaEvent = S.Struct({
697
+ ...eventBase,
698
+ type: S.Literal("content.delta"),
699
+ turn_id: S.optional(AgentRefId),
700
+ item_id: AgentRefId,
701
+ stream: AgentContentStream,
702
+ delta: S.String,
703
+ });
704
+
705
+ /** What an approval request asks permission for. */
706
+ export const AgentRequestKind = S.Literals([
707
+ "command",
708
+ "file_change",
709
+ "tool",
710
+ "other",
711
+ ]);
712
+ export type TAgentRequestKind = S.Schema.Type<typeof AgentRequestKind>;
713
+
714
+ export const AgentRequestOpenedEvent = S.Struct({
715
+ ...eventBase,
716
+ type: S.Literal("request.opened"),
717
+ request_id: AgentRefId,
718
+ turn_id: S.optional(AgentRefId),
719
+ item_id: S.optional(AgentRefId),
720
+ request_kind: AgentRequestKind,
721
+ title: S.optional(ShortText),
722
+ detail: S.optional(DetailText),
723
+ input: S.optional(S.Unknown),
724
+ });
725
+
726
+ export const AgentRequestResolvedEvent = S.Struct({
727
+ ...eventBase,
728
+ type: S.Literal("request.resolved"),
729
+ request_id: AgentRefId,
730
+ decision: AgentRequestDecision,
731
+ });
732
+
733
+ export const AgentUserInputQuestion = S.Struct({
734
+ id: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
735
+ header: S.optional(ShortText),
736
+ question: DetailText,
737
+ options: S.optional(
738
+ S.Array(
739
+ S.Struct({
740
+ label: ShortText,
741
+ description: S.optional(S.String.check(S.isMaxLength(1024))),
742
+ }),
743
+ ).check(S.isMaxLength(64)),
744
+ ),
745
+ multi_select: S.optional(S.Boolean),
746
+ });
747
+ export type TAgentUserInputQuestion = S.Schema.Type<
748
+ typeof AgentUserInputQuestion
749
+ >;
750
+
751
+ export const AgentUserInputRequestedEvent = S.Struct({
752
+ ...eventBase,
753
+ type: S.Literal("user-input.requested"),
754
+ request_id: AgentRefId,
755
+ turn_id: S.optional(AgentRefId),
756
+ questions: S.Array(AgentUserInputQuestion).check(
757
+ S.isMinLength(1),
758
+ S.isMaxLength(16),
759
+ ),
760
+ });
761
+
762
+ export const AgentUserInputResolvedEvent = S.Struct({
763
+ ...eventBase,
764
+ type: S.Literal("user-input.resolved"),
765
+ request_id: AgentRefId,
766
+ answers: AgentUserInputAnswers,
767
+ });
768
+
769
+ export const AgentTokenUsageUpdatedEvent = S.Struct({
770
+ ...eventBase,
771
+ type: S.Literal("thread.token-usage.updated"),
772
+ usage: AgentTokenUsage,
773
+ });
774
+
775
+ export const AgentRuntimeWarningEvent = S.Struct({
776
+ ...eventBase,
777
+ type: S.Literal("runtime.warning"),
778
+ code: S.optional(S.String.check(S.isMaxLength(64))),
779
+ message: DetailText,
780
+ });
781
+
782
+ /**
783
+ * `runtime.error` code of a `set_model` the engine accepted but could not
784
+ * apply (the CLI refused the model, or never confirmed the switch).
785
+ */
786
+ export const AGENT_MODEL_SWITCH_FAILED_CODE = "model_switch_failed";
787
+ /** `runtime.warning` code of a model switch the user declined. */
788
+ export const AGENT_MODEL_SWITCH_DECLINED_CODE = "model_switch_declined";
789
+
790
+ export const AgentRuntimeErrorEvent = S.Struct({
791
+ ...eventBase,
792
+ type: S.Literal("runtime.error"),
793
+ code: S.optional(S.String.check(S.isMaxLength(64))),
794
+ message: DetailText,
795
+ /** True when the session cannot continue (a `session.exited` follows). */
796
+ fatal: S.optional(S.Boolean),
797
+ });
798
+
799
+ /**
800
+ * One chunk of an `attachment_get` response. Chunked so a single NDJSON line
801
+ * stays under {@link AGENT_MAX_LINE_BYTES}: `data` is base64 of
802
+ * `file[offset .. offset+decodedLen)`, and `done` is true on the last chunk.
803
+ */
804
+ export const AgentAttachmentDataEvent = S.Struct({
805
+ ...eventBase,
806
+ type: S.Literal("attachment.data"),
807
+ name: S.String.check(S.isMinLength(1), S.isMaxLength(256)),
808
+ mime: S.String.check(S.isMinLength(1), S.isMaxLength(128)),
809
+ /** Total decoded byte length of the file. */
810
+ size: S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0)),
811
+ /** Decoded-byte offset of this chunk within the file. */
812
+ offset: S.Number.check(S.isInt(), S.isGreaterThanOrEqualTo(0)),
813
+ /** Base64 of this chunk. */
814
+ data: S.String.check(S.isMaxLength(AGENT_MAX_ATTACHMENT_BASE64_LENGTH)),
815
+ /** True when this is the last chunk. */
816
+ done: S.Boolean,
817
+ });
818
+ export type TAgentAttachmentDataEvent = S.Schema.Type<
819
+ typeof AgentAttachmentDataEvent
820
+ >;
821
+
822
+ /** Answer to `delete_session`: the session is gone from the device. */
823
+ export const AgentSessionDeletedEvent = S.Struct({
824
+ ...eventBase,
825
+ type: S.Literal("session.deleted"),
826
+ session_id: AgentSessionId,
827
+ });
828
+
829
+ /**
830
+ * A page of session history. On attach (no `events`): the cursor before the
831
+ * replayed window. Answering `history_get` (same `command_id`): the older
832
+ * events themselves, oldest first, each one {@link AgentEvent} line's value
833
+ * (decode with {@link parseAgentEvent}; unknown types are dropped). Paging is
834
+ * by whole turns, so a page never splits one. `has_more` false → the page
835
+ * reaches the start of the session.
836
+ */
837
+ export const AgentHistoryPageEvent = S.Struct({
838
+ ...eventBase,
839
+ type: S.Literal("history.page"),
840
+ before_cursor: S.optional(AgentHistoryCursor),
841
+ has_more: S.Boolean,
842
+ events: S.optional(
843
+ S.Array(S.Unknown).check(S.isMaxLength(AGENT_HISTORY_MAX_PAGE_EVENTS)),
844
+ ),
845
+ });
846
+ export type TAgentHistoryPageEvent = S.Schema.Type<
847
+ typeof AgentHistoryPageEvent
848
+ >;
849
+
850
+ /** One daemon → consumer event line. */
851
+ export const AgentEvent = S.Union([
852
+ AgentSessionStartedEvent,
853
+ AgentSessionResetEvent,
854
+ AgentSessionConfiguredEvent,
855
+ AgentSessionExitedEvent,
856
+ AgentTurnStartedEvent,
857
+ AgentQueueUpdatedEvent,
858
+ AgentTurnCompletedEvent,
859
+ AgentTurnAbortedEvent,
860
+ AgentItemStartedEvent,
861
+ AgentItemUpdatedEvent,
862
+ AgentItemCompletedEvent,
863
+ AgentContentDeltaEvent,
864
+ AgentRequestOpenedEvent,
865
+ AgentRequestResolvedEvent,
866
+ AgentUserInputRequestedEvent,
867
+ AgentUserInputResolvedEvent,
868
+ AgentTokenUsageUpdatedEvent,
869
+ AgentRuntimeWarningEvent,
870
+ AgentRuntimeErrorEvent,
871
+ AgentAttachmentDataEvent,
872
+ AgentSessionDeletedEvent,
873
+ AgentHistoryPageEvent,
874
+ ]);
875
+ export type TAgentEvent = S.Schema.Type<typeof AgentEvent>;
876
+ export type TAgentEventType = TAgentEvent["type"];
877
+ /** Narrow {@link TAgentEvent} to one `type`. */
878
+ export type TAgentEventOf<K extends TAgentEventType> = Extract<
879
+ TAgentEvent,
880
+ { readonly type: K }
881
+ >;
882
+
883
+ // ---------------------------------------------------------------------------
884
+ // Parsing + NDJSON framing
885
+ // ---------------------------------------------------------------------------
886
+
887
+ const decodeCommand = S.decodeUnknownResult(S.revealCodec(AgentCommand));
888
+ const decodeEvent = S.decodeUnknownResult(S.revealCodec(AgentEvent));
889
+
890
+ /** Decode an already-parsed JSON value as a command, or null. */
891
+ export const parseAgentCommand = (value: unknown): TAgentCommand | null => {
892
+ const result = decodeCommand(value);
893
+ return Result.isSuccess(result) ? result.success : null;
894
+ };
895
+
896
+ /** Decode an already-parsed JSON value as an event, or null (unknown types too). */
897
+ export const parseAgentEvent = (value: unknown): TAgentEvent | null => {
898
+ const result = decodeEvent(value);
899
+ return Result.isSuccess(result) ? result.success : null;
900
+ };
901
+
902
+ const lineDecoder = new TextDecoder("utf-8", { fatal: true });
903
+ const NEWLINE = 0x0a;
904
+
905
+ /**
906
+ * JSON-encode one value as a newline-terminated line. Null when it does not
907
+ * serialize or exceeds {@link AGENT_MAX_LINE_BYTES} — the caller decides
908
+ * (truncate, or emit a `runtime.warning`); a truncated line would desync the
909
+ * framing.
910
+ */
911
+ export const encodeAgentLine = (value: unknown): Uint8Array | null => {
912
+ let text: string | undefined;
913
+ try {
914
+ text = JSON.stringify(value);
915
+ } catch {
916
+ return null;
917
+ }
918
+ if (text === undefined) return null;
919
+ const encoded = lineEncoder.encode(`${text}\n`);
920
+ return encoded.byteLength > AGENT_MAX_LINE_BYTES ? null : encoded;
921
+ };
922
+
923
+ /** Decode one line's bytes (without `\n`) into JSON, or `undefined`. */
924
+ export const decodeAgentLine = (line: Uint8Array): unknown => {
925
+ try {
926
+ return JSON.parse(lineDecoder.decode(line));
927
+ } catch {
928
+ return undefined;
929
+ }
930
+ };
931
+
932
+ export type TAgentLineSplitter = {
933
+ /**
934
+ * Feed one chunk; returns the complete lines it finished (without `\n`), or
935
+ * null once a line exceeds `maxLineBytes` (the splitter stays failed).
936
+ */
937
+ readonly push: (chunk: Uint8Array) => readonly Uint8Array[] | null;
938
+ };
939
+
940
+ /**
941
+ * Stateful NDJSON splitter. Partial lines are kept as a chunk list and joined
942
+ * once, when their newline arrives, so a multi-megabyte line costs one copy
943
+ * rather than one per DATA frame.
944
+ */
945
+ export const createAgentLineSplitter = (
946
+ maxLineBytes: number = AGENT_MAX_LINE_BYTES,
947
+ ): TAgentLineSplitter => {
948
+ let pending: Uint8Array[] = [];
949
+ let pendingBytes = 0;
950
+ let failed = false;
951
+ const join = (tail: Uint8Array): Uint8Array => {
952
+ if (pending.length === 0) return tail;
953
+ const out = new Uint8Array(pendingBytes + tail.byteLength);
954
+ let offset = 0;
955
+ for (const part of pending) {
956
+ out.set(part, offset);
957
+ offset += part.byteLength;
958
+ }
959
+ out.set(tail, offset);
960
+ pending = [];
961
+ pendingBytes = 0;
962
+ return out;
963
+ };
964
+ return {
965
+ push: (chunk) => {
966
+ if (failed) return null;
967
+ const lines: Uint8Array[] = [];
968
+ let start = 0;
969
+ for (let i = 0; i < chunk.byteLength; i += 1) {
970
+ if (chunk[i] !== NEWLINE) continue;
971
+ if (pendingBytes + (i - start) > maxLineBytes) {
972
+ failed = true;
973
+ return null;
974
+ }
975
+ lines.push(join(chunk.subarray(start, i)));
976
+ start = i + 1;
977
+ }
978
+ if (start < chunk.byteLength) {
979
+ const rest = chunk.subarray(start);
980
+ if (pendingBytes + rest.byteLength > maxLineBytes) {
981
+ failed = true;
982
+ return null;
983
+ }
984
+ // Copy: the transport may reuse the chunk's buffer.
985
+ pending.push(rest.slice());
986
+ pendingBytes += rest.byteLength;
987
+ }
988
+ return lines;
989
+ },
990
+ };
991
+ };