@workerdeck/protocol 0.6.0 → 0.9.0

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.
package/build/index.d.mts CHANGED
@@ -10,7 +10,7 @@
10
10
  * structurally (see {@link ApiMessage}) so clients don't need the Agent SDK to render transcripts.
11
11
  */
12
12
  /** Bumped on any breaking change to events, commands, or REST shapes. */
13
- declare const PROTOCOL_VERSION = 4;
13
+ declare const PROTOCOL_VERSION = 6;
14
14
  /**
15
15
  * - `starting` — runner spawned, waiting for the SDK init handshake
16
16
  * - `running` — a turn is in progress
@@ -55,6 +55,29 @@ type UnknownBlock = {
55
55
  [key: string]: unknown;
56
56
  };
57
57
  type ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock | UnknownBlock;
58
+ /**
59
+ * A file the user attached to a message — a photo, a screenshot, a document.
60
+ *
61
+ * The bytes never travel on this protocol. An attachment is uploaded first
62
+ * (`POST {basePath}/sessions/:id/attachments`), and the command that sends the
63
+ * message names it by id; what lands in the seq-numbered event log is this
64
+ * reference. That is deliberate: the log is replayed to every attaching client
65
+ * and captured into parking snapshots, so a few phone photos inlined as base64
66
+ * would be paid for on every attach, forever. Clients render a thumbnail by
67
+ * fetching `GET {basePath}/sessions/:id/attachments/:attachmentId`.
68
+ *
69
+ * Lifetime is the session's, like `/files` — the store is in-memory and an
70
+ * attachment 404s after a server restart. The message itself is unaffected: the
71
+ * model saw the bytes at send time.
72
+ */
73
+ type MessageAttachment = {
74
+ /** Server-assigned; the path segment of the download URL. */id: string; /** Display name from the file the user picked. A leaf name, never a path. */
75
+ name: string;
76
+ /** IANA media type, e.g. 'image/jpeg'. The server decides how it reaches the
77
+ * model (image block, document block, or inlined text) from this. */
78
+ mediaType: string;
79
+ bytes: number;
80
+ };
58
81
  type ApiMessage = {
59
82
  role: 'user' | 'assistant';
60
83
  content: string | ContentBlock[];
@@ -69,7 +92,13 @@ type ApiMessage = {
69
92
  cache_read_input_tokens?: number;
70
93
  };
71
94
  };
72
- /** A tool call promoted into a pending approval by the runner's canUseTool hook. */
95
+ /** A tool call promoted into a pending approval by the runner's canUseTool hook
96
+ * (Claude), or an engine ask-channel request surfaced by its runner (codex).
97
+ * The two do not share a tense: Claude asks BEFORE a tool runs; codex's command
98
+ * approval is usually an escalation AFTER its sandbox already ran and refused
99
+ * the command ("command failed; retry without sandbox?"). The runner authors
100
+ * `title`/`description`/`decisionReason` to say which — clients should render
101
+ * those fields rather than composing their own "X wants to run Y" sentence. */
73
102
  type PermissionRequest = {
74
103
  /** Server-assigned id; used by the `permission_decision` command. */id: string;
75
104
  toolName: string;
@@ -111,8 +140,21 @@ type QuestionBehavior = 'ask' | 'auto' | 'deny';
111
140
  /** A model the session can switch to (SDK ModelInfo mirror; fields it may grow stay unknown). */
112
141
  type ModelOption = {
113
142
  /** Model id for createSession.model / set_model. */value: string;
143
+ /** Wire model id this row resolves to ('sonnet' → 'claude-sonnet-5'). What a
144
+ * session actually reports as its model is the resolved form, so this is how a
145
+ * client matches the running model back to the row that names it. */
146
+ resolvedModel?: string;
114
147
  displayName: string;
115
148
  description?: string;
149
+ /** Whether this belongs in a picker's main list rather than behind a "more
150
+ * models" step: the newest model of each family. Derived server-side — the CLI
151
+ * reports one flat list — so that every client groups it the same way. */
152
+ primary?: boolean;
153
+ /** Reasoning efforts this model supports at create time (codex catalogs carry
154
+ * them, from the binary's own per-model list). Absent = the engine's default
155
+ * set ({@link EngineCapabilities.reasoningEfforts}) applies. Open strings —
156
+ * the binary's vocabulary outruns its SDK's union. */
157
+ reasoningEfforts?: readonly string[];
116
158
  };
117
159
  /** A slash command the CLI accepts as user-message text (SDK SlashCommand mirror). */
118
160
  type SlashCommandInfo = {
@@ -202,6 +244,11 @@ type SessionEventBody = /** SDK init handshake: what this session actually is. *
202
244
  type: 'capabilities';
203
245
  models: ModelOption[];
204
246
  commands: SlashCommandInfo[];
247
+ /** Wire id the session's *default* resolves to, from the CLI's own `default`
248
+ * row. Answers "what will this session answer as" before it has answered
249
+ * anything — `system_init` carries the model, but a promptless session gets
250
+ * no `system_init` until its first message. */
251
+ defaultModel?: string;
205
252
  } /** The session's model changed via `set_model`. `model` undefined = back to default. */ | {
206
253
  type: 'model_changed';
207
254
  model?: string;
@@ -214,6 +261,15 @@ type SessionEventBody = /** SDK init handshake: what this session actually is. *
214
261
  } /** Subscription rate-limit update for one window (see {@link RateLimitInfo}). */ | {
215
262
  type: 'rate_limit';
216
263
  info: RateLimitInfo;
264
+ }
265
+ /** Which claude.ai plan the rate-limit windows belong to: 'pro' | 'max' | 'team' |
266
+ * 'enterprise' — kept as string, the set may grow. Emitted from the same poll as
267
+ * `rate_limit`, once per change, and never for an API-key session (which has no
268
+ * plan). It names the windows; it does not size them — the tier suffix a
269
+ * subscription page shows ("Max 20x") is not in the data. */
270
+ | {
271
+ type: 'plan_info';
272
+ subscriptionType: string;
217
273
  } | {
218
274
  type: 'assistant_message';
219
275
  message: ApiMessage; /** Set when the message was produced inside a subagent (Task tool). */
@@ -226,6 +282,10 @@ type SessionEventBody = /** SDK init handshake: what this session actually is. *
226
282
  parentToolUseId: string | null; /** True when replayed from a resumed session's history. */
227
283
  replay?: boolean; /** True for tool results and other synthetic user-role messages. */
228
284
  synthetic?: boolean;
285
+ /** Files sent with this message, by reference (see {@link MessageAttachment}).
286
+ * `message.content` carries the typed text only — the attachment bytes went
287
+ * to the model, not into this log. */
288
+ attachments?: MessageAttachment[];
229
289
  uuid?: string;
230
290
  }
231
291
  /** Raw Anthropic streaming event (message_start/content_block_delta/...); emitted only
@@ -316,6 +376,10 @@ type SessionEvent = SessionEventBody & {
316
376
  type SessionCommand = {
317
377
  type: 'user_message';
318
378
  text: string;
379
+ /** Ids from `POST {basePath}/sessions/:id/attachments`, in the order they
380
+ * should reach the model. Unknown ids fail the command rather than sending
381
+ * a message that quietly lost its picture. */
382
+ attachmentIds?: string[];
319
383
  } | {
320
384
  type: 'permission_decision';
321
385
  requestId: string;
@@ -414,16 +478,77 @@ type ProfileDefaults = {
414
478
  * auto-created from the operator's own config dir) — the API only reads them.
415
479
  */
416
480
  /**
417
- * Which engine a profile runs on.
481
+ * Which engine a profile runs on. A **closed union, deliberately**: both clients
482
+ * switch exhaustively, the Swift mirror ships in lockstep, and a closed set is
483
+ * what lets this package carry per-engine capability defaults
484
+ * ({@link ENGINE_CAPABILITIES}) browser-safe, with no server round-trip. Adding a
485
+ * member is a versioned protocol event.
486
+ *
418
487
  * - `claude` (default) — Claude Code via the Agent SDK, configured by a config dir.
419
- * - `provider` — a model-agnostic provider (OpenAI-compatible, Anthropic, Moonshot),
420
- * configured by provider id and credentials from the operator's environment.
488
+ * - `codex` — OpenAI Codex over the codex CLI binary's `app-server` JSON-RPC
489
+ * surface, configured by a CODEX_HOME (auth resolved by the binary itself,
490
+ * like claude).
491
+ * - `provider` — a model-agnostic provider over the AI SDK, assembled by the
492
+ * host's `createEngineRunner` hook.
493
+ */
494
+ type ProfileEngine = 'claude' | 'codex' | 'provider';
495
+ /**
496
+ * What an engine does and does not do — one axis per real difference, each field
497
+ * answering a concrete UI or gateway question. Clients render from this record
498
+ * instead of switching on the engine name: an absent capability means the
499
+ * affordance is *hidden*, never a control that silently does nothing.
500
+ *
501
+ * Reaches clients in two places, same shape: `ProfileInfo.capabilities` (stamped
502
+ * by the server; the create form's source) and `SessionInfo.capabilities`
503
+ * (reported by the runner; the session surface's source). When the field is
504
+ * absent — an older server — {@link ENGINE_CAPABILITIES} keyed by the engine
505
+ * name is the browser-safe default.
506
+ */
507
+ type EngineCapabilities = {
508
+ /** PermissionRequest / permission_resolved can occur; approval UI is live.
509
+ * False: hide approval affordances entirely (and `questionBehavior` on jobs). */
510
+ interactiveApprovals: boolean;
511
+ /** Modes this engine can honor. A stored choice outside the set is coerced to
512
+ * {@link EngineCapabilities.defaultPermissionMode}, not submitted. */
513
+ permissionModes: readonly PermissionMode[]; /** Coercion target for a stored/unsupported mode choice (always ∈ permissionModes). */
514
+ defaultPermissionMode: PermissionMode; /** CreateSessionRequest.resume works (an engine session id continues). */
515
+ resume: boolean;
516
+ /** Resume replays prior history into the transcript (Claude's backfill).
517
+ * False + resume: show a "history predates this attach" notice instead of
518
+ * treating an empty transcript as a bug. */
519
+ resumeBackfill: boolean; /** GET /sdk-sessions offers a resume picker for this engine. */
520
+ listSessions: boolean; /** context_usage events can occur. False: render nothing — never a 0% ring. */
521
+ contextUsage: boolean; /** rate_limit / plan_info events can occur. False: render nothing. */
522
+ rateLimits: boolean; /** GET/POST /sessions/:id/mcp works (else 501). */
523
+ mcpStatus: boolean; /** A session request may bring its own mcpServers. */
524
+ sessionMcpServers: boolean; /** capabilities events carry slash commands (composer popover). */
525
+ slashCommands: boolean; /** settingSources / allowDangerouslySkipPermissions-style CLI options apply. */
526
+ settingSources: boolean; /** maxTurns / maxBudgetUsd are honored (else the gateway 400s them). */
527
+ budgets: boolean;
528
+ /** Attachment kinds sendMessage can deliver to the model. Filter the attach
529
+ * menu by kind; refuse locally before the server's 415. */
530
+ attachments: ReadonlyArray<'image' | 'pdf' | 'text'>;
531
+ /** Efforts offerable at create time; absent = not settable (hide the control).
532
+ * Open strings — Codex's own binary already outruns its SDK's union. */
533
+ reasoningEfforts?: readonly string[]; /** Sessions expose a scratch VFS (GET /sessions/:id/files, deliverables panel). */
534
+ vfs: boolean;
535
+ /** stream_delta granularity: per-token, coarse item updates (no typing
536
+ * cursor), or none. */
537
+ streaming: 'token' | 'item' | 'none';
538
+ };
539
+ /**
540
+ * The static capability record of each engine — the browser-safe default for
541
+ * `ProfileInfo.capabilities` / `SessionInfo.capabilities`, and the single place
542
+ * the values are written down. Core's adapters *reference* this record and a
543
+ * conformance test compares runner behaviour against it, so it cannot silently
544
+ * diverge from the code. When both a wire copy and this default exist, the wire
545
+ * copy wins.
421
546
  */
422
- type ProfileEngine = 'claude' | 'provider';
547
+ declare const ENGINE_CAPABILITIES: Record<ProfileEngine, EngineCapabilities>;
423
548
  /**
424
- * Permission modes the model-agnostic provider engine understands. The rest of
425
- * {@link PermissionMode}'s vocabulary is Claude Code's: `acceptEdits`, `plan` and
426
- * `auto` name CLI-side behaviours a provider session has no equivalent of.
549
+ * Permission modes the model-agnostic provider engine understands.
550
+ * @deprecated Read `ENGINE_CAPABILITIES.provider.permissionModes` (this is an
551
+ * alias of it, kept for protocol-5 consumers).
427
552
  */
428
553
  declare const PROVIDER_PERMISSION_MODES: readonly PermissionMode[];
429
554
  /**
@@ -481,12 +606,37 @@ type ProfileInfo = {
481
606
  * written before provider support keep working unchanged. */
482
607
  engine?: ProfileEngine;
483
608
  /** Absolute path set as CLAUDE_CONFIG_DIR for the session's CLI process.
484
- * Required for 'claude' profiles; meaningless for 'provider' ones. */
485
- configDir?: string; /** Provider wiring for 'provider' profiles. */
609
+ * Required for 'claude' profiles; meaningless for the other engines. */
610
+ configDir?: string;
611
+ /** Codex profiles: absolute path set as CODEX_HOME for the session's codex
612
+ * process (auth, config.toml, thread storage) — the `configDir` analogue,
613
+ * request-writable like it. Unset = the binary's own `~/.codex`. */
614
+ codexHome?: string; /** Provider wiring for 'provider' profiles. */
486
615
  provider?: ProviderConfig;
487
616
  description?: string;
488
617
  defaults?: ProfileDefaults; /** Provider-engine session grants (capabilities, MCP servers, instructions). */
489
618
  session?: ProfileSessionDefaults;
619
+ /** Response-only: the engine's model catalog, shipped with the release and
620
+ * served from the first request (no process spawned, no warm-up session).
621
+ * For provider profiles the ids come from `provider.models` instead. Never
622
+ * contains a 'default' sentinel row — forms add their own "Profile default"
623
+ * row mapping to an unset model. Ignored on the way in. */
624
+ models?: ModelOption[];
625
+ /** Response-only: what this profile's default model resolves to. For claude
626
+ * profiles this is the operator's CLI config — unknowable statically — so it
627
+ * is absent until a session on this profile reports it. */
628
+ defaultModel?: string;
629
+ /** Response-only: the engine's capability record (see {@link EngineCapabilities}).
630
+ * Absent = use ENGINE_CAPABILITIES[engine]. Ignored on the way in. */
631
+ capabilities?: EngineCapabilities;
632
+ /** Response-only: whether the profile's credentials probe as usable right now.
633
+ * Absent = unknown/unchecked — treat as available. **Display-only**: create
634
+ * against an unavailable profile still proceeds and fails with the engine's
635
+ * own error (the probe can be stale in both directions). */
636
+ available?: boolean;
637
+ /** Response-only: one operator-actionable line, present only when
638
+ * `available === false`. */
639
+ unavailableReason?: string;
490
640
  /** Response-only, computed by the server: this profile came from the profile
491
641
  * store and can be edited or deleted through the API. Profiles declared in
492
642
  * server options are absent/false — they are code. Ignored on the way in. */
@@ -528,6 +678,59 @@ type McpServerConfigWire = {
528
678
  url: string;
529
679
  headers?: Record<string, string>;
530
680
  };
681
+ /** One tool an MCP server exposes, as the session's engine reports it.
682
+ * Parameters are deliberately absent: the CLI's status payload names and
683
+ * describes each tool but does not carry its input schema. */
684
+ type McpServerToolInfo = {
685
+ name: string;
686
+ description?: string;
687
+ annotations?: {
688
+ readOnly?: boolean;
689
+ destructive?: boolean;
690
+ openWorld?: boolean;
691
+ };
692
+ };
693
+ /**
694
+ * Live status of one MCP server on a session — what `GET
695
+ * {basePath}/sessions/:id/mcp` answers with, and what the `/mcp` screens render.
696
+ *
697
+ * The connection *identity* is here (transport, command, url, scope) but never
698
+ * its secrets: the engine's config carries `env` for stdio servers and `headers`
699
+ * for HTTP/SSE ones, and both are dropped on the way out. A client that can read
700
+ * this is not thereby entitled to the tokens the operator configured.
701
+ */
702
+ type McpServerStatusInfo = {
703
+ name: string;
704
+ /** 'connected' | 'failed' | 'needs-auth' | 'pending' | 'disabled' — kept open,
705
+ * the engine's set may grow. */
706
+ status: string; /** Where the server was configured: 'project' | 'user' | 'local' | 'dynamic' | … */
707
+ scope?: string; /** Present when `status` is 'failed'. */
708
+ error?: string; /** Name and version the server announced on connect. */
709
+ serverInfo?: {
710
+ name: string;
711
+ version: string;
712
+ };
713
+ transport?: 'stdio' | 'http' | 'sse' | 'sdk'; /** stdio only. */
714
+ command?: string;
715
+ /** stdio only. Secrets do occasionally ride argv; the operator's own client
716
+ * shows them, and hiding them here would only mislead. `env` is not exposed. */
717
+ args?: string[]; /** http/sse only. */
718
+ url?: string; /** Present when connected. */
719
+ tools?: McpServerToolInfo[];
720
+ };
721
+ type McpServersResponse = {
722
+ servers: McpServerStatusInfo[];
723
+ };
724
+ /** `POST {basePath}/sessions/:id/mcp/:name` — answers with the refreshed status. */
725
+ type McpServerActionRequest = {
726
+ action: 'reconnect' | 'enable' | 'disable';
727
+ };
728
+ /** `POST {basePath}/sessions/:id/attachments?name=<name>` — the body is the raw
729
+ * file, the `content-type` header its media type. Answers with the reference to
730
+ * name on the next `user_message`. */
731
+ type UploadAttachmentResponse = {
732
+ attachment: MessageAttachment;
733
+ };
531
734
  type CreateSessionRequest = {
532
735
  /** Directory the session is rooted at. Required: `cwd` is per-query in the SDK
533
736
  * and the server re-pins it on every call. */
@@ -552,7 +755,11 @@ type CreateSessionRequest = {
552
755
  maxTurns?: number;
553
756
  maxBudgetUsd?: number; /** Resume an existing SDK session by id. */
554
757
  resume?: string; /** With `resume`: fork to a new session id instead of continuing. */
555
- forkSession?: boolean; /** Emit `stream_delta` events for token-by-token rendering. Default true. */
758
+ forkSession?: boolean;
759
+ /** Reasoning effort for the session's model (codex engine). Open string —
760
+ * offerable values come from the profile's catalog/capability record. The
761
+ * gateway 400s it when the engine's record declares no `reasoningEfforts`. */
762
+ reasoningEffort?: string; /** Emit `stream_delta` events for token-by-token rendering. Default true. */
556
763
  includePartialMessages?: boolean; /** Per-session override of the server's permission-request timeout (ms). */
557
764
  approvalTimeoutMs?: number; /** AskUserQuestion handling (see {@link QuestionBehavior}). Default 'ask'. */
558
765
  questionBehavior?: QuestionBehavior;
@@ -572,8 +779,18 @@ type SessionInfo = {
572
779
  * session surface gate CLI-only affordances (permission modes, context usage,
573
780
  * rate limits) without looking the profile back up. Absent = 'claude'. */
574
781
  engine?: ProfileEngine;
782
+ /** The engine's capability record, reported by the runner like `engine`. The
783
+ * attach snapshot is the session-level source (no event carries it). Absent =
784
+ * ENGINE_CAPABILITIES[engine]. */
785
+ capabilities?: EngineCapabilities;
575
786
  model?: string;
576
- permissionMode?: PermissionMode; /** See the `system_init` event; 'oauth' = claude.ai subscription credentials. */
787
+ permissionMode?: PermissionMode;
788
+ /** Whether this session may be switched into `bypassPermissions`. The CLI only
789
+ * allows it when the process was spawned for it, so it is decided at creation
790
+ * and never changes: a session that did not ask for bypass up front cannot
791
+ * gain it later. Lets a picker disable the mode instead of offering a switch
792
+ * the engine will refuse. Absent = unknown (an older server). */
793
+ canBypassPermissions?: boolean; /** See the `system_init` event; 'oauth' = claude.ai subscription credentials. */
577
794
  apiKeySource?: string;
578
795
  createdAt: number; /** Highest event seq emitted so far; attach with `afterSeq` to catch up. */
579
796
  lastSeq: number;
@@ -585,9 +802,15 @@ type SessionInfo = {
585
802
  lastActivityAt?: number;
586
803
  };
587
804
  /**
588
- * A session in the Agent SDK's on-disk store (independent of this server's registry).
589
- * Listed so hosts can offer "resume" across server restarts: feed `sessionId` to
590
- * CreateSessionRequest.resume. Mirrors the SDK's SDKSessionInfo, kept browser-safe.
805
+ * A session in an engine's on-disk store (independent of this server's registry):
806
+ * the Agent SDK's session files, or a codex profile's CODEX_HOME threads. Listed
807
+ * so hosts can offer "resume" across server restarts: feed `sessionId` to
808
+ * CreateSessionRequest.resume — under a profile of the SAME engine, since the id
809
+ * only means something to the store it came from. `GET {basePath}/sdk-sessions`
810
+ * takes an optional `profile` query parameter naming whose store to list; absent,
811
+ * the profile is resolved implicitly when the server declares exactly one, else
812
+ * the Claude engine's store is listed (the pre-engine-aware behavior). Mirrors
813
+ * the SDK's SDKSessionInfo shape, kept browser-safe.
591
814
  */
592
815
  type SdkSessionSummary = {
593
816
  sessionId: string; /** Custom title, auto summary, or first prompt — whichever the SDK has. */
@@ -680,6 +903,101 @@ type CreateProfileRequest = ProfileInfo;
680
903
  /** `PATCH {basePath}/profiles/:name` — merge into a managed profile. The name is
681
904
  * the route, not the body; pass `null` to clear an optional field. */
682
905
  type UpdateProfileRequest = Omit<Partial<ProfileInfo>, 'name'>;
906
+ /**
907
+ * The **host's real project tree**, not a session's in-memory VFS — the two are
908
+ * unrelated despite both being "files". {@link SessionFileInfo} is a deliverable
909
+ * the agent produced inside a session; these routes read and write the operator's
910
+ * actual disk.
911
+ *
912
+ * That makes them **operator-privileged**: they are authorized by the server's auth
913
+ * key alone and deliberately sit outside the agent permission flow, because the
914
+ * caller *is* the operator, not the model. A client holding the key can already
915
+ * start a session with any allowed cwd; browsing that same tree grants it nothing
916
+ * new. Writing does, which is why writes are separately enabled server-side.
917
+ *
918
+ * The whole surface is opt-in and root-scoped: with no roots configured every route
919
+ * below 404s. There is no "unset means anything" default here — a phone on a tailnet
920
+ * must never be one request away from `~/.ssh`.
921
+ */
922
+ type HostFileRoot = {
923
+ /** Absolute, canonical (symlinks resolved) path of the root. */path: string; /** Last path segment, for display — roots are not named by the operator. */
924
+ name: string;
925
+ };
926
+ /** `GET {basePath}/fs/roots` — where a client may start browsing. Empty `roots`
927
+ * never happens: the routes are absent entirely when none are configured. */
928
+ type ListHostRootsResponse = {
929
+ roots: HostFileRoot[]; /** Whether `PUT /fs/write` is enabled here; lets a UI hide an editor it can't save from. */
930
+ canWrite: boolean;
931
+ };
932
+ /** One entry in a host directory listing. Classified with `lstat` semantics, so a
933
+ * `symlink` is reported as itself and never silently resolved — following it is the
934
+ * *next* request's problem, and that request is refused if it escapes the roots. */
935
+ type HostDirEntry = {
936
+ name: string; /** Absolute path, ready to pass back as `?path=`. */
937
+ path: string;
938
+ type: 'file' | 'dir' | 'symlink' | 'other'; /** Regular files only. */
939
+ bytes?: number; /** Epoch ms mtime. */
940
+ modifiedAt?: number;
941
+ };
942
+ /** `GET {basePath}/fs/list?path=<abs>` — one directory, not recursive. */
943
+ type ListHostDirResponse = {
944
+ /** Canonical path actually listed (the request's path after symlink resolution). */path: string; /** Directories first, then files, each alphabetical. */
945
+ entries: HostDirEntry[]; /** Set when the directory held more entries than the server will return. */
946
+ truncated?: boolean;
947
+ };
948
+ /** One hit from `GET {basePath}/fs/find`. */
949
+ type HostFileMatch = {
950
+ /** Absolute path, for a follow-up read. */path: string; /** Path relative to the searched directory — what a picker shows and inserts. */
951
+ relative: string;
952
+ };
953
+ /**
954
+ * `GET {basePath}/fs/find?path=<dir>&q=<query>&limit=<n>` — recursive fuzzy file
955
+ * search under one directory, which is what an `@file` picker needs and
956
+ * `/fs/list` is not: listing answers "what is in this directory", this answers
957
+ * "which file in this tree did you mean".
958
+ *
959
+ * Subsequence matching (`seslist` finds `SessionListView.swift`), filename hits
960
+ * ranked above path hits, shallow files above deep ones. An empty `q` returns the
961
+ * shallowest files. Build directories (`.git`, `node_modules`, …) are skipped, as
962
+ * is anything behind a symlink — so every path returned is one `/fs/read` will
963
+ * accept.
964
+ */
965
+ type FindHostFilesResponse = {
966
+ /** Canonical directory the search ran under; `relative` paths are relative to it. */base: string;
967
+ matches: HostFileMatch[]; /** More matched, or the tree was larger than the server would walk. */
968
+ truncated: boolean;
969
+ };
970
+ /** `GET {basePath}/fs/read?path=<abs>` — one file's contents. Binary files come back
971
+ * base64; 413 rather than a truncated read when the file exceeds the server's cap. */
972
+ type ReadHostFileResponse = {
973
+ path: string;
974
+ content: string;
975
+ encoding: 'utf8' | 'base64';
976
+ bytes: number; /** sha256 (hex) of the bytes on disk. Pass it back as `expectedHash` to write. */
977
+ hash: string;
978
+ modifiedAt: number;
979
+ };
980
+ /**
981
+ * `PUT {basePath}/fs/write` — replace or create one file.
982
+ *
983
+ * The agent is editing this same tree, so a write is **conditional, always**:
984
+ * `expectedHash` must be the hash from the read this edit is based on, and the
985
+ * server 409s if the file has changed since. Omitting it means "create" and 409s
986
+ * if the path already exists — there is no unconditional overwrite, by design.
987
+ * Directories are never created implicitly: writing under a missing parent is a 404.
988
+ */
989
+ type WriteHostFileRequest = {
990
+ path: string;
991
+ content: string; /** Default 'utf8'. */
992
+ encoding?: 'utf8' | 'base64'; /** Required to overwrite; omit only to create a new file. */
993
+ expectedHash?: string;
994
+ };
995
+ type WriteHostFileResponse = {
996
+ path: string;
997
+ bytes: number; /** Hash of what was just written — carry it into the next edit. */
998
+ hash: string;
999
+ modifiedAt: number;
1000
+ };
683
1001
  type SaveProfileResponse = {
684
1002
  profile: ProfileInfo;
685
1003
  };
@@ -895,5 +1213,5 @@ type QueueStatsResponse = {
895
1213
  stats: QueueStats;
896
1214
  };
897
1215
  //#endregion
898
- export { ApiMessage, AttachedFrame, ClientFrame, ContentBlock, ContextUsage, ContextUsageCategory, CreateJobRequest, CreateJobResponse, CreateProfileRequest, CreateSessionRequest, CreateSessionResponse, ErrorResponse, GetJobResponse, GetProfileResponse, GetSessionResponse, JobEvent, JobInfo, JobProgress, JobResult, JobStatus, JobUsage, ListJobsResponse, ListProfilesResponse, ListSdkSessionsResponse, ListSessionFilesResponse, ListSessionsResponse, McpServerConfigWire, ModelOption, PROTOCOL_VERSION, PROVIDER_PERMISSION_MODES, PermissionDecisionSource, PermissionMode, PermissionRequest, ProfileConfigSnapshot, ProfileDefaults, ProfileEngine, ProfileInfo, ProfileSessionDefaults, ProviderConfig, QuestionBehavior, QueueServerFrame, QueueStats, QueueStatsResponse, RateLimitInfo, ResolvePermissionRequest, ResolvePermissionResponse, SaveProfileResponse, SdkSessionSummary, ServerFrame, SessionCapability, SessionCommand, SessionEvent, SessionEventBody, SessionFileInfo, SessionInfo, SessionNotification, SessionNotificationType, SessionStatus, SessionWebhookConfig, SlashCommandInfo, SubmitExecutionResultRequest, SubmitExecutionResultResponse, TextBlock, ThinkingBlock, ToolCallRequestFrame, ToolExecutionBackend, ToolExecutionOutput, ToolExecutionStatus, ToolResultBlock, ToolUseBlock, UnknownBlock, UpdateProfileRequest, UserQuestion, UserQuestionOption, WebhookConfig, supportsPermissionMode };
1216
+ export { ApiMessage, AttachedFrame, ClientFrame, ContentBlock, ContextUsage, ContextUsageCategory, CreateJobRequest, CreateJobResponse, CreateProfileRequest, CreateSessionRequest, CreateSessionResponse, ENGINE_CAPABILITIES, EngineCapabilities, ErrorResponse, FindHostFilesResponse, GetJobResponse, GetProfileResponse, GetSessionResponse, HostDirEntry, HostFileMatch, HostFileRoot, JobEvent, JobInfo, JobProgress, JobResult, JobStatus, JobUsage, ListHostDirResponse, ListHostRootsResponse, ListJobsResponse, ListProfilesResponse, ListSdkSessionsResponse, ListSessionFilesResponse, ListSessionsResponse, McpServerActionRequest, McpServerConfigWire, McpServerStatusInfo, McpServerToolInfo, McpServersResponse, MessageAttachment, ModelOption, PROTOCOL_VERSION, PROVIDER_PERMISSION_MODES, PermissionDecisionSource, PermissionMode, PermissionRequest, ProfileConfigSnapshot, ProfileDefaults, ProfileEngine, ProfileInfo, ProfileSessionDefaults, ProviderConfig, QuestionBehavior, QueueServerFrame, QueueStats, QueueStatsResponse, RateLimitInfo, ReadHostFileResponse, ResolvePermissionRequest, ResolvePermissionResponse, SaveProfileResponse, SdkSessionSummary, ServerFrame, SessionCapability, SessionCommand, SessionEvent, SessionEventBody, SessionFileInfo, SessionInfo, SessionNotification, SessionNotificationType, SessionStatus, SessionWebhookConfig, SlashCommandInfo, SubmitExecutionResultRequest, SubmitExecutionResultResponse, TextBlock, ThinkingBlock, ToolCallRequestFrame, ToolExecutionBackend, ToolExecutionOutput, ToolExecutionStatus, ToolResultBlock, ToolUseBlock, UnknownBlock, UpdateProfileRequest, UploadAttachmentResponse, UserQuestion, UserQuestionOption, WebhookConfig, WriteHostFileRequest, WriteHostFileResponse, supportsPermissionMode };
899
1217
  //# sourceMappingURL=index.d.mts.map
package/build/index.mjs CHANGED
@@ -10,26 +10,123 @@
10
10
  * structurally (see {@link ApiMessage}) so clients don't need the Agent SDK to render transcripts.
11
11
  */
12
12
  /** Bumped on any breaking change to events, commands, or REST shapes. */
13
- const PROTOCOL_VERSION = 4;
13
+ const PROTOCOL_VERSION = 6;
14
14
  /**
15
- * Permission modes the model-agnostic provider engine understands. The rest of
16
- * {@link PermissionMode}'s vocabulary is Claude Code's: `acceptEdits`, `plan` and
17
- * `auto` name CLI-side behaviours a provider session has no equivalent of.
15
+ * The static capability record of each engine — the browser-safe default for
16
+ * `ProfileInfo.capabilities` / `SessionInfo.capabilities`, and the single place
17
+ * the values are written down. Core's adapters *reference* this record and a
18
+ * conformance test compares runner behaviour against it, so it cannot silently
19
+ * diverge from the code. When both a wire copy and this default exist, the wire
20
+ * copy wins.
18
21
  */
19
- const PROVIDER_PERMISSION_MODES = [
20
- "default",
21
- "bypassPermissions",
22
- "dontAsk"
23
- ];
22
+ const ENGINE_CAPABILITIES = {
23
+ claude: {
24
+ interactiveApprovals: true,
25
+ permissionModes: [
26
+ "default",
27
+ "acceptEdits",
28
+ "bypassPermissions",
29
+ "plan",
30
+ "dontAsk",
31
+ "auto"
32
+ ],
33
+ defaultPermissionMode: "default",
34
+ resume: true,
35
+ resumeBackfill: true,
36
+ listSessions: true,
37
+ contextUsage: true,
38
+ rateLimits: true,
39
+ mcpStatus: true,
40
+ sessionMcpServers: true,
41
+ slashCommands: true,
42
+ settingSources: true,
43
+ budgets: true,
44
+ attachments: [
45
+ "image",
46
+ "pdf",
47
+ "text"
48
+ ],
49
+ reasoningEfforts: [
50
+ "low",
51
+ "medium",
52
+ "high",
53
+ "xhigh",
54
+ "max"
55
+ ],
56
+ vfs: false,
57
+ streaming: "token"
58
+ },
59
+ codex: {
60
+ interactiveApprovals: true,
61
+ permissionModes: [
62
+ "default",
63
+ "acceptEdits",
64
+ "bypassPermissions"
65
+ ],
66
+ defaultPermissionMode: "default",
67
+ resume: true,
68
+ resumeBackfill: true,
69
+ listSessions: true,
70
+ contextUsage: true,
71
+ rateLimits: true,
72
+ mcpStatus: false,
73
+ sessionMcpServers: false,
74
+ slashCommands: false,
75
+ settingSources: false,
76
+ budgets: false,
77
+ attachments: ["image", "text"],
78
+ reasoningEfforts: [
79
+ "minimal",
80
+ "low",
81
+ "medium",
82
+ "high",
83
+ "xhigh"
84
+ ],
85
+ vfs: false,
86
+ streaming: "token"
87
+ },
88
+ provider: {
89
+ interactiveApprovals: false,
90
+ permissionModes: [
91
+ "default",
92
+ "bypassPermissions",
93
+ "dontAsk"
94
+ ],
95
+ defaultPermissionMode: "default",
96
+ resume: false,
97
+ resumeBackfill: false,
98
+ listSessions: false,
99
+ contextUsage: false,
100
+ rateLimits: false,
101
+ mcpStatus: false,
102
+ sessionMcpServers: false,
103
+ slashCommands: false,
104
+ settingSources: false,
105
+ budgets: false,
106
+ attachments: [
107
+ "image",
108
+ "pdf",
109
+ "text"
110
+ ],
111
+ vfs: true,
112
+ streaming: "token"
113
+ }
114
+ };
115
+ /**
116
+ * Permission modes the model-agnostic provider engine understands.
117
+ * @deprecated Read `ENGINE_CAPABILITIES.provider.permissionModes` (this is an
118
+ * alias of it, kept for protocol-5 consumers).
119
+ */
120
+ const PROVIDER_PERMISSION_MODES = ENGINE_CAPABILITIES.provider.permissionModes;
24
121
  /**
25
122
  * Whether a profile's engine can run a permission mode. The single source of
26
123
  * truth for the restriction: create forms filter what they offer with it, the
27
124
  * gateway rejects with it. An absent `engine` means 'claude' (every mode).
28
125
  */
29
126
  function supportsPermissionMode(engine, mode) {
30
- return engine === "provider" ? PROVIDER_PERMISSION_MODES.includes(mode) : true;
127
+ return ENGINE_CAPABILITIES[engine ?? "claude"].permissionModes.includes(mode);
31
128
  }
32
129
  //#endregion
33
- export { PROTOCOL_VERSION, PROVIDER_PERMISSION_MODES, supportsPermissionMode };
130
+ export { ENGINE_CAPABILITIES, PROTOCOL_VERSION, PROVIDER_PERMISSION_MODES, supportsPermissionMode };
34
131
 
35
132
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @workerdeck/protocol — the wire protocol between a workerdeck server and its clients.\n *\n * One session = one ordered stream of {@link SessionEvent}s (each stamped with a monotonically\n * increasing `seq`) plus a small command set ({@link SessionCommand}). Clients attach over\n * WebSocket, optionally replaying from a known `seq`, and drive the session with commands.\n *\n * This package is dependency-free and browser-safe. Anthropic API message content is modeled\n * structurally (see {@link ApiMessage}) so clients don't need the Agent SDK to render transcripts.\n */\n\n/** Bumped on any breaking change to events, commands, or REST shapes. */\nexport const PROTOCOL_VERSION = 4\n\n// ---------------------------------------------------------------------------\n// Session lifecycle\n// ---------------------------------------------------------------------------\n\n/**\n * - `starting` — runner spawned, waiting for the SDK init handshake\n * - `running` — a turn is in progress\n * - `awaiting_approval` — blocked on at least one pending permission request\n * - `idle` — between turns; accepting user messages\n * - `parked` — waiting on a deferred tool execution. The live runner has been torn\n * down and the session's state persisted; delivering the execution's result\n * (`POST {basePath}/executions/:executionId/result`) rehydrates it under the same\n * id and the run continues. Not terminal.\n * - `failed` — the underlying query errored; terminal\n * - `closed` — closed by a client or the host; terminal\n */\nexport type SessionStatus =\n | 'starting'\n | 'running'\n | 'awaiting_approval'\n | 'idle'\n | 'parked'\n | 'failed'\n | 'closed'\n\nexport type PermissionMode =\n | 'default'\n | 'acceptEdits'\n | 'bypassPermissions'\n | 'plan'\n | 'dontAsk'\n | 'auto'\n\n// ---------------------------------------------------------------------------\n// API message content (structural mirror of Anthropic message shapes)\n// ---------------------------------------------------------------------------\n\nexport type TextBlock = { type: 'text'; text: string }\nexport type ThinkingBlock = { type: 'thinking'; thinking: string }\nexport type ToolUseBlock = { type: 'tool_use'; id: string; name: string; input: unknown }\nexport type ToolResultBlock = {\n type: 'tool_result'\n tool_use_id: string\n content?: string | Array<{ type: string; text?: string; [key: string]: unknown }>\n is_error?: boolean\n}\n/** Forward-compatible fallback for block types this protocol version doesn't model. */\nexport type UnknownBlock = { type: string; [key: string]: unknown }\n\nexport type ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock | UnknownBlock\n\nexport type ApiMessage = {\n role: 'user' | 'assistant'\n content: string | ContentBlock[]\n model?: string\n stop_reason?: string | null\n /** Per-API-call token usage when the message carries it (assistant messages do).\n * Enables mid-run token accounting; result-message usage stays authoritative. */\n usage?: {\n input_tokens?: number\n output_tokens?: number\n cache_creation_input_tokens?: number\n cache_read_input_tokens?: number\n }\n}\n\n// ---------------------------------------------------------------------------\n// Permission requests\n// ---------------------------------------------------------------------------\n\n/** A tool call promoted into a pending approval by the runner's canUseTool hook. */\nexport type PermissionRequest = {\n /** Server-assigned id; used by the `permission_decision` command. */\n id: string\n toolName: string\n input: Record<string, unknown>\n toolUseId: string\n /** Full prompt sentence from the SDK, e.g. \"Claude wants to read foo.txt\". */\n title?: string\n /** Short noun phrase for the tool action, e.g. \"Read file\". */\n displayName?: string\n /** Human-readable subtitle, e.g. \"Claude will have read access to ~/x\". */\n description?: string\n /** Why this permission request was triggered. */\n decisionReason?: string\n /** If raised from within a subagent, that subagent's id. */\n agentId?: string\n /** Epoch ms after which the server resolves it via its timeout policy. */\n expiresAt?: number\n}\n\nexport type PermissionDecisionSource = 'client' | 'timeout' | 'policy'\n\n// ---------------------------------------------------------------------------\n// User questions (the AskUserQuestion tool)\n// ---------------------------------------------------------------------------\n\n/** One choice of an AskUserQuestion question (SDK tool-input mirror). */\nexport type UserQuestionOption = {\n label: string\n description?: string\n /** Optional preview content (markdown unless the session configures html)\n * rendered when the option is focused. */\n preview?: string\n}\n\n/** One question from the AskUserQuestion tool's input. By the tool's convention the\n * first option is the model's recommended choice. */\nexport type UserQuestion = {\n question: string\n /** Short chip/tag label (max ~12 chars), e.g. \"Auth method\". */\n header: string\n options: UserQuestionOption[]\n multiSelect?: boolean\n}\n\n/** How a session treats the AskUserQuestion tool:\n * - 'ask' (default) — a pending permission like any other: interactive UIs render the\n * question form; job webhooks carry the full request so a remote controller can\n * answer over REST (POST /sessions/:id/permissions/:requestId).\n * - 'auto' — resolved immediately with each question's first (recommended) option.\n * - 'deny' — the tool is refused with guidance to decide autonomously (unattended runs).\n * Answers ride a permission allow as `updatedInput.answers`: question text → chosen\n * option label(s), multi-select labels comma-joined — the shape the CLI's own UI uses. */\nexport type QuestionBehavior = 'ask' | 'auto' | 'deny'\n\n// ---------------------------------------------------------------------------\n// Session capabilities (models / slash commands the CLI reports)\n// ---------------------------------------------------------------------------\n\n/** A model the session can switch to (SDK ModelInfo mirror; fields it may grow stay unknown). */\nexport type ModelOption = {\n /** Model id for createSession.model / set_model. */\n value: string\n displayName: string\n description?: string\n}\n\n/** A slash command the CLI accepts as user-message text (SDK SlashCommand mirror). */\nexport type SlashCommandInfo = {\n /** Command name without the leading slash. */\n name: string\n description?: string\n /** Hint for arguments, e.g. \"<file>\". */\n argumentHint?: string\n /** Alternate names resolving to this command. */\n aliases?: string[]\n}\n\n// ---------------------------------------------------------------------------\n// Usage telemetry (context window + subscription rate limits)\n// ---------------------------------------------------------------------------\n\n/** One category row from the CLI's context-usage breakdown (system prompt, tools, ...). */\nexport type ContextUsageCategory = {\n name: string\n tokens: number\n /** Color the CLI assigns the category. Often a CLI theme token name ('inactive',\n * 'promptBorder', ...), not a CSS color — validate before styling with it. */\n color: string\n}\n\n/** Context-window usage snapshot (SDK getContextUsage mirror), polled after each turn. */\nexport type ContextUsage = {\n categories: ContextUsageCategory[]\n totalTokens: number\n maxTokens: number\n /** Used share of the window, 0–100. */\n percentage: number\n /** Model the window sizing applies to. */\n model?: string\n}\n\n/**\n * One rate-limit window snapshot (SDK SDKRateLimitInfo mirror). Emitted only for\n * claude.ai subscription sessions — API-key sessions may never produce one, so\n * clients must render nothing (not 0%) until data arrives.\n */\nexport type RateLimitInfo = {\n /** 'allowed' | 'allowed_warning' | 'rejected' — kept as string, the SDK union may grow. */\n status: string\n /** Which window: 'five_hour' (session), 'seven_day' (weekly), 'seven_day_opus',\n * 'seven_day_sonnet', 'overage', ... — kept as string, the SDK union may grow. */\n rateLimitType?: string\n /** Used share of the window, 0–100. The CLI omits it on some updates — treat\n * absent as unknown, not 0. */\n utilization?: number\n /** Epoch **seconds** when the window resets (render countdowns client-side). */\n resetsAt?: number\n isUsingOverage?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Tool execution (bridged, deferred, and remote)\n// ---------------------------------------------------------------------------\n\n/**\n * Lifecycle of one tool execution, correlated by `executionId` end to end.\n *\n * - `pending` — dispatched, result not in yet (bridged to a client, or queued).\n * - `deferred` — parked beyond this turn/process; may outlive the session's\n * liveness and be applied on rehydration.\n * - `settled` / `failed` — terminal. Results are applied idempotently by id, so\n * a duplicate delivery is a no-op rather than a second application.\n */\nexport type ToolExecutionStatus = 'pending' | 'deferred' | 'settled' | 'failed'\n\n/** Where a tool execution ran (or is running). Advisory: for display and routing. */\nexport type ToolExecutionBackend = 'server' | 'browser' | 'managed' | 'remote'\n\n/** Result payload of a tool execution, by value — never a live host reference. */\nexport type ToolExecutionOutput =\n | { type: 'text'; value: string }\n | { type: 'json'; value: unknown }\n\n// ---------------------------------------------------------------------------\n// Session events (server -> client)\n// ---------------------------------------------------------------------------\n\nexport type SessionEventBody =\n /** SDK init handshake: what this session actually is. */\n | {\n type: 'system_init'\n sdkSessionId: string\n model: string\n cwd: string\n /** Where the session's Anthropic auth came from: 'oauth' means a claude.ai\n * subscription login; other values ('user' | 'project' | 'org' | 'temporary')\n * are API-key provenance. Kept as string — the SDK union may grow. */\n apiKeySource: string\n tools: string[]\n skills: string[]\n slashCommands: string[]\n permissionMode: PermissionMode\n claudeCodeVersion: string\n mcpServers: Array<{ name: string; status: string }>\n }\n | { type: 'status_changed'; status: SessionStatus; detail?: string }\n /** Models and slash commands available to this session; fetched from the CLI after\n * init. Late attachers get it via replay like any other event. */\n | { type: 'capabilities'; models: ModelOption[]; commands: SlashCommandInfo[] }\n /** The session's model changed via `set_model`. `model` undefined = back to default. */\n | { type: 'model_changed'; model?: string }\n /** The session's permission mode changed via `set_permission_mode`. */\n | { type: 'permission_mode_changed'; mode: PermissionMode }\n /** Context-window usage snapshot; the runner polls it after each turn. */\n | { type: 'context_usage'; usage: ContextUsage }\n /** Subscription rate-limit update for one window (see {@link RateLimitInfo}). */\n | { type: 'rate_limit'; info: RateLimitInfo }\n | {\n type: 'assistant_message'\n message: ApiMessage\n /** Set when the message was produced inside a subagent (Task tool). */\n parentToolUseId: string | null\n /** True when backfilled from a resumed session's history. */\n replay?: boolean\n uuid: string\n }\n | {\n type: 'user_message'\n message: ApiMessage\n parentToolUseId: string | null\n /** True when replayed from a resumed session's history. */\n replay?: boolean\n /** True for tool results and other synthetic user-role messages. */\n synthetic?: boolean\n uuid?: string\n }\n /** Raw Anthropic streaming event (message_start/content_block_delta/...); emitted only\n * when the session was created with `includePartialMessages`. */\n | {\n type: 'stream_delta'\n event: { type: string; [key: string]: unknown }\n parentToolUseId: string | null\n uuid: string\n }\n | {\n type: 'turn_result'\n subtype:\n | 'success'\n | 'error_during_execution'\n | 'error_max_turns'\n | 'error_max_budget_usd'\n | 'error_max_structured_output_retries'\n isError: boolean\n durationMs: number\n numTurns: number\n totalCostUsd: number\n /** Final text of the turn (success only). */\n result?: string\n errors?: string[]\n usage?: unknown\n }\n | { type: 'permission_requested'; request: PermissionRequest }\n | {\n type: 'permission_resolved'\n requestId: string\n behavior: 'allow' | 'deny'\n resolvedBy: PermissionDecisionSource\n /** Denial message, when denied. */\n message?: string\n }\n /** A tool execution was dispatched to a backend. For bridged executions this\n * precedes the `tool_call_request` frame; for deferred ones it is the record\n * that survives a teardown. */\n | {\n type: 'execution_dispatched'\n executionId: string\n toolName: string\n backend: ToolExecutionBackend\n /** True when the execution may outlive this turn or process. */\n deferred?: boolean\n /** Epoch ms after which the server applies its timeout policy. */\n expiresAt?: number\n }\n /** A dispatched execution produced a result. Applied idempotently by `executionId`. */\n | {\n type: 'execution_result'\n executionId: string\n output: ToolExecutionOutput\n /** Guest/agent-visible logs, if the backend captured any. */\n logs?: string[]\n durationMs?: number\n }\n /** A dispatched execution failed, timed out, or was orphaned. The failure is fed\n * back into the loop as tool output so the agent can adapt — it is not a session error. */\n | {\n type: 'execution_failed'\n executionId: string\n /** Machine-readable cause: 'timeout' | 'oom' | 'exception' | 'orphaned' | backend-specific. */\n reason: string\n error: string\n logs?: string[]\n durationMs?: number\n }\n /** The agent handed over a file from its session scratch filesystem (the\n * `deliver_file` tool). Download it via `GET {basePath}/sessions/:id/files/<path>`\n * for as long as the session lives (the VFS is in-memory). */\n | { type: 'file_delivered'; path: string; bytes: number; description?: string }\n /** Any SDKMessage this protocol version doesn't model first-class (task progress,\n * compaction boundaries, auth status, ...). Payload is the raw SDK message. */\n | { type: 'sdk_event'; payload: { type: string; [key: string]: unknown } }\n | { type: 'session_error'; message: string }\n | { type: 'session_closed'; reason: 'client' | 'server' | 'error' }\n\nexport type SessionEvent = SessionEventBody & {\n /** Monotonic per-session sequence number, starting at 1. */\n seq: number\n /** Epoch ms when the server emitted the event. */\n ts: number\n}\n\n// ---------------------------------------------------------------------------\n// Commands (client -> server)\n// ---------------------------------------------------------------------------\n\nexport type SessionCommand =\n | { type: 'user_message'; text: string }\n | {\n type: 'permission_decision'\n requestId: string\n behavior: 'allow' | 'deny'\n /** allow only: modified tool input to run instead of the original. */\n updatedInput?: Record<string, unknown>\n /** deny only: reason surfaced to the model. */\n message?: string\n /** deny only: also interrupt the running turn. */\n interrupt?: boolean\n }\n | { type: 'interrupt' }\n | { type: 'set_permission_mode'; mode: PermissionMode }\n /** Switch the model for subsequent responses; omit `model` for the default. */\n | { type: 'set_model'; model?: string }\n /**\n * Result of a tool execution the server bridged to this client (see\n * {@link ToolCallRequestFrame}). Unknown or already-settled `executionId`s are\n * ignored — delivery is idempotent, and a late result after a timeout must not\n * re-open a settled call.\n *\n * Browser-returned results are UNTRUSTED input: acceptable for the user's own\n * data, never a source for server-authoritative state.\n */\n | {\n type: 'tool_call_result'\n executionId: string\n output: ToolExecutionOutput\n logs?: string[]\n }\n /** The client could not execute a bridged call (unsupported tool, guest error,\n * tab closing). Fed back to the agent as tool output. */\n | {\n type: 'tool_call_error'\n executionId: string\n reason: string\n error: string\n logs?: string[]\n }\n | { type: 'close' }\n\n// ---------------------------------------------------------------------------\n// WebSocket frames\n// ---------------------------------------------------------------------------\n\n/** First frame the server sends after a successful attach. */\nexport type AttachedFrame = {\n type: 'attached'\n protocolVersion: number\n session: SessionInfo\n /** Events with seq > the client's `afterSeq` follow as `event` frames. */\n replayingFrom: number\n}\n\n/**\n * Ask the attached client to execute a tool call in its own sandbox (browser\n * bridge). The client answers with `tool_call_result` or `tool_call_error`\n * carrying the same `executionId`.\n *\n * Only sandbox-benefiting tools are ever bridged. Authenticated/authoritative\n * tools (MCP, secret-bearing APIs) execute server-side and never appear here.\n */\nexport type ToolCallRequestFrame = {\n type: 'tool_call_request'\n executionId: string\n toolName: string\n input: unknown\n /** Files to seed the client's scratch VFS with, path → contents. */\n vfsSeed?: Record<string, string>\n limits?: { timeoutMs?: number; memoryLimitBytes?: number }\n /** Epoch ms after which the server gives up and fails the execution. */\n expiresAt?: number\n}\n\nexport type ServerFrame =\n | AttachedFrame\n | { type: 'event'; event: SessionEvent }\n | ToolCallRequestFrame\n /** A bridged execution no longer needs an answer (turn interrupted, timed out,\n * or the session closed) — the client should abandon it. */\n | { type: 'tool_call_canceled'; executionId: string; reason: string }\n | { type: 'protocol_error'; message: string }\n\nexport type ClientFrame = SessionCommand\n\n// ---------------------------------------------------------------------------\n// Profiles (named Claude Code config directories)\n// ---------------------------------------------------------------------------\n\n/** Per-profile fallbacks filled into session/job requests that leave the field\n * unset. Defaults, not enforced caps — an explicit request value always wins. */\nexport type ProfileDefaults = {\n model?: string\n permissionMode?: PermissionMode\n}\n\n/**\n * A named Claude Code config directory sessions can run under: the session's CLI\n * process gets it as CLAUDE_CONFIG_DIR, so the profile carries that directory's\n * settings, memory, skills, and whatever credentials the SDK/CLI resolves from it.\n * Profiles are declared in server options at startup (or a 'default' one is\n * auto-created from the operator's own config dir) — the API only reads them.\n */\n/**\n * Which engine a profile runs on.\n * - `claude` (default) — Claude Code via the Agent SDK, configured by a config dir.\n * - `provider` — a model-agnostic provider (OpenAI-compatible, Anthropic, Moonshot),\n * configured by provider id and credentials from the operator's environment.\n */\nexport type ProfileEngine = 'claude' | 'provider'\n\n/**\n * Permission modes the model-agnostic provider engine understands. The rest of\n * {@link PermissionMode}'s vocabulary is Claude Code's: `acceptEdits`, `plan` and\n * `auto` name CLI-side behaviours a provider session has no equivalent of.\n */\nexport const PROVIDER_PERMISSION_MODES: readonly PermissionMode[] = [\n 'default',\n 'bypassPermissions',\n 'dontAsk',\n]\n\n/**\n * Whether a profile's engine can run a permission mode. The single source of\n * truth for the restriction: create forms filter what they offer with it, the\n * gateway rejects with it. An absent `engine` means 'claude' (every mode).\n */\nexport function supportsPermissionMode(\n engine: ProfileEngine | undefined,\n mode: PermissionMode,\n): boolean {\n return engine === 'provider' ? PROVIDER_PERMISSION_MODES.includes(mode) : true\n}\n\n/**\n * A model provider a `provider` profile can run on. Credentials are ALWAYS\n * resolved from the operator's environment — never carried on the wire, never\n * stored here. `apiKeyEnv` names the variable to read, it does not hold a key.\n */\nexport type ProviderConfig = {\n /** Provider adapter to use, e.g. 'anthropic' | 'openai' | 'moonshotai' |\n * 'openai-compatible'. Kept as a string: the set is host-extensible. */\n id: string\n /** Default model id, e.g. 'kimi-k3'. Overridable per session. */\n model?: string\n /** Model ids this profile offers, for the dashboard's picker. Operator-declared\n * rather than discovered: provider engines have no equivalent of the CLI's\n * `supportedModels()`, and only the operator knows which ids their endpoint and\n * key actually serve. Unset → the picker offers {@link ProviderConfig.model} alone. */\n models?: string[]\n /** Base URL for OpenAI-compatible providers. */\n baseUrl?: string\n /** Environment variable the operator put the key in. Never the key itself. */\n apiKeyEnv?: string\n}\n\n/**\n * A grantable capability of the model-agnostic engine, named after the tool it\n * yields. The always-present tools (`fs_*`, `eval_script`) are not listed: they\n * are the engine's scratch filesystem and sandbox, not a grant.\n */\nexport type SessionCapability = 'web_search' | 'download' | 'web_fetch' | 'deliver_file'\n\n/**\n * What sessions under a `provider` profile get, declared by the operator. Meaning-\n * less for `claude` profiles, whose equivalents live in the config directory.\n *\n * MCP servers are named, never configured, here: a server's transport config can\n * carry credentials in its headers, and this type is served by `GET /profiles`.\n * The names refer to servers the host connected in `createEngineRunner`, which is\n * where the configs (and the credentials) stay.\n */\nexport type ProfileSessionDefaults = {\n /** Capabilities granted to sessions under this profile. Absent = no\n * declaration, so a session gets whatever backends the host wired. A session\n * request may narrow this set, never widen it. */\n capabilities?: SessionCapability[]\n /** MCP servers, by name, whose tools sessions under this profile may use.\n * Absent = no declaration (every server the host connected). */\n mcpServers?: string[]\n /** Prepended to the session's system prompt. */\n instructions?: string\n}\n\nexport type ProfileInfo = {\n /** Unique name, used as {@link CreateSessionRequest.profile}. */\n name: string\n /** Engine this profile runs on. Defaults to 'claude' when absent, so profiles\n * written before provider support keep working unchanged. */\n engine?: ProfileEngine\n /** Absolute path set as CLAUDE_CONFIG_DIR for the session's CLI process.\n * Required for 'claude' profiles; meaningless for 'provider' ones. */\n configDir?: string\n /** Provider wiring for 'provider' profiles. */\n provider?: ProviderConfig\n description?: string\n defaults?: ProfileDefaults\n /** Provider-engine session grants (capabilities, MCP servers, instructions). */\n session?: ProfileSessionDefaults\n /** Response-only, computed by the server: this profile came from the profile\n * store and can be edited or deleted through the API. Profiles declared in\n * server options are absent/false — they are code. Ignored on the way in. */\n managed?: boolean\n}\n\n/**\n * Curated, read-only snapshot of what a profile's config directory contains —\n * the parts relevant to running worker sessions. Values that could carry secrets\n * (env var values) never leave the server; only names are listed.\n */\nexport type ProfileConfigSnapshot = {\n /** From the config dir's settings.json; absent when missing or unparseable. */\n settings?: {\n /** Configured default model. */\n model?: string\n /** permissions.defaultMode — the CLI's default permission mode. */\n defaultPermissionMode?: string\n /** Rule counts from permissions.allow / ask / deny. */\n permissionRules?: { allow: number; ask: number; deny: number }\n /** Env var NAMES declared in settings.json env (values never included). */\n envKeys?: string[]\n /** Hook event names with at least one hook configured. */\n hooks?: string[]\n }\n /** CLAUDE.md (user memory) present in the config dir. */\n hasUserMemory: boolean\n /** Skill names (skills/<name>/). */\n skills: string[]\n /** Agent names (agents/<name>.md). */\n agents: string[]\n /** Custom slash-command names (commands/<name>.md). */\n commands: string[]\n}\n\n// ---------------------------------------------------------------------------\n// REST shapes\n// ---------------------------------------------------------------------------\n\nexport type McpServerConfigWire =\n | { type?: 'stdio'; command: string; args?: string[]; env?: Record<string, string> }\n | { type: 'http'; url: string; headers?: Record<string, string> }\n | { type: 'sse'; url: string; headers?: Record<string, string> }\n\nexport type CreateSessionRequest = {\n /** Directory the session is rooted at. Required: `cwd` is per-query in the SDK\n * and the server re-pins it on every call. */\n cwd: string\n /** Profile (named Claude Code config dir) to run under. Required when the server\n * declares more than one profile; implicit when exactly one exists. */\n profile?: string\n /** Optional initial prompt (may be a skill invocation like \"/verify-content 123\"). */\n prompt?: string\n permissionMode?: PermissionMode\n /** Pre-authorize 'bypassPermissions' (the CLI's --dangerously-skip-permissions\n * capability) so the mode can be switched on mid-session. Without it the CLI\n * rejects `set_permission_mode: 'bypassPermissions'` on a running session.\n * Implied when `permissionMode` is already 'bypassPermissions'. */\n allowDangerouslySkipPermissions?: boolean\n allowedTools?: string[]\n disallowedTools?: string[]\n mcpServers?: Record<string, McpServerConfigWire>\n /** Which filesystem settings the session loads. Include 'project' to pick up the\n * target repo's skills and CLAUDE.md (\"close-to-real\" fidelity). */\n settingSources?: Array<'user' | 'project' | 'local'>\n model?: string\n maxTurns?: number\n maxBudgetUsd?: number\n /** Resume an existing SDK session by id. */\n resume?: string\n /** With `resume`: fork to a new session id instead of continuing. */\n forkSession?: boolean\n /** Emit `stream_delta` events for token-by-token rendering. Default true. */\n includePartialMessages?: boolean\n /** Per-session override of the server's permission-request timeout (ms). */\n approvalTimeoutMs?: number\n /** AskUserQuestion handling (see {@link QuestionBehavior}). Default 'ask'. */\n questionBehavior?: QuestionBehavior\n /** Provider engine only: run with fewer capabilities than the profile grants\n * (see {@link ProfileSessionDefaults.capabilities}). Narrowing only — naming a\n * capability the profile does not grant is a 400, not a silent upgrade. */\n capabilities?: SessionCapability[]\n /** Free-form metadata echoed back on SessionInfo (host app bookkeeping). */\n meta?: Record<string, unknown>\n}\n\nexport type SessionInfo = {\n /** Server-assigned id (stable across SDK session forks/resumes). */\n id: string\n /** Underlying Agent SDK session id, once known; use for `resume`. */\n sdkSessionId?: string\n status: SessionStatus\n cwd: string\n /** Profile the session runs under (resolved name, present even when implicit). */\n profile?: string\n /** Engine actually running this session, reported by the runner itself. Lets a\n * session surface gate CLI-only affordances (permission modes, context usage,\n * rate limits) without looking the profile back up. Absent = 'claude'. */\n engine?: ProfileEngine\n model?: string\n permissionMode?: PermissionMode\n /** See the `system_init` event; 'oauth' = claude.ai subscription credentials. */\n apiKeySource?: string\n createdAt: number\n /** Highest event seq emitted so far; attach with `afterSeq` to catch up. */\n lastSeq: number\n pendingPermissionCount: number\n meta?: Record<string, unknown>\n /** Display title: `meta.title` if the host set one, else derived (e.g. first prompt). */\n title?: string\n /** Cumulative cost across all turns so far (sum of turn_result totals). */\n totalCostUsd?: number\n /** Cumulative turn count across the session. */\n numTurns?: number\n /** Epoch ms of the most recent emitted event. */\n lastActivityAt?: number\n}\n\n/**\n * A session in the Agent SDK's on-disk store (independent of this server's registry).\n * Listed so hosts can offer \"resume\" across server restarts: feed `sessionId` to\n * CreateSessionRequest.resume. Mirrors the SDK's SDKSessionInfo, kept browser-safe.\n */\nexport type SdkSessionSummary = {\n sessionId: string\n /** Custom title, auto summary, or first prompt — whichever the SDK has. */\n summary: string\n /** Epoch ms of last modification. */\n lastModified: number\n createdAt?: number\n customTitle?: string\n firstPrompt?: string\n gitBranch?: string\n cwd?: string\n}\n\n/** One deliverable in the session's scratch filesystem (see the `file_delivered` event). */\nexport type SessionFileInfo = { path: string; bytes: number }\n/** `GET {basePath}/sessions/:id/files` — every file currently in the session's VFS.\n * `GET {basePath}/sessions/:id/files/<path>` downloads one (attachment disposition).\n * 404 when the session's engine exposes no VFS (Claude-engine sessions). */\nexport type ListSessionFilesResponse = { files: SessionFileInfo[] }\nexport type ListSessionsResponse = { sessions: SessionInfo[] }\nexport type CreateSessionResponse = { session: SessionInfo }\nexport type GetSessionResponse = { session: SessionInfo }\n\n/** Body of `POST {basePath}/sessions/:id/permissions/:requestId` — the REST counterpart\n * of the WS `permission_decision` command, for remote controllers without a socket\n * (e.g. answering a job's AskUserQuestion from a webhook consumer). 404 = the request\n * is unknown, already resolved, or expired. */\nexport type ResolvePermissionRequest =\n | { behavior: 'allow'; updatedInput?: Record<string, unknown> }\n | { behavior: 'deny'; message?: string; interrupt?: boolean }\nexport type ResolvePermissionResponse = { resolved: true }\n\n/**\n * Body of `POST {basePath}/executions/:executionId/result` — the way a deferred\n * executor (a remote worker, a batch job, a human) delivers the outcome of an\n * execution the session parked on. The session is rehydrated if its runner was\n * torn down, and the result is folded back into the agent loop; a `failed` result\n * is ordinary tool output the agent adapts to, not a session error.\n *\n * Applied **idempotently by `executionId`**: a duplicate or late delivery (one\n * racing the execution watchdog) answers 200 with `applied: false` rather than\n * erroring or applying twice. 404 means no session is parked on that id.\n */\nexport type SubmitExecutionResultRequest =\n | { status: 'ok'; output: ToolExecutionOutput; logs?: string[] }\n | { status: 'failed'; reason: string; error: string; logs?: string[] }\nexport type SubmitExecutionResultResponse = {\n /** False when the id was already settled — the delivery was a no-op. */\n applied: boolean\n /** Session the execution belonged to. */\n sessionId: string\n}\n\nexport type ListSdkSessionsResponse = { sdkSessions: SdkSessionSummary[] }\n/** `GET {basePath}/profiles` — filtered to the profiles the caller may use. */\nexport type ListProfilesResponse = {\n profiles: ProfileInfo[]\n /** Whether this caller may create profiles here — true only when the server has\n * a profile store AND the principal carries `canManageProfiles`. Lets a UI hide\n * controls that would always be refused. */\n canManage?: boolean\n}\n\n/**\n * `POST {basePath}/profiles` — create a managed profile. Available only when the\n * server was given a profile store, and only to a principal with\n * `canManageProfiles`. Profiles declared in server options are code, not data:\n * they cannot be created, edited, or deleted through these routes.\n */\nexport type CreateProfileRequest = ProfileInfo\n\n/** `PATCH {basePath}/profiles/:name` — merge into a managed profile. The name is\n * the route, not the body; pass `null` to clear an optional field. */\nexport type UpdateProfileRequest = Omit<Partial<ProfileInfo>, 'name'>\n\nexport type SaveProfileResponse = { profile: ProfileInfo }\n/** `GET {basePath}/profiles/:name` — the profile plus a fresh config snapshot. */\nexport type GetProfileResponse = { profile: ProfileInfo; config: ProfileConfigSnapshot }\nexport type ErrorResponse = { error: string }\n\n// ---------------------------------------------------------------------------\n// Session notifications (the out-of-band \"something wants you\" channel)\n// ---------------------------------------------------------------------------\n\n/**\n * The moments in an *interactive* session a person needs to hear about when they\n * are not watching it — the whole point being that a phone cannot hold a\n * WebSocket open in the background, so the server has to reach out.\n *\n * Deliberately four: this is a human-attention channel, not an event mirror. The\n * event log stays on the session WS (attach with `afterSeq` to catch up); if you\n * want every assistant message, subscribe there instead.\n */\nexport type SessionNotificationType =\n /** The agent is blocked on an approval — the one that matters most. */\n | 'permission_requested'\n /** A turn finished; the session is idle and waiting for the human. */\n | 'turn_completed'\n /** The session failed (`session_error`). */\n | 'session_error'\n /** The session ended (`session_closed`), whoever ended it. */\n | 'session_closed'\n\n/** One delivery on the session-notification channel (JSON body of a webhook POST). */\nexport type SessionNotification = {\n type: SessionNotificationType\n sessionId: string\n /** Snapshot at notification time — status, title, cwd, cost, `lastSeq`. */\n session: SessionInfo\n /** Seq of the event behind this notification; attach with `afterSeq: seq - 1` to\n * land on it. */\n seq: number\n ts: number\n /** One line fit for a notification body: the permission title, the turn's final\n * text, the error message. */\n preview?: string\n /** `permission_requested` only: the full request, so a consumer can answer it via\n * `POST {basePath}/sessions/:id/permissions/:requestId` — which is what makes an\n * Approve/Deny action on a lock-screen notification possible. */\n request?: PermissionRequest\n /** `turn_completed` only. */\n result?: { isError: boolean; durationMs: number; numTurns: number; totalCostUsd: number }\n /** `session_closed` only. */\n reason?: 'client' | 'server' | 'error'\n}\n\n/** Where session notifications are POSTed (JSON body = {@link SessionNotification}).\n * Server-wide, not per session: the point is to hear about sessions you did not\n * create yourself and are not attached to. */\nexport type SessionWebhookConfig = {\n url: string\n /** Extra headers sent with every delivery (auth tokens etc.). */\n headers?: Record<string, string>\n /** Types to deliver. Default: all of them. */\n events?: SessionNotificationType[]\n}\n\n// ---------------------------------------------------------------------------\n// Job queue (one-shot scheduled runs over the session runner)\n// ---------------------------------------------------------------------------\n\n/**\n * - `queued` — accepted, waiting for a concurrency slot (or the daily token budget)\n * - `running` — a session is executing the prompt\n * - `parked` — waiting on an external event (a deferred tool execution). Not\n * terminal and not consuming a concurrency slot; resumes to `running` when the\n * result arrives, or fails via the execution watchdog if it never does.\n * - `succeeded` / `failed` — terminal; `result` (and `error` on failure) are set\n * - `canceled` — terminal; canceled by a client before or during the run\n */\nexport type JobStatus = 'queued' | 'running' | 'parked' | 'succeeded' | 'failed' | 'canceled'\n\n/** Where job progress/completion deliveries are POSTed (JSON body = {@link JobEvent}). */\nexport type WebhookConfig = {\n url: string\n /** Extra headers sent with every delivery (auth tokens etc.). */\n headers?: Record<string, string>\n /** Delivery granularity: 'messages' also POSTs job_progress per assistant message /\n * permission request; 'completion' only job_started + job_completed. Default 'messages'. */\n progress?: 'messages' | 'completion'\n}\n\n/**\n * Schedule a one-shot run: the session executes `prompt` unattended and the job\n * completes with that run's result. `session.prompt` is the task and is required;\n * `resume`/`forkSession` are not supported for queued jobs.\n */\nexport type CreateJobRequest = {\n session: CreateSessionRequest & { prompt: string }\n webhook?: WebhookConfig\n /** Per-job token cap; the effective cap is min(this, the server's sessionTokenLimit). */\n maxTokens?: number\n /** Per-job wall-clock cap; the effective cap is min(this, the server's maxJobDurationMs). */\n maxDurationMs?: number\n /** Total run attempts: failed (not canceled) runs re-queue until this many attempts\n * have been made. Default 1 (no retries). */\n attempts?: number\n /** Delay before the first retry, doubled for each subsequent one. Default 5000. */\n retryDelayMs?: number\n /** Host bookkeeping echoed back on JobInfo. */\n meta?: Record<string, unknown>\n}\n\n/** Cumulative resource usage of a job's run. `tokens` counts input + output +\n * cache-creation + cache-read tokens across all turns. */\nexport type JobUsage = {\n tokens: number\n totalCostUsd: number\n numTurns: number\n}\n\n/** Terminal outcome of the job's run (mirrors the final turn_result). */\nexport type JobResult = {\n subtype: string\n isError: boolean\n /** Final text of the run (success only). */\n result?: string\n errors?: string[]\n durationMs: number\n}\n\nexport type JobInfo = {\n id: string\n status: JobStatus\n cwd: string\n /** Profile the run executes under (resolved name, present even when implicit). */\n profile?: string\n prompt: string\n /** Server session id once started — attach via the sessions WS to watch the run live. */\n sessionId?: string\n sdkSessionId?: string\n createdAt: number\n startedAt?: number\n finishedAt?: number\n /** 1-based run attempt this info reflects. */\n attempt?: number\n /** Total attempts configured on the request (see CreateJobRequest.attempts). */\n maxAttempts?: number\n /** For a job re-queued by retry backoff: earliest time the next attempt may start. */\n nextRunAt?: number\n /** Set while `status` is 'parked': when the run parked, and the execution it is\n * waiting on — the id to POST a result to. Cleared when it resumes. */\n parkedAt?: number\n parkedExecutionId?: string\n /** Cumulative across attempts. */\n usage: JobUsage\n result?: JobResult\n /** Failure or cancellation reason (for a queued retry: the previous attempt's error). */\n error?: string\n meta?: Record<string, unknown>\n}\n\n/** Latest mid-run activity, carried on job_progress deliveries. */\nexport type JobProgress = {\n kind: 'assistant_text' | 'tool_use' | 'permission_requested' | 'permission_resolved'\n /** Short human-readable preview (message excerpt, tool name, permission title). */\n preview?: string\n /** 'permission_requested' only: the full request (including AskUserQuestion input) so\n * webhook consumers can answer via POST /sessions/:sessionId/permissions/:requestId. */\n request?: PermissionRequest\n}\n\n/** Webhook delivery payload (also the queue's local event shape). `job_submitted` goes\n * to local observers and the queue WS only — the submitter already has the POST\n * response, so webhooks start at `job_started`. `job_retrying` marks a failed run that\n * was re-queued (`job.nextRunAt` says when); `job_completed` is always terminal. */\nexport type JobEvent =\n | { type: 'job_submitted'; job: JobInfo; ts: number }\n | { type: 'job_started'; job: JobInfo; ts: number }\n | { type: 'job_progress'; job: JobInfo; progress: JobProgress; ts: number }\n /** The run parked on a deferred execution; `executionId` says what it waits on —\n * the id to POST a result to. The *work itself* (tool name, input, VFS seed) went\n * to the executor's own dispatch hook, not over this channel: a webhook consumer\n * learns that a run is waiting, the worker learns what to do. */\n | { type: 'job_parked'; job: JobInfo; executionId: string; ts: number }\n /** A parked run resumed because its execution result arrived. */\n | { type: 'job_resumed'; job: JobInfo; executionId: string; ts: number }\n | { type: 'job_retrying'; job: JobInfo; ts: number }\n | { type: 'job_completed'; job: JobInfo; ts: number }\n\nexport type QueueStats = {\n maxConcurrency: number\n running: number\n queued: number\n /** Jobs waiting on a deferred execution. They hold no concurrency slot and\n * their wall-clock budget is not ticking. */\n parked: number\n sessionTokenLimit?: number\n dailyTokenLimit?: number\n /** Tokens consumed by queue jobs in the current UTC day. */\n dailyTokensUsed: number\n /** True when the daily budget is exhausted and queued jobs are being held. */\n paused: boolean\n}\n\n/** Frames sent on the queue WS (`{basePath}/queue/ws`). The stream is one-way\n * (server→client): every job's lifecycle as it happens, plus refreshed stats after\n * lifecycle changes. Clients send nothing; job mutations stay on REST. */\nexport type QueueServerFrame =\n | { type: 'queue_attached'; protocolVersion: number; stats: QueueStats }\n | { type: 'job_event'; event: JobEvent }\n | { type: 'queue_stats'; stats: QueueStats }\n\nexport type CreateJobResponse = { job: JobInfo }\nexport type GetJobResponse = { job: JobInfo }\nexport type ListJobsResponse = { jobs: JobInfo[] }\nexport type QueueStatsResponse = { stats: QueueStats }\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,mBAAmB;;;;;;AA4dhC,MAAa,4BAAuD;CAClE;CACA;CACA;CACD;;;;;;AAOD,SAAgB,uBACd,QACA,MACS;AACT,QAAO,WAAW,aAAa,0BAA0B,SAAS,KAAK,GAAG"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @workerdeck/protocol — the wire protocol between a workerdeck server and its clients.\n *\n * One session = one ordered stream of {@link SessionEvent}s (each stamped with a monotonically\n * increasing `seq`) plus a small command set ({@link SessionCommand}). Clients attach over\n * WebSocket, optionally replaying from a known `seq`, and drive the session with commands.\n *\n * This package is dependency-free and browser-safe. Anthropic API message content is modeled\n * structurally (see {@link ApiMessage}) so clients don't need the Agent SDK to render transcripts.\n */\n\n/** Bumped on any breaking change to events, commands, or REST shapes. */\nexport const PROTOCOL_VERSION = 6\n\n// ---------------------------------------------------------------------------\n// Session lifecycle\n// ---------------------------------------------------------------------------\n\n/**\n * - `starting` — runner spawned, waiting for the SDK init handshake\n * - `running` — a turn is in progress\n * - `awaiting_approval` — blocked on at least one pending permission request\n * - `idle` — between turns; accepting user messages\n * - `parked` — waiting on a deferred tool execution. The live runner has been torn\n * down and the session's state persisted; delivering the execution's result\n * (`POST {basePath}/executions/:executionId/result`) rehydrates it under the same\n * id and the run continues. Not terminal.\n * - `failed` — the underlying query errored; terminal\n * - `closed` — closed by a client or the host; terminal\n */\nexport type SessionStatus =\n | 'starting'\n | 'running'\n | 'awaiting_approval'\n | 'idle'\n | 'parked'\n | 'failed'\n | 'closed'\n\nexport type PermissionMode =\n | 'default'\n | 'acceptEdits'\n | 'bypassPermissions'\n | 'plan'\n | 'dontAsk'\n | 'auto'\n\n// ---------------------------------------------------------------------------\n// API message content (structural mirror of Anthropic message shapes)\n// ---------------------------------------------------------------------------\n\nexport type TextBlock = { type: 'text'; text: string }\nexport type ThinkingBlock = { type: 'thinking'; thinking: string }\nexport type ToolUseBlock = { type: 'tool_use'; id: string; name: string; input: unknown }\nexport type ToolResultBlock = {\n type: 'tool_result'\n tool_use_id: string\n content?: string | Array<{ type: string; text?: string; [key: string]: unknown }>\n is_error?: boolean\n}\n/** Forward-compatible fallback for block types this protocol version doesn't model. */\nexport type UnknownBlock = { type: string; [key: string]: unknown }\n\nexport type ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock | UnknownBlock\n\n/**\n * A file the user attached to a message — a photo, a screenshot, a document.\n *\n * The bytes never travel on this protocol. An attachment is uploaded first\n * (`POST {basePath}/sessions/:id/attachments`), and the command that sends the\n * message names it by id; what lands in the seq-numbered event log is this\n * reference. That is deliberate: the log is replayed to every attaching client\n * and captured into parking snapshots, so a few phone photos inlined as base64\n * would be paid for on every attach, forever. Clients render a thumbnail by\n * fetching `GET {basePath}/sessions/:id/attachments/:attachmentId`.\n *\n * Lifetime is the session's, like `/files` — the store is in-memory and an\n * attachment 404s after a server restart. The message itself is unaffected: the\n * model saw the bytes at send time.\n */\nexport type MessageAttachment = {\n /** Server-assigned; the path segment of the download URL. */\n id: string\n /** Display name from the file the user picked. A leaf name, never a path. */\n name: string\n /** IANA media type, e.g. 'image/jpeg'. The server decides how it reaches the\n * model (image block, document block, or inlined text) from this. */\n mediaType: string\n bytes: number\n}\n\nexport type ApiMessage = {\n role: 'user' | 'assistant'\n content: string | ContentBlock[]\n model?: string\n stop_reason?: string | null\n /** Per-API-call token usage when the message carries it (assistant messages do).\n * Enables mid-run token accounting; result-message usage stays authoritative. */\n usage?: {\n input_tokens?: number\n output_tokens?: number\n cache_creation_input_tokens?: number\n cache_read_input_tokens?: number\n }\n}\n\n// ---------------------------------------------------------------------------\n// Permission requests\n// ---------------------------------------------------------------------------\n\n/** A tool call promoted into a pending approval by the runner's canUseTool hook\n * (Claude), or an engine ask-channel request surfaced by its runner (codex).\n * The two do not share a tense: Claude asks BEFORE a tool runs; codex's command\n * approval is usually an escalation AFTER its sandbox already ran and refused\n * the command (\"command failed; retry without sandbox?\"). The runner authors\n * `title`/`description`/`decisionReason` to say which — clients should render\n * those fields rather than composing their own \"X wants to run Y\" sentence. */\nexport type PermissionRequest = {\n /** Server-assigned id; used by the `permission_decision` command. */\n id: string\n toolName: string\n input: Record<string, unknown>\n toolUseId: string\n /** Full prompt sentence from the SDK, e.g. \"Claude wants to read foo.txt\". */\n title?: string\n /** Short noun phrase for the tool action, e.g. \"Read file\". */\n displayName?: string\n /** Human-readable subtitle, e.g. \"Claude will have read access to ~/x\". */\n description?: string\n /** Why this permission request was triggered. */\n decisionReason?: string\n /** If raised from within a subagent, that subagent's id. */\n agentId?: string\n /** Epoch ms after which the server resolves it via its timeout policy. */\n expiresAt?: number\n}\n\nexport type PermissionDecisionSource = 'client' | 'timeout' | 'policy'\n\n// ---------------------------------------------------------------------------\n// User questions (the AskUserQuestion tool)\n// ---------------------------------------------------------------------------\n\n/** One choice of an AskUserQuestion question (SDK tool-input mirror). */\nexport type UserQuestionOption = {\n label: string\n description?: string\n /** Optional preview content (markdown unless the session configures html)\n * rendered when the option is focused. */\n preview?: string\n}\n\n/** One question from the AskUserQuestion tool's input. By the tool's convention the\n * first option is the model's recommended choice. */\nexport type UserQuestion = {\n question: string\n /** Short chip/tag label (max ~12 chars), e.g. \"Auth method\". */\n header: string\n options: UserQuestionOption[]\n multiSelect?: boolean\n}\n\n/** How a session treats the AskUserQuestion tool:\n * - 'ask' (default) — a pending permission like any other: interactive UIs render the\n * question form; job webhooks carry the full request so a remote controller can\n * answer over REST (POST /sessions/:id/permissions/:requestId).\n * - 'auto' — resolved immediately with each question's first (recommended) option.\n * - 'deny' — the tool is refused with guidance to decide autonomously (unattended runs).\n * Answers ride a permission allow as `updatedInput.answers`: question text → chosen\n * option label(s), multi-select labels comma-joined — the shape the CLI's own UI uses. */\nexport type QuestionBehavior = 'ask' | 'auto' | 'deny'\n\n// ---------------------------------------------------------------------------\n// Session capabilities (models / slash commands the CLI reports)\n// ---------------------------------------------------------------------------\n\n/** A model the session can switch to (SDK ModelInfo mirror; fields it may grow stay unknown). */\nexport type ModelOption = {\n /** Model id for createSession.model / set_model. */\n value: string\n /** Wire model id this row resolves to ('sonnet' → 'claude-sonnet-5'). What a\n * session actually reports as its model is the resolved form, so this is how a\n * client matches the running model back to the row that names it. */\n resolvedModel?: string\n displayName: string\n description?: string\n /** Whether this belongs in a picker's main list rather than behind a \"more\n * models\" step: the newest model of each family. Derived server-side — the CLI\n * reports one flat list — so that every client groups it the same way. */\n primary?: boolean\n /** Reasoning efforts this model supports at create time (codex catalogs carry\n * them, from the binary's own per-model list). Absent = the engine's default\n * set ({@link EngineCapabilities.reasoningEfforts}) applies. Open strings —\n * the binary's vocabulary outruns its SDK's union. */\n reasoningEfforts?: readonly string[]\n}\n\n/** A slash command the CLI accepts as user-message text (SDK SlashCommand mirror). */\nexport type SlashCommandInfo = {\n /** Command name without the leading slash. */\n name: string\n description?: string\n /** Hint for arguments, e.g. \"<file>\". */\n argumentHint?: string\n /** Alternate names resolving to this command. */\n aliases?: string[]\n}\n\n// ---------------------------------------------------------------------------\n// Usage telemetry (context window + subscription rate limits)\n// ---------------------------------------------------------------------------\n\n/** One category row from the CLI's context-usage breakdown (system prompt, tools, ...). */\nexport type ContextUsageCategory = {\n name: string\n tokens: number\n /** Color the CLI assigns the category. Often a CLI theme token name ('inactive',\n * 'promptBorder', ...), not a CSS color — validate before styling with it. */\n color: string\n}\n\n/** Context-window usage snapshot (SDK getContextUsage mirror), polled after each turn. */\nexport type ContextUsage = {\n categories: ContextUsageCategory[]\n totalTokens: number\n maxTokens: number\n /** Used share of the window, 0–100. */\n percentage: number\n /** Model the window sizing applies to. */\n model?: string\n}\n\n/**\n * One rate-limit window snapshot (SDK SDKRateLimitInfo mirror). Emitted only for\n * claude.ai subscription sessions — API-key sessions may never produce one, so\n * clients must render nothing (not 0%) until data arrives.\n */\nexport type RateLimitInfo = {\n /** 'allowed' | 'allowed_warning' | 'rejected' — kept as string, the SDK union may grow. */\n status: string\n /** Which window: 'five_hour' (session), 'seven_day' (weekly), 'seven_day_opus',\n * 'seven_day_sonnet', 'overage', ... — kept as string, the SDK union may grow. */\n rateLimitType?: string\n /** Used share of the window, 0–100. The CLI omits it on some updates — treat\n * absent as unknown, not 0. */\n utilization?: number\n /** Epoch **seconds** when the window resets (render countdowns client-side). */\n resetsAt?: number\n isUsingOverage?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Tool execution (bridged, deferred, and remote)\n// ---------------------------------------------------------------------------\n\n/**\n * Lifecycle of one tool execution, correlated by `executionId` end to end.\n *\n * - `pending` — dispatched, result not in yet (bridged to a client, or queued).\n * - `deferred` — parked beyond this turn/process; may outlive the session's\n * liveness and be applied on rehydration.\n * - `settled` / `failed` — terminal. Results are applied idempotently by id, so\n * a duplicate delivery is a no-op rather than a second application.\n */\nexport type ToolExecutionStatus = 'pending' | 'deferred' | 'settled' | 'failed'\n\n/** Where a tool execution ran (or is running). Advisory: for display and routing. */\nexport type ToolExecutionBackend = 'server' | 'browser' | 'managed' | 'remote'\n\n/** Result payload of a tool execution, by value — never a live host reference. */\nexport type ToolExecutionOutput =\n | { type: 'text'; value: string }\n | { type: 'json'; value: unknown }\n\n// ---------------------------------------------------------------------------\n// Session events (server -> client)\n// ---------------------------------------------------------------------------\n\nexport type SessionEventBody =\n /** SDK init handshake: what this session actually is. */\n | {\n type: 'system_init'\n sdkSessionId: string\n model: string\n cwd: string\n /** Where the session's Anthropic auth came from: 'oauth' means a claude.ai\n * subscription login; other values ('user' | 'project' | 'org' | 'temporary')\n * are API-key provenance. Kept as string — the SDK union may grow. */\n apiKeySource: string\n tools: string[]\n skills: string[]\n slashCommands: string[]\n permissionMode: PermissionMode\n claudeCodeVersion: string\n mcpServers: Array<{ name: string; status: string }>\n }\n | { type: 'status_changed'; status: SessionStatus; detail?: string }\n /** Models and slash commands available to this session; fetched from the CLI after\n * init. Late attachers get it via replay like any other event. */\n | {\n type: 'capabilities'\n models: ModelOption[]\n commands: SlashCommandInfo[]\n /** Wire id the session's *default* resolves to, from the CLI's own `default`\n * row. Answers \"what will this session answer as\" before it has answered\n * anything — `system_init` carries the model, but a promptless session gets\n * no `system_init` until its first message. */\n defaultModel?: string\n }\n /** The session's model changed via `set_model`. `model` undefined = back to default. */\n | { type: 'model_changed'; model?: string }\n /** The session's permission mode changed via `set_permission_mode`. */\n | { type: 'permission_mode_changed'; mode: PermissionMode }\n /** Context-window usage snapshot; the runner polls it after each turn. */\n | { type: 'context_usage'; usage: ContextUsage }\n /** Subscription rate-limit update for one window (see {@link RateLimitInfo}). */\n | { type: 'rate_limit'; info: RateLimitInfo }\n /** Which claude.ai plan the rate-limit windows belong to: 'pro' | 'max' | 'team' |\n * 'enterprise' — kept as string, the set may grow. Emitted from the same poll as\n * `rate_limit`, once per change, and never for an API-key session (which has no\n * plan). It names the windows; it does not size them — the tier suffix a\n * subscription page shows (\"Max 20x\") is not in the data. */\n | { type: 'plan_info'; subscriptionType: string }\n | {\n type: 'assistant_message'\n message: ApiMessage\n /** Set when the message was produced inside a subagent (Task tool). */\n parentToolUseId: string | null\n /** True when backfilled from a resumed session's history. */\n replay?: boolean\n uuid: string\n }\n | {\n type: 'user_message'\n message: ApiMessage\n parentToolUseId: string | null\n /** True when replayed from a resumed session's history. */\n replay?: boolean\n /** True for tool results and other synthetic user-role messages. */\n synthetic?: boolean\n /** Files sent with this message, by reference (see {@link MessageAttachment}).\n * `message.content` carries the typed text only — the attachment bytes went\n * to the model, not into this log. */\n attachments?: MessageAttachment[]\n uuid?: string\n }\n /** Raw Anthropic streaming event (message_start/content_block_delta/...); emitted only\n * when the session was created with `includePartialMessages`. */\n | {\n type: 'stream_delta'\n event: { type: string; [key: string]: unknown }\n parentToolUseId: string | null\n uuid: string\n }\n | {\n type: 'turn_result'\n subtype:\n | 'success'\n | 'error_during_execution'\n | 'error_max_turns'\n | 'error_max_budget_usd'\n | 'error_max_structured_output_retries'\n isError: boolean\n durationMs: number\n numTurns: number\n totalCostUsd: number\n /** Final text of the turn (success only). */\n result?: string\n errors?: string[]\n usage?: unknown\n }\n | { type: 'permission_requested'; request: PermissionRequest }\n | {\n type: 'permission_resolved'\n requestId: string\n behavior: 'allow' | 'deny'\n resolvedBy: PermissionDecisionSource\n /** Denial message, when denied. */\n message?: string\n }\n /** A tool execution was dispatched to a backend. For bridged executions this\n * precedes the `tool_call_request` frame; for deferred ones it is the record\n * that survives a teardown. */\n | {\n type: 'execution_dispatched'\n executionId: string\n toolName: string\n backend: ToolExecutionBackend\n /** True when the execution may outlive this turn or process. */\n deferred?: boolean\n /** Epoch ms after which the server applies its timeout policy. */\n expiresAt?: number\n }\n /** A dispatched execution produced a result. Applied idempotently by `executionId`. */\n | {\n type: 'execution_result'\n executionId: string\n output: ToolExecutionOutput\n /** Guest/agent-visible logs, if the backend captured any. */\n logs?: string[]\n durationMs?: number\n }\n /** A dispatched execution failed, timed out, or was orphaned. The failure is fed\n * back into the loop as tool output so the agent can adapt — it is not a session error. */\n | {\n type: 'execution_failed'\n executionId: string\n /** Machine-readable cause: 'timeout' | 'oom' | 'exception' | 'orphaned' | backend-specific. */\n reason: string\n error: string\n logs?: string[]\n durationMs?: number\n }\n /** The agent handed over a file from its session scratch filesystem (the\n * `deliver_file` tool). Download it via `GET {basePath}/sessions/:id/files/<path>`\n * for as long as the session lives (the VFS is in-memory). */\n | { type: 'file_delivered'; path: string; bytes: number; description?: string }\n /** Any SDKMessage this protocol version doesn't model first-class (task progress,\n * compaction boundaries, auth status, ...). Payload is the raw SDK message. */\n | { type: 'sdk_event'; payload: { type: string; [key: string]: unknown } }\n | { type: 'session_error'; message: string }\n | { type: 'session_closed'; reason: 'client' | 'server' | 'error' }\n\nexport type SessionEvent = SessionEventBody & {\n /** Monotonic per-session sequence number, starting at 1. */\n seq: number\n /** Epoch ms when the server emitted the event. */\n ts: number\n}\n\n// ---------------------------------------------------------------------------\n// Commands (client -> server)\n// ---------------------------------------------------------------------------\n\nexport type SessionCommand =\n | {\n type: 'user_message'\n text: string\n /** Ids from `POST {basePath}/sessions/:id/attachments`, in the order they\n * should reach the model. Unknown ids fail the command rather than sending\n * a message that quietly lost its picture. */\n attachmentIds?: string[]\n }\n | {\n type: 'permission_decision'\n requestId: string\n behavior: 'allow' | 'deny'\n /** allow only: modified tool input to run instead of the original. */\n updatedInput?: Record<string, unknown>\n /** deny only: reason surfaced to the model. */\n message?: string\n /** deny only: also interrupt the running turn. */\n interrupt?: boolean\n }\n | { type: 'interrupt' }\n | { type: 'set_permission_mode'; mode: PermissionMode }\n /** Switch the model for subsequent responses; omit `model` for the default. */\n | { type: 'set_model'; model?: string }\n /**\n * Result of a tool execution the server bridged to this client (see\n * {@link ToolCallRequestFrame}). Unknown or already-settled `executionId`s are\n * ignored — delivery is idempotent, and a late result after a timeout must not\n * re-open a settled call.\n *\n * Browser-returned results are UNTRUSTED input: acceptable for the user's own\n * data, never a source for server-authoritative state.\n */\n | {\n type: 'tool_call_result'\n executionId: string\n output: ToolExecutionOutput\n logs?: string[]\n }\n /** The client could not execute a bridged call (unsupported tool, guest error,\n * tab closing). Fed back to the agent as tool output. */\n | {\n type: 'tool_call_error'\n executionId: string\n reason: string\n error: string\n logs?: string[]\n }\n | { type: 'close' }\n\n// ---------------------------------------------------------------------------\n// WebSocket frames\n// ---------------------------------------------------------------------------\n\n/** First frame the server sends after a successful attach. */\nexport type AttachedFrame = {\n type: 'attached'\n protocolVersion: number\n session: SessionInfo\n /** Events with seq > the client's `afterSeq` follow as `event` frames. */\n replayingFrom: number\n}\n\n/**\n * Ask the attached client to execute a tool call in its own sandbox (browser\n * bridge). The client answers with `tool_call_result` or `tool_call_error`\n * carrying the same `executionId`.\n *\n * Only sandbox-benefiting tools are ever bridged. Authenticated/authoritative\n * tools (MCP, secret-bearing APIs) execute server-side and never appear here.\n */\nexport type ToolCallRequestFrame = {\n type: 'tool_call_request'\n executionId: string\n toolName: string\n input: unknown\n /** Files to seed the client's scratch VFS with, path → contents. */\n vfsSeed?: Record<string, string>\n limits?: { timeoutMs?: number; memoryLimitBytes?: number }\n /** Epoch ms after which the server gives up and fails the execution. */\n expiresAt?: number\n}\n\nexport type ServerFrame =\n | AttachedFrame\n | { type: 'event'; event: SessionEvent }\n | ToolCallRequestFrame\n /** A bridged execution no longer needs an answer (turn interrupted, timed out,\n * or the session closed) — the client should abandon it. */\n | { type: 'tool_call_canceled'; executionId: string; reason: string }\n | { type: 'protocol_error'; message: string }\n\nexport type ClientFrame = SessionCommand\n\n// ---------------------------------------------------------------------------\n// Profiles (named Claude Code config directories)\n// ---------------------------------------------------------------------------\n\n/** Per-profile fallbacks filled into session/job requests that leave the field\n * unset. Defaults, not enforced caps — an explicit request value always wins. */\nexport type ProfileDefaults = {\n model?: string\n permissionMode?: PermissionMode\n}\n\n/**\n * A named Claude Code config directory sessions can run under: the session's CLI\n * process gets it as CLAUDE_CONFIG_DIR, so the profile carries that directory's\n * settings, memory, skills, and whatever credentials the SDK/CLI resolves from it.\n * Profiles are declared in server options at startup (or a 'default' one is\n * auto-created from the operator's own config dir) — the API only reads them.\n */\n/**\n * Which engine a profile runs on. A **closed union, deliberately**: both clients\n * switch exhaustively, the Swift mirror ships in lockstep, and a closed set is\n * what lets this package carry per-engine capability defaults\n * ({@link ENGINE_CAPABILITIES}) browser-safe, with no server round-trip. Adding a\n * member is a versioned protocol event.\n *\n * - `claude` (default) — Claude Code via the Agent SDK, configured by a config dir.\n * - `codex` — OpenAI Codex over the codex CLI binary's `app-server` JSON-RPC\n * surface, configured by a CODEX_HOME (auth resolved by the binary itself,\n * like claude).\n * - `provider` — a model-agnostic provider over the AI SDK, assembled by the\n * host's `createEngineRunner` hook.\n */\nexport type ProfileEngine = 'claude' | 'codex' | 'provider'\n\n/**\n * What an engine does and does not do — one axis per real difference, each field\n * answering a concrete UI or gateway question. Clients render from this record\n * instead of switching on the engine name: an absent capability means the\n * affordance is *hidden*, never a control that silently does nothing.\n *\n * Reaches clients in two places, same shape: `ProfileInfo.capabilities` (stamped\n * by the server; the create form's source) and `SessionInfo.capabilities`\n * (reported by the runner; the session surface's source). When the field is\n * absent — an older server — {@link ENGINE_CAPABILITIES} keyed by the engine\n * name is the browser-safe default.\n */\nexport type EngineCapabilities = {\n /** PermissionRequest / permission_resolved can occur; approval UI is live.\n * False: hide approval affordances entirely (and `questionBehavior` on jobs). */\n interactiveApprovals: boolean\n /** Modes this engine can honor. A stored choice outside the set is coerced to\n * {@link EngineCapabilities.defaultPermissionMode}, not submitted. */\n permissionModes: readonly PermissionMode[]\n /** Coercion target for a stored/unsupported mode choice (always ∈ permissionModes). */\n defaultPermissionMode: PermissionMode\n /** CreateSessionRequest.resume works (an engine session id continues). */\n resume: boolean\n /** Resume replays prior history into the transcript (Claude's backfill).\n * False + resume: show a \"history predates this attach\" notice instead of\n * treating an empty transcript as a bug. */\n resumeBackfill: boolean\n /** GET /sdk-sessions offers a resume picker for this engine. */\n listSessions: boolean\n /** context_usage events can occur. False: render nothing — never a 0% ring. */\n contextUsage: boolean\n /** rate_limit / plan_info events can occur. False: render nothing. */\n rateLimits: boolean\n /** GET/POST /sessions/:id/mcp works (else 501). */\n mcpStatus: boolean\n /** A session request may bring its own mcpServers. */\n sessionMcpServers: boolean\n /** capabilities events carry slash commands (composer popover). */\n slashCommands: boolean\n /** settingSources / allowDangerouslySkipPermissions-style CLI options apply. */\n settingSources: boolean\n /** maxTurns / maxBudgetUsd are honored (else the gateway 400s them). */\n budgets: boolean\n /** Attachment kinds sendMessage can deliver to the model. Filter the attach\n * menu by kind; refuse locally before the server's 415. */\n attachments: ReadonlyArray<'image' | 'pdf' | 'text'>\n /** Efforts offerable at create time; absent = not settable (hide the control).\n * Open strings — Codex's own binary already outruns its SDK's union. */\n reasoningEfforts?: readonly string[]\n /** Sessions expose a scratch VFS (GET /sessions/:id/files, deliverables panel). */\n vfs: boolean\n /** stream_delta granularity: per-token, coarse item updates (no typing\n * cursor), or none. */\n streaming: 'token' | 'item' | 'none'\n}\n\n/**\n * The static capability record of each engine — the browser-safe default for\n * `ProfileInfo.capabilities` / `SessionInfo.capabilities`, and the single place\n * the values are written down. Core's adapters *reference* this record and a\n * conformance test compares runner behaviour against it, so it cannot silently\n * diverge from the code. When both a wire copy and this default exist, the wire\n * copy wins.\n */\nexport const ENGINE_CAPABILITIES: Record<ProfileEngine, EngineCapabilities> = {\n claude: {\n interactiveApprovals: true,\n permissionModes: ['default', 'acceptEdits', 'bypassPermissions', 'plan', 'dontAsk', 'auto'],\n defaultPermissionMode: 'default',\n resume: true,\n resumeBackfill: true,\n listSessions: true,\n contextUsage: true,\n rateLimits: true,\n mcpStatus: true,\n sessionMcpServers: true,\n slashCommands: true,\n settingSources: true,\n budgets: true,\n attachments: ['image', 'pdf', 'text'],\n // The engine-wide set (SDK Options.effort); per-model narrowing rides the\n // catalog rows, and the CLI silently downgrades an effort a model lacks.\n reasoningEfforts: ['low', 'medium', 'high', 'xhigh', 'max'],\n vfs: false,\n streaming: 'token',\n },\n codex: {\n // The app-server ask channels (server→client JSON-RPC requests: command\n // escalations, file changes, permission grants, tool questions, MCP\n // elicitations) are wired to the permission surface: they arrive as\n // `permission_requested` and are answered by `permission_decision`.\n // NOTE the semantic shift a client should not paper over: codex's command\n // approval is usually an ESCALATION after the sandbox already refused the\n // command (\"command failed; retry without sandbox?\"), not a gate before\n // execution — the runner authors `title`/`decisionReason` from codex's own\n // reason sentence, so render those rather than composing \"wants to use X\".\n interactiveApprovals: true,\n // 'default' = read-only sandbox + ask (a blocked action becomes a real\n // question instead of a silent refusal); acceptEdits = workspace-write +\n // ask (in-workspace writes sail through, escalations still ask); bypass =\n // full access, asking nothing. plan/dontAsk/auto name CLI workflows codex\n // cannot deliver.\n permissionModes: ['default', 'acceptEdits', 'bypassPermissions'],\n defaultPermissionMode: 'default',\n resume: true,\n // A resume replays the thread's prior turns from `thread/resume`'s\n // `thread.turns` (topped up via `thread/read {includeTurns: true}` when the\n // resume page is partial) as `replay: true` events — same contract as the\n // Claude engine's backfill.\n resumeBackfill: true,\n // `GET /sdk-sessions?profile=<codex profile>` lists CODEX_HOME's threads\n // over a short-lived `thread/list` connection; no live session required.\n listSessions: true,\n // From `thread/tokenUsage/updated.last` against `modelContextWindow`, after\n // each turn. Its `categories` is always empty — codex publishes no\n // breakdown — so a client must not draw an empty breakdown section.\n contextUsage: true,\n // From `account/rateLimits/updated`, which app-server pushes during a turn\n // (no poll needed). Windows are positional there and named here by their\n // measured duration — see `docs/GOTCHAS.md` §Codex.\n rateLimits: true,\n mcpStatus: false,\n // MCP belongs to CODEX_HOME's config.toml; a session request cannot add servers.\n sessionMcpServers: false,\n slashCommands: false,\n settingSources: false,\n budgets: false,\n // Images travel as localImage host paths, text is inlined into the prompt\n // envelope; pdf has no representation and 415s at upload.\n attachments: ['image', 'text'],\n // The engine-wide floor; per-model supersets (max, ultra) ride\n // ModelOption.reasoningEfforts from the catalog.\n reasoningEfforts: ['minimal', 'low', 'medium', 'high', 'xhigh'],\n vfs: false,\n // item/agentMessage/delta and the reasoning deltas arrive token-by-token.\n streaming: 'token',\n },\n provider: {\n interactiveApprovals: false,\n permissionModes: ['default', 'bypassPermissions', 'dontAsk'],\n defaultPermissionMode: 'default',\n resume: false,\n resumeBackfill: false,\n listSessions: false,\n contextUsage: false,\n rateLimits: false,\n mcpStatus: false,\n sessionMcpServers: false,\n slashCommands: false,\n settingSources: false,\n budgets: false,\n attachments: ['image', 'pdf', 'text'],\n vfs: true,\n streaming: 'token',\n },\n}\n\n/**\n * Permission modes the model-agnostic provider engine understands.\n * @deprecated Read `ENGINE_CAPABILITIES.provider.permissionModes` (this is an\n * alias of it, kept for protocol-5 consumers).\n */\nexport const PROVIDER_PERMISSION_MODES: readonly PermissionMode[] =\n ENGINE_CAPABILITIES.provider.permissionModes\n\n/**\n * Whether a profile's engine can run a permission mode. The single source of\n * truth for the restriction: create forms filter what they offer with it, the\n * gateway rejects with it. An absent `engine` means 'claude' (every mode).\n */\nexport function supportsPermissionMode(\n engine: ProfileEngine | undefined,\n mode: PermissionMode,\n): boolean {\n return ENGINE_CAPABILITIES[engine ?? 'claude'].permissionModes.includes(mode)\n}\n\n/**\n * A model provider a `provider` profile can run on. Credentials are ALWAYS\n * resolved from the operator's environment — never carried on the wire, never\n * stored here. `apiKeyEnv` names the variable to read, it does not hold a key.\n */\nexport type ProviderConfig = {\n /** Provider adapter to use, e.g. 'anthropic' | 'openai' | 'moonshotai' |\n * 'openai-compatible'. Kept as a string: the set is host-extensible. */\n id: string\n /** Default model id, e.g. 'kimi-k3'. Overridable per session. */\n model?: string\n /** Model ids this profile offers, for the dashboard's picker. Operator-declared\n * rather than discovered: provider engines have no equivalent of the CLI's\n * `supportedModels()`, and only the operator knows which ids their endpoint and\n * key actually serve. Unset → the picker offers {@link ProviderConfig.model} alone. */\n models?: string[]\n /** Base URL for OpenAI-compatible providers. */\n baseUrl?: string\n /** Environment variable the operator put the key in. Never the key itself. */\n apiKeyEnv?: string\n}\n\n/**\n * A grantable capability of the model-agnostic engine, named after the tool it\n * yields. The always-present tools (`fs_*`, `eval_script`) are not listed: they\n * are the engine's scratch filesystem and sandbox, not a grant.\n */\nexport type SessionCapability = 'web_search' | 'download' | 'web_fetch' | 'deliver_file'\n\n/**\n * What sessions under a `provider` profile get, declared by the operator. Meaning-\n * less for `claude` profiles, whose equivalents live in the config directory.\n *\n * MCP servers are named, never configured, here: a server's transport config can\n * carry credentials in its headers, and this type is served by `GET /profiles`.\n * The names refer to servers the host connected in `createEngineRunner`, which is\n * where the configs (and the credentials) stay.\n */\nexport type ProfileSessionDefaults = {\n /** Capabilities granted to sessions under this profile. Absent = no\n * declaration, so a session gets whatever backends the host wired. A session\n * request may narrow this set, never widen it. */\n capabilities?: SessionCapability[]\n /** MCP servers, by name, whose tools sessions under this profile may use.\n * Absent = no declaration (every server the host connected). */\n mcpServers?: string[]\n /** Prepended to the session's system prompt. */\n instructions?: string\n}\n\nexport type ProfileInfo = {\n /** Unique name, used as {@link CreateSessionRequest.profile}. */\n name: string\n /** Engine this profile runs on. Defaults to 'claude' when absent, so profiles\n * written before provider support keep working unchanged. */\n engine?: ProfileEngine\n /** Absolute path set as CLAUDE_CONFIG_DIR for the session's CLI process.\n * Required for 'claude' profiles; meaningless for the other engines. */\n configDir?: string\n /** Codex profiles: absolute path set as CODEX_HOME for the session's codex\n * process (auth, config.toml, thread storage) — the `configDir` analogue,\n * request-writable like it. Unset = the binary's own `~/.codex`. */\n codexHome?: string\n /** Provider wiring for 'provider' profiles. */\n provider?: ProviderConfig\n description?: string\n defaults?: ProfileDefaults\n /** Provider-engine session grants (capabilities, MCP servers, instructions). */\n session?: ProfileSessionDefaults\n /** Response-only: the engine's model catalog, shipped with the release and\n * served from the first request (no process spawned, no warm-up session).\n * For provider profiles the ids come from `provider.models` instead. Never\n * contains a 'default' sentinel row — forms add their own \"Profile default\"\n * row mapping to an unset model. Ignored on the way in. */\n models?: ModelOption[]\n /** Response-only: what this profile's default model resolves to. For claude\n * profiles this is the operator's CLI config — unknowable statically — so it\n * is absent until a session on this profile reports it. */\n defaultModel?: string\n /** Response-only: the engine's capability record (see {@link EngineCapabilities}).\n * Absent = use ENGINE_CAPABILITIES[engine]. Ignored on the way in. */\n capabilities?: EngineCapabilities\n /** Response-only: whether the profile's credentials probe as usable right now.\n * Absent = unknown/unchecked — treat as available. **Display-only**: create\n * against an unavailable profile still proceeds and fails with the engine's\n * own error (the probe can be stale in both directions). */\n available?: boolean\n /** Response-only: one operator-actionable line, present only when\n * `available === false`. */\n unavailableReason?: string\n /** Response-only, computed by the server: this profile came from the profile\n * store and can be edited or deleted through the API. Profiles declared in\n * server options are absent/false — they are code. Ignored on the way in. */\n managed?: boolean\n}\n\n/**\n * Curated, read-only snapshot of what a profile's config directory contains —\n * the parts relevant to running worker sessions. Values that could carry secrets\n * (env var values) never leave the server; only names are listed.\n */\nexport type ProfileConfigSnapshot = {\n /** From the config dir's settings.json; absent when missing or unparseable. */\n settings?: {\n /** Configured default model. */\n model?: string\n /** permissions.defaultMode — the CLI's default permission mode. */\n defaultPermissionMode?: string\n /** Rule counts from permissions.allow / ask / deny. */\n permissionRules?: { allow: number; ask: number; deny: number }\n /** Env var NAMES declared in settings.json env (values never included). */\n envKeys?: string[]\n /** Hook event names with at least one hook configured. */\n hooks?: string[]\n }\n /** CLAUDE.md (user memory) present in the config dir. */\n hasUserMemory: boolean\n /** Skill names (skills/<name>/). */\n skills: string[]\n /** Agent names (agents/<name>.md). */\n agents: string[]\n /** Custom slash-command names (commands/<name>.md). */\n commands: string[]\n}\n\n// ---------------------------------------------------------------------------\n// REST shapes\n// ---------------------------------------------------------------------------\n\nexport type McpServerConfigWire =\n | { type?: 'stdio'; command: string; args?: string[]; env?: Record<string, string> }\n | { type: 'http'; url: string; headers?: Record<string, string> }\n | { type: 'sse'; url: string; headers?: Record<string, string> }\n\n/** One tool an MCP server exposes, as the session's engine reports it.\n * Parameters are deliberately absent: the CLI's status payload names and\n * describes each tool but does not carry its input schema. */\nexport type McpServerToolInfo = {\n name: string\n description?: string\n annotations?: { readOnly?: boolean; destructive?: boolean; openWorld?: boolean }\n}\n\n/**\n * Live status of one MCP server on a session — what `GET\n * {basePath}/sessions/:id/mcp` answers with, and what the `/mcp` screens render.\n *\n * The connection *identity* is here (transport, command, url, scope) but never\n * its secrets: the engine's config carries `env` for stdio servers and `headers`\n * for HTTP/SSE ones, and both are dropped on the way out. A client that can read\n * this is not thereby entitled to the tokens the operator configured.\n */\nexport type McpServerStatusInfo = {\n name: string\n /** 'connected' | 'failed' | 'needs-auth' | 'pending' | 'disabled' — kept open,\n * the engine's set may grow. */\n status: string\n /** Where the server was configured: 'project' | 'user' | 'local' | 'dynamic' | … */\n scope?: string\n /** Present when `status` is 'failed'. */\n error?: string\n /** Name and version the server announced on connect. */\n serverInfo?: { name: string; version: string }\n transport?: 'stdio' | 'http' | 'sse' | 'sdk'\n /** stdio only. */\n command?: string\n /** stdio only. Secrets do occasionally ride argv; the operator's own client\n * shows them, and hiding them here would only mislead. `env` is not exposed. */\n args?: string[]\n /** http/sse only. */\n url?: string\n /** Present when connected. */\n tools?: McpServerToolInfo[]\n}\n\nexport type McpServersResponse = { servers: McpServerStatusInfo[] }\n\n/** `POST {basePath}/sessions/:id/mcp/:name` — answers with the refreshed status. */\nexport type McpServerActionRequest = { action: 'reconnect' | 'enable' | 'disable' }\n\n/** `POST {basePath}/sessions/:id/attachments?name=<name>` — the body is the raw\n * file, the `content-type` header its media type. Answers with the reference to\n * name on the next `user_message`. */\nexport type UploadAttachmentResponse = { attachment: MessageAttachment }\n\nexport type CreateSessionRequest = {\n /** Directory the session is rooted at. Required: `cwd` is per-query in the SDK\n * and the server re-pins it on every call. */\n cwd: string\n /** Profile (named Claude Code config dir) to run under. Required when the server\n * declares more than one profile; implicit when exactly one exists. */\n profile?: string\n /** Optional initial prompt (may be a skill invocation like \"/verify-content 123\"). */\n prompt?: string\n permissionMode?: PermissionMode\n /** Pre-authorize 'bypassPermissions' (the CLI's --dangerously-skip-permissions\n * capability) so the mode can be switched on mid-session. Without it the CLI\n * rejects `set_permission_mode: 'bypassPermissions'` on a running session.\n * Implied when `permissionMode` is already 'bypassPermissions'. */\n allowDangerouslySkipPermissions?: boolean\n allowedTools?: string[]\n disallowedTools?: string[]\n mcpServers?: Record<string, McpServerConfigWire>\n /** Which filesystem settings the session loads. Include 'project' to pick up the\n * target repo's skills and CLAUDE.md (\"close-to-real\" fidelity). */\n settingSources?: Array<'user' | 'project' | 'local'>\n model?: string\n maxTurns?: number\n maxBudgetUsd?: number\n /** Resume an existing SDK session by id. */\n resume?: string\n /** With `resume`: fork to a new session id instead of continuing. */\n forkSession?: boolean\n /** Reasoning effort for the session's model (codex engine). Open string —\n * offerable values come from the profile's catalog/capability record. The\n * gateway 400s it when the engine's record declares no `reasoningEfforts`. */\n reasoningEffort?: string\n /** Emit `stream_delta` events for token-by-token rendering. Default true. */\n includePartialMessages?: boolean\n /** Per-session override of the server's permission-request timeout (ms). */\n approvalTimeoutMs?: number\n /** AskUserQuestion handling (see {@link QuestionBehavior}). Default 'ask'. */\n questionBehavior?: QuestionBehavior\n /** Provider engine only: run with fewer capabilities than the profile grants\n * (see {@link ProfileSessionDefaults.capabilities}). Narrowing only — naming a\n * capability the profile does not grant is a 400, not a silent upgrade. */\n capabilities?: SessionCapability[]\n /** Free-form metadata echoed back on SessionInfo (host app bookkeeping). */\n meta?: Record<string, unknown>\n}\n\nexport type SessionInfo = {\n /** Server-assigned id (stable across SDK session forks/resumes). */\n id: string\n /** Underlying Agent SDK session id, once known; use for `resume`. */\n sdkSessionId?: string\n status: SessionStatus\n cwd: string\n /** Profile the session runs under (resolved name, present even when implicit). */\n profile?: string\n /** Engine actually running this session, reported by the runner itself. Lets a\n * session surface gate CLI-only affordances (permission modes, context usage,\n * rate limits) without looking the profile back up. Absent = 'claude'. */\n engine?: ProfileEngine\n /** The engine's capability record, reported by the runner like `engine`. The\n * attach snapshot is the session-level source (no event carries it). Absent =\n * ENGINE_CAPABILITIES[engine]. */\n capabilities?: EngineCapabilities\n model?: string\n permissionMode?: PermissionMode\n /** Whether this session may be switched into `bypassPermissions`. The CLI only\n * allows it when the process was spawned for it, so it is decided at creation\n * and never changes: a session that did not ask for bypass up front cannot\n * gain it later. Lets a picker disable the mode instead of offering a switch\n * the engine will refuse. Absent = unknown (an older server). */\n canBypassPermissions?: boolean\n /** See the `system_init` event; 'oauth' = claude.ai subscription credentials. */\n apiKeySource?: string\n createdAt: number\n /** Highest event seq emitted so far; attach with `afterSeq` to catch up. */\n lastSeq: number\n pendingPermissionCount: number\n meta?: Record<string, unknown>\n /** Display title: `meta.title` if the host set one, else derived (e.g. first prompt). */\n title?: string\n /** Cumulative cost across all turns so far (sum of turn_result totals). */\n totalCostUsd?: number\n /** Cumulative turn count across the session. */\n numTurns?: number\n /** Epoch ms of the most recent emitted event. */\n lastActivityAt?: number\n}\n\n/**\n * A session in an engine's on-disk store (independent of this server's registry):\n * the Agent SDK's session files, or a codex profile's CODEX_HOME threads. Listed\n * so hosts can offer \"resume\" across server restarts: feed `sessionId` to\n * CreateSessionRequest.resume — under a profile of the SAME engine, since the id\n * only means something to the store it came from. `GET {basePath}/sdk-sessions`\n * takes an optional `profile` query parameter naming whose store to list; absent,\n * the profile is resolved implicitly when the server declares exactly one, else\n * the Claude engine's store is listed (the pre-engine-aware behavior). Mirrors\n * the SDK's SDKSessionInfo shape, kept browser-safe.\n */\nexport type SdkSessionSummary = {\n sessionId: string\n /** Custom title, auto summary, or first prompt — whichever the SDK has. */\n summary: string\n /** Epoch ms of last modification. */\n lastModified: number\n createdAt?: number\n customTitle?: string\n firstPrompt?: string\n gitBranch?: string\n cwd?: string\n}\n\n/** One deliverable in the session's scratch filesystem (see the `file_delivered` event). */\nexport type SessionFileInfo = { path: string; bytes: number }\n/** `GET {basePath}/sessions/:id/files` — every file currently in the session's VFS.\n * `GET {basePath}/sessions/:id/files/<path>` downloads one (attachment disposition).\n * 404 when the session's engine exposes no VFS (Claude-engine sessions). */\nexport type ListSessionFilesResponse = { files: SessionFileInfo[] }\nexport type ListSessionsResponse = { sessions: SessionInfo[] }\nexport type CreateSessionResponse = { session: SessionInfo }\nexport type GetSessionResponse = { session: SessionInfo }\n\n/** Body of `POST {basePath}/sessions/:id/permissions/:requestId` — the REST counterpart\n * of the WS `permission_decision` command, for remote controllers without a socket\n * (e.g. answering a job's AskUserQuestion from a webhook consumer). 404 = the request\n * is unknown, already resolved, or expired. */\nexport type ResolvePermissionRequest =\n | { behavior: 'allow'; updatedInput?: Record<string, unknown> }\n | { behavior: 'deny'; message?: string; interrupt?: boolean }\nexport type ResolvePermissionResponse = { resolved: true }\n\n/**\n * Body of `POST {basePath}/executions/:executionId/result` — the way a deferred\n * executor (a remote worker, a batch job, a human) delivers the outcome of an\n * execution the session parked on. The session is rehydrated if its runner was\n * torn down, and the result is folded back into the agent loop; a `failed` result\n * is ordinary tool output the agent adapts to, not a session error.\n *\n * Applied **idempotently by `executionId`**: a duplicate or late delivery (one\n * racing the execution watchdog) answers 200 with `applied: false` rather than\n * erroring or applying twice. 404 means no session is parked on that id.\n */\nexport type SubmitExecutionResultRequest =\n | { status: 'ok'; output: ToolExecutionOutput; logs?: string[] }\n | { status: 'failed'; reason: string; error: string; logs?: string[] }\nexport type SubmitExecutionResultResponse = {\n /** False when the id was already settled — the delivery was a no-op. */\n applied: boolean\n /** Session the execution belonged to. */\n sessionId: string\n}\n\nexport type ListSdkSessionsResponse = { sdkSessions: SdkSessionSummary[] }\n/** `GET {basePath}/profiles` — filtered to the profiles the caller may use. */\nexport type ListProfilesResponse = {\n profiles: ProfileInfo[]\n /** Whether this caller may create profiles here — true only when the server has\n * a profile store AND the principal carries `canManageProfiles`. Lets a UI hide\n * controls that would always be refused. */\n canManage?: boolean\n}\n\n/**\n * `POST {basePath}/profiles` — create a managed profile. Available only when the\n * server was given a profile store, and only to a principal with\n * `canManageProfiles`. Profiles declared in server options are code, not data:\n * they cannot be created, edited, or deleted through these routes.\n */\nexport type CreateProfileRequest = ProfileInfo\n\n/** `PATCH {basePath}/profiles/:name` — merge into a managed profile. The name is\n * the route, not the body; pass `null` to clear an optional field. */\nexport type UpdateProfileRequest = Omit<Partial<ProfileInfo>, 'name'>\n\n// ---------------------------------------------------------------------------\n// Host filesystem (`{basePath}/fs/*`)\n// ---------------------------------------------------------------------------\n\n/**\n * The **host's real project tree**, not a session's in-memory VFS — the two are\n * unrelated despite both being \"files\". {@link SessionFileInfo} is a deliverable\n * the agent produced inside a session; these routes read and write the operator's\n * actual disk.\n *\n * That makes them **operator-privileged**: they are authorized by the server's auth\n * key alone and deliberately sit outside the agent permission flow, because the\n * caller *is* the operator, not the model. A client holding the key can already\n * start a session with any allowed cwd; browsing that same tree grants it nothing\n * new. Writing does, which is why writes are separately enabled server-side.\n *\n * The whole surface is opt-in and root-scoped: with no roots configured every route\n * below 404s. There is no \"unset means anything\" default here — a phone on a tailnet\n * must never be one request away from `~/.ssh`.\n */\nexport type HostFileRoot = {\n /** Absolute, canonical (symlinks resolved) path of the root. */\n path: string\n /** Last path segment, for display — roots are not named by the operator. */\n name: string\n}\n\n/** `GET {basePath}/fs/roots` — where a client may start browsing. Empty `roots`\n * never happens: the routes are absent entirely when none are configured. */\nexport type ListHostRootsResponse = {\n roots: HostFileRoot[]\n /** Whether `PUT /fs/write` is enabled here; lets a UI hide an editor it can't save from. */\n canWrite: boolean\n}\n\n/** One entry in a host directory listing. Classified with `lstat` semantics, so a\n * `symlink` is reported as itself and never silently resolved — following it is the\n * *next* request's problem, and that request is refused if it escapes the roots. */\nexport type HostDirEntry = {\n name: string\n /** Absolute path, ready to pass back as `?path=`. */\n path: string\n type: 'file' | 'dir' | 'symlink' | 'other'\n /** Regular files only. */\n bytes?: number\n /** Epoch ms mtime. */\n modifiedAt?: number\n}\n\n/** `GET {basePath}/fs/list?path=<abs>` — one directory, not recursive. */\nexport type ListHostDirResponse = {\n /** Canonical path actually listed (the request's path after symlink resolution). */\n path: string\n /** Directories first, then files, each alphabetical. */\n entries: HostDirEntry[]\n /** Set when the directory held more entries than the server will return. */\n truncated?: boolean\n}\n\n/** One hit from `GET {basePath}/fs/find`. */\nexport type HostFileMatch = {\n /** Absolute path, for a follow-up read. */\n path: string\n /** Path relative to the searched directory — what a picker shows and inserts. */\n relative: string\n}\n\n/**\n * `GET {basePath}/fs/find?path=<dir>&q=<query>&limit=<n>` — recursive fuzzy file\n * search under one directory, which is what an `@file` picker needs and\n * `/fs/list` is not: listing answers \"what is in this directory\", this answers\n * \"which file in this tree did you mean\".\n *\n * Subsequence matching (`seslist` finds `SessionListView.swift`), filename hits\n * ranked above path hits, shallow files above deep ones. An empty `q` returns the\n * shallowest files. Build directories (`.git`, `node_modules`, …) are skipped, as\n * is anything behind a symlink — so every path returned is one `/fs/read` will\n * accept.\n */\nexport type FindHostFilesResponse = {\n /** Canonical directory the search ran under; `relative` paths are relative to it. */\n base: string\n matches: HostFileMatch[]\n /** More matched, or the tree was larger than the server would walk. */\n truncated: boolean\n}\n\n/** `GET {basePath}/fs/read?path=<abs>` — one file's contents. Binary files come back\n * base64; 413 rather than a truncated read when the file exceeds the server's cap. */\nexport type ReadHostFileResponse = {\n path: string\n content: string\n encoding: 'utf8' | 'base64'\n bytes: number\n /** sha256 (hex) of the bytes on disk. Pass it back as `expectedHash` to write. */\n hash: string\n modifiedAt: number\n}\n\n/**\n * `PUT {basePath}/fs/write` — replace or create one file.\n *\n * The agent is editing this same tree, so a write is **conditional, always**:\n * `expectedHash` must be the hash from the read this edit is based on, and the\n * server 409s if the file has changed since. Omitting it means \"create\" and 409s\n * if the path already exists — there is no unconditional overwrite, by design.\n * Directories are never created implicitly: writing under a missing parent is a 404.\n */\nexport type WriteHostFileRequest = {\n path: string\n content: string\n /** Default 'utf8'. */\n encoding?: 'utf8' | 'base64'\n /** Required to overwrite; omit only to create a new file. */\n expectedHash?: string\n}\n\nexport type WriteHostFileResponse = {\n path: string\n bytes: number\n /** Hash of what was just written — carry it into the next edit. */\n hash: string\n modifiedAt: number\n}\n\nexport type SaveProfileResponse = { profile: ProfileInfo }\n/** `GET {basePath}/profiles/:name` — the profile plus a fresh config snapshot. */\nexport type GetProfileResponse = { profile: ProfileInfo; config: ProfileConfigSnapshot }\nexport type ErrorResponse = { error: string }\n\n// ---------------------------------------------------------------------------\n// Session notifications (the out-of-band \"something wants you\" channel)\n// ---------------------------------------------------------------------------\n\n/**\n * The moments in an *interactive* session a person needs to hear about when they\n * are not watching it — the whole point being that a phone cannot hold a\n * WebSocket open in the background, so the server has to reach out.\n *\n * Deliberately four: this is a human-attention channel, not an event mirror. The\n * event log stays on the session WS (attach with `afterSeq` to catch up); if you\n * want every assistant message, subscribe there instead.\n */\nexport type SessionNotificationType =\n /** The agent is blocked on an approval — the one that matters most. */\n | 'permission_requested'\n /** A turn finished; the session is idle and waiting for the human. */\n | 'turn_completed'\n /** The session failed (`session_error`). */\n | 'session_error'\n /** The session ended (`session_closed`), whoever ended it. */\n | 'session_closed'\n\n/** One delivery on the session-notification channel (JSON body of a webhook POST). */\nexport type SessionNotification = {\n type: SessionNotificationType\n sessionId: string\n /** Snapshot at notification time — status, title, cwd, cost, `lastSeq`. */\n session: SessionInfo\n /** Seq of the event behind this notification; attach with `afterSeq: seq - 1` to\n * land on it. */\n seq: number\n ts: number\n /** One line fit for a notification body: the permission title, the turn's final\n * text, the error message. */\n preview?: string\n /** `permission_requested` only: the full request, so a consumer can answer it via\n * `POST {basePath}/sessions/:id/permissions/:requestId` — which is what makes an\n * Approve/Deny action on a lock-screen notification possible. */\n request?: PermissionRequest\n /** `turn_completed` only. */\n result?: { isError: boolean; durationMs: number; numTurns: number; totalCostUsd: number }\n /** `session_closed` only. */\n reason?: 'client' | 'server' | 'error'\n}\n\n/** Where session notifications are POSTed (JSON body = {@link SessionNotification}).\n * Server-wide, not per session: the point is to hear about sessions you did not\n * create yourself and are not attached to. */\nexport type SessionWebhookConfig = {\n url: string\n /** Extra headers sent with every delivery (auth tokens etc.). */\n headers?: Record<string, string>\n /** Types to deliver. Default: all of them. */\n events?: SessionNotificationType[]\n}\n\n// ---------------------------------------------------------------------------\n// Job queue (one-shot scheduled runs over the session runner)\n// ---------------------------------------------------------------------------\n\n/**\n * - `queued` — accepted, waiting for a concurrency slot (or the daily token budget)\n * - `running` — a session is executing the prompt\n * - `parked` — waiting on an external event (a deferred tool execution). Not\n * terminal and not consuming a concurrency slot; resumes to `running` when the\n * result arrives, or fails via the execution watchdog if it never does.\n * - `succeeded` / `failed` — terminal; `result` (and `error` on failure) are set\n * - `canceled` — terminal; canceled by a client before or during the run\n */\nexport type JobStatus = 'queued' | 'running' | 'parked' | 'succeeded' | 'failed' | 'canceled'\n\n/** Where job progress/completion deliveries are POSTed (JSON body = {@link JobEvent}). */\nexport type WebhookConfig = {\n url: string\n /** Extra headers sent with every delivery (auth tokens etc.). */\n headers?: Record<string, string>\n /** Delivery granularity: 'messages' also POSTs job_progress per assistant message /\n * permission request; 'completion' only job_started + job_completed. Default 'messages'. */\n progress?: 'messages' | 'completion'\n}\n\n/**\n * Schedule a one-shot run: the session executes `prompt` unattended and the job\n * completes with that run's result. `session.prompt` is the task and is required;\n * `resume`/`forkSession` are not supported for queued jobs.\n */\nexport type CreateJobRequest = {\n session: CreateSessionRequest & { prompt: string }\n webhook?: WebhookConfig\n /** Per-job token cap; the effective cap is min(this, the server's sessionTokenLimit). */\n maxTokens?: number\n /** Per-job wall-clock cap; the effective cap is min(this, the server's maxJobDurationMs). */\n maxDurationMs?: number\n /** Total run attempts: failed (not canceled) runs re-queue until this many attempts\n * have been made. Default 1 (no retries). */\n attempts?: number\n /** Delay before the first retry, doubled for each subsequent one. Default 5000. */\n retryDelayMs?: number\n /** Host bookkeeping echoed back on JobInfo. */\n meta?: Record<string, unknown>\n}\n\n/** Cumulative resource usage of a job's run. `tokens` counts input + output +\n * cache-creation + cache-read tokens across all turns. */\nexport type JobUsage = {\n tokens: number\n totalCostUsd: number\n numTurns: number\n}\n\n/** Terminal outcome of the job's run (mirrors the final turn_result). */\nexport type JobResult = {\n subtype: string\n isError: boolean\n /** Final text of the run (success only). */\n result?: string\n errors?: string[]\n durationMs: number\n}\n\nexport type JobInfo = {\n id: string\n status: JobStatus\n cwd: string\n /** Profile the run executes under (resolved name, present even when implicit). */\n profile?: string\n prompt: string\n /** Server session id once started — attach via the sessions WS to watch the run live. */\n sessionId?: string\n sdkSessionId?: string\n createdAt: number\n startedAt?: number\n finishedAt?: number\n /** 1-based run attempt this info reflects. */\n attempt?: number\n /** Total attempts configured on the request (see CreateJobRequest.attempts). */\n maxAttempts?: number\n /** For a job re-queued by retry backoff: earliest time the next attempt may start. */\n nextRunAt?: number\n /** Set while `status` is 'parked': when the run parked, and the execution it is\n * waiting on — the id to POST a result to. Cleared when it resumes. */\n parkedAt?: number\n parkedExecutionId?: string\n /** Cumulative across attempts. */\n usage: JobUsage\n result?: JobResult\n /** Failure or cancellation reason (for a queued retry: the previous attempt's error). */\n error?: string\n meta?: Record<string, unknown>\n}\n\n/** Latest mid-run activity, carried on job_progress deliveries. */\nexport type JobProgress = {\n kind: 'assistant_text' | 'tool_use' | 'permission_requested' | 'permission_resolved'\n /** Short human-readable preview (message excerpt, tool name, permission title). */\n preview?: string\n /** 'permission_requested' only: the full request (including AskUserQuestion input) so\n * webhook consumers can answer via POST /sessions/:sessionId/permissions/:requestId. */\n request?: PermissionRequest\n}\n\n/** Webhook delivery payload (also the queue's local event shape). `job_submitted` goes\n * to local observers and the queue WS only — the submitter already has the POST\n * response, so webhooks start at `job_started`. `job_retrying` marks a failed run that\n * was re-queued (`job.nextRunAt` says when); `job_completed` is always terminal. */\nexport type JobEvent =\n | { type: 'job_submitted'; job: JobInfo; ts: number }\n | { type: 'job_started'; job: JobInfo; ts: number }\n | { type: 'job_progress'; job: JobInfo; progress: JobProgress; ts: number }\n /** The run parked on a deferred execution; `executionId` says what it waits on —\n * the id to POST a result to. The *work itself* (tool name, input, VFS seed) went\n * to the executor's own dispatch hook, not over this channel: a webhook consumer\n * learns that a run is waiting, the worker learns what to do. */\n | { type: 'job_parked'; job: JobInfo; executionId: string; ts: number }\n /** A parked run resumed because its execution result arrived. */\n | { type: 'job_resumed'; job: JobInfo; executionId: string; ts: number }\n | { type: 'job_retrying'; job: JobInfo; ts: number }\n | { type: 'job_completed'; job: JobInfo; ts: number }\n\nexport type QueueStats = {\n maxConcurrency: number\n running: number\n queued: number\n /** Jobs waiting on a deferred execution. They hold no concurrency slot and\n * their wall-clock budget is not ticking. */\n parked: number\n sessionTokenLimit?: number\n dailyTokenLimit?: number\n /** Tokens consumed by queue jobs in the current UTC day. */\n dailyTokensUsed: number\n /** True when the daily budget is exhausted and queued jobs are being held. */\n paused: boolean\n}\n\n/** Frames sent on the queue WS (`{basePath}/queue/ws`). The stream is one-way\n * (server→client): every job's lifecycle as it happens, plus refreshed stats after\n * lifecycle changes. Clients send nothing; job mutations stay on REST. */\nexport type QueueServerFrame =\n | { type: 'queue_attached'; protocolVersion: number; stats: QueueStats }\n | { type: 'job_event'; event: JobEvent }\n | { type: 'queue_stats'; stats: QueueStats }\n\nexport type CreateJobResponse = { job: JobInfo }\nexport type GetJobResponse = { job: JobInfo }\nexport type ListJobsResponse = { jobs: JobInfo[] }\nexport type QueueStatsResponse = { stats: QueueStats }\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,mBAAmB;;;;;;;;;AAsmBhC,MAAa,sBAAiE;CAC5E,QAAQ;EACN,sBAAsB;EACtB,iBAAiB;GAAC;GAAW;GAAe;GAAqB;GAAQ;GAAW;GAAO;EAC3F,uBAAuB;EACvB,QAAQ;EACR,gBAAgB;EAChB,cAAc;EACd,cAAc;EACd,YAAY;EACZ,WAAW;EACX,mBAAmB;EACnB,eAAe;EACf,gBAAgB;EAChB,SAAS;EACT,aAAa;GAAC;GAAS;GAAO;GAAO;EAGrC,kBAAkB;GAAC;GAAO;GAAU;GAAQ;GAAS;GAAM;EAC3D,KAAK;EACL,WAAW;EACZ;CACD,OAAO;EAUL,sBAAsB;EAMtB,iBAAiB;GAAC;GAAW;GAAe;GAAoB;EAChE,uBAAuB;EACvB,QAAQ;EAKR,gBAAgB;EAGhB,cAAc;EAId,cAAc;EAId,YAAY;EACZ,WAAW;EAEX,mBAAmB;EACnB,eAAe;EACf,gBAAgB;EAChB,SAAS;EAGT,aAAa,CAAC,SAAS,OAAO;EAG9B,kBAAkB;GAAC;GAAW;GAAO;GAAU;GAAQ;GAAQ;EAC/D,KAAK;EAEL,WAAW;EACZ;CACD,UAAU;EACR,sBAAsB;EACtB,iBAAiB;GAAC;GAAW;GAAqB;GAAU;EAC5D,uBAAuB;EACvB,QAAQ;EACR,gBAAgB;EAChB,cAAc;EACd,cAAc;EACd,YAAY;EACZ,WAAW;EACX,mBAAmB;EACnB,eAAe;EACf,gBAAgB;EAChB,SAAS;EACT,aAAa;GAAC;GAAS;GAAO;GAAO;EACrC,KAAK;EACL,WAAW;EACZ;CACF;;;;;;AAOD,MAAa,4BACX,oBAAoB,SAAS;;;;;;AAO/B,SAAgB,uBACd,QACA,MACS;AACT,QAAO,oBAAoB,UAAU,UAAU,gBAAgB,SAAS,KAAK"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workerdeck/protocol",
3
- "version": "0.6.0",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "The WorkerDeck wire protocol: typed session events, commands, and REST shapes shared by server and clients. Dependency-free, browser-safe. This protocol is the product boundary — versioned from day one.",
6
6
  "license": "MIT",