@workerdeck/client 0.7.0 → 0.11.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
@@ -1,6 +1,10 @@
1
- import { AttachedFrame, CreateJobRequest, CreateProfileRequest, CreateSessionRequest, FindHostFilesResponse, GetProfileResponse, JobEvent, JobInfo, ListHostDirResponse, ListHostRootsResponse, ListProfilesResponse, PermissionMode, ProfileInfo, QueueStats, ReadHostFileResponse, ResolvePermissionRequest, SdkSessionSummary, SessionEvent, SessionFileInfo, SessionInfo, SubmitExecutionResultRequest, SubmitExecutionResultResponse, ToolCallRequestFrame, ToolExecutionOutput, UpdateProfileRequest, WriteHostFileRequest, WriteHostFileResponse } from "@workerdeck/protocol";
1
+ import { AttachedFrame, CreateJobRequest, CreateProfileRequest, CreateSessionRequest, FindHostFilesResponse, GetProfileResponse, JobEvent, JobInfo, ListHostDirResponse, ListHostRootsResponse, ListProfilesResponse, McpServerActionRequest, McpServerStatusInfo, MessageAttachment, PermissionMode, ProfileInfo, QueueStats, ReadHostFileResponse, ResolvePermissionRequest, SdkSessionSummary, SessionEvent, SessionFileInfo, SessionInfo, SubmitExecutionResultRequest, SubmitExecutionResultResponse, ToolCallRequestFrame, ToolExecutionOutput, UpdateProfileRequest, UpdateSessionRequest, WriteHostFileRequest, WriteHostFileResponse } from "@workerdeck/protocol";
2
2
 
3
3
  //#region src/index.d.ts
4
+ /** Whatever the ambient `fetch` accepts as a body — `Blob`/`File` in a browser,
5
+ * `Uint8Array` or a string in Node. Derived rather than named (`BodyInit` is a
6
+ * DOM-lib type, and this package compiles against both). */
7
+ type FetchBody = NonNullable<NonNullable<Parameters<typeof fetch>[1]>['body']>;
4
8
  type ClientOptions = {
5
9
  /** REST base, e.g. "http://127.0.0.1:8787/v1". The ws:// URL is derived from it. */baseUrl: string;
6
10
  /** Extra headers for REST calls (auth). Browsers can't set WS headers — use
@@ -11,6 +15,18 @@ type ClientOptions = {
11
15
  WebSocketImpl?: typeof WebSocket;
12
16
  fetchImpl?: typeof fetch;
13
17
  };
18
+ /**
19
+ * A REST call the gateway refused, carrying the status alongside the message.
20
+ *
21
+ * An `Error` subclass on purpose: every existing `e instanceof Error` check and
22
+ * every `e.message` read keeps working unchanged. The status is what lets a
23
+ * caller tell "this server doesn't have that route" (404 — stop asking) from
24
+ * "that file was too big" (413 — tell the user), which a message string can't.
25
+ */
26
+ declare class WorkerDeckError extends Error {
27
+ readonly status: number;
28
+ constructor(message: string, status: number);
29
+ }
14
30
  type AttachOptions = {
15
31
  /** Replay events with seq greater than this. Default 0 (full replay). */afterSeq?: number; /** Auto-reconnect with backoff on unexpected disconnects. Default true. */
16
32
  reconnect?: boolean;
@@ -20,6 +36,12 @@ type SessionHandleEvents = {
20
36
  event: SessionEvent;
21
37
  protocolError: string; /** WS connectivity: true on open, false on close. */
22
38
  connectionChange: boolean;
39
+ /**
40
+ * A reconnect has been scheduled, carrying how many have failed in a row (1 on
41
+ * the first). The handle retries forever, so "offline" is a judgement a UI makes
42
+ * about how long it has been failing rather than a state reported here.
43
+ */
44
+ reconnectAttempt: number;
23
45
  /**
24
46
  * The server is asking this client to execute a tool call in its own sandbox.
25
47
  * Answer with {@link SessionHandle.sendToolCallResult} or
@@ -41,7 +63,11 @@ declare class SessionHandle {
41
63
  constructor(client: WorkerDeckClient, sessionId: string, options?: AttachOptions);
42
64
  get lastSeq(): number;
43
65
  on<K extends keyof SessionHandleEvents>(kind: K, listener: Listener<SessionHandleEvents[K]>): () => void;
44
- send(text: string): void;
66
+ /** Send a message, optionally naming attachments uploaded ahead of it with
67
+ * {@link WorkerDeckClient.uploadAttachment} (ids in the order they should reach
68
+ * the model). An unknown id fails the whole command — the server will not send a
69
+ * message that quietly lost its picture. */
70
+ send(text: string, attachmentIds?: string[]): void;
45
71
  approve(requestId: string, updatedInput?: Record<string, unknown>): void;
46
72
  deny(requestId: string, message?: string, interrupt?: boolean): void;
47
73
  interrupt(): void;
@@ -55,6 +81,10 @@ declare class SessionHandle {
55
81
  sendToolCallError(executionId: string, reason: string, error: string, logs?: string[]): void;
56
82
  /** Ask the server to terminate the session (the handle disconnects too). */
57
83
  closeSession(): void;
84
+ /** Skip the reconnect backoff and try again now — what a tab returning to the
85
+ * foreground should do, rather than sitting out the remaining delay. No-op
86
+ * while connected or after {@link SessionHandle.detach}. */
87
+ reconnectNow(): void;
58
88
  /** Disconnect this handle without touching the session. */
59
89
  detach(): void;
60
90
  }
@@ -83,6 +113,9 @@ declare class WorkerDeckClient {
83
113
  createSession(request: CreateSessionRequest): Promise<SessionInfo>;
84
114
  listSessions(): Promise<SessionInfo[]>;
85
115
  getSession(id: string): Promise<SessionInfo>;
116
+ /** Rename a session (or clear the name with `null`, restoring the derived
117
+ * title). 409 when the session is parked. */
118
+ updateSession(id: string, patch: UpdateSessionRequest): Promise<SessionInfo>;
86
119
  deleteSession(id: string): Promise<SessionInfo>;
87
120
  /** List the files currently in a session's scratch filesystem (deliverables the
88
121
  * agent wrote; see the `file_delivered` event). 404s when the session's engine
@@ -90,6 +123,40 @@ declare class WorkerDeckClient {
90
123
  listSessionFiles(sessionId: string): Promise<SessionFileInfo[]>;
91
124
  /** Download one session file as text. */
92
125
  fetchSessionFile(sessionId: string, path: string): Promise<string>;
126
+ /**
127
+ * Upload one file for the session, ahead of the message that will carry it.
128
+ * The returned `id` goes to {@link SessionHandle.send}.
129
+ *
130
+ * The body is the raw bytes — no multipart — so anything `fetch` accepts as a
131
+ * body works: a `File`/`Blob` from a picker, a `Uint8Array`, a string.
132
+ */
133
+ uploadAttachment(sessionId: string, file: {
134
+ name: string;
135
+ mediaType: string;
136
+ data: FetchBody;
137
+ }): Promise<MessageAttachment>;
138
+ /** Direct URL for an uploaded attachment — an `<img src>` on a cookie-authenticated
139
+ * same-origin server. Header-authenticated clients must fetch it themselves. */
140
+ attachmentUrl(sessionId: string, attachmentId: string): string;
141
+ /**
142
+ * Direct URL for a file the session's ENGINE produced on the host — the
143
+ * `fileId` of a `file_produced` event. Same caveat as `attachmentUrl`: usable
144
+ * as an `<img src>` only where the credential is a same-origin cookie; a
145
+ * header-authenticated client (the phone) fetches it and makes its own blob.
146
+ *
147
+ * Unlike `/fs/read`, this needs no host-file roots and no raised byte cap —
148
+ * see the `file_produced` note in the protocol for why that is sound.
149
+ */
150
+ producedFileUrl(sessionId: string, fileId: string): string;
151
+ /** Fetch a produced file's bytes. For clients that cannot put a credential on
152
+ * an `<img src>`. Throws {@link WorkerDeckError} with the response status —
153
+ * a 404 means the file is gone from disk, not that the route is missing. */
154
+ readProducedFile(sessionId: string, fileId: string): Promise<Blob>;
155
+ /** The session's MCP servers and their tools, live from the engine. 501 when the
156
+ * session's engine has no MCP surface; 409 while the session is parked. */
157
+ listMcpServers(sessionId: string): Promise<McpServerStatusInfo[]>;
158
+ /** Reconnect, enable or disable one MCP server; answers with the refreshed list. */
159
+ mcpServerAction(sessionId: string, serverName: string, action: McpServerActionRequest['action']): Promise<McpServerStatusInfo[]>;
93
160
  /** Direct download URL for a session file (e.g. an <a download> href). Carries
94
161
  * no headers — on authenticated servers, use fetchSessionFile instead. */
95
162
  sessionFileUrl(sessionId: string, path: string): string;
@@ -131,12 +198,17 @@ declare class WorkerDeckClient {
131
198
  /** Delete a managed profile. Startup-declared profiles are refused (403) —
132
199
  * they live in the server's options. */
133
200
  deleteProfile(name: string): Promise<void>;
134
- /** List the Agent SDK's on-disk sessions (for resume across server restarts).
135
- * Feed a result's `sessionId` to createSession({ resume }). */
201
+ /** List an engine's on-disk sessions (for resume across server restarts).
202
+ * Feed a result's `sessionId` to createSession({ resume }) — under a profile
203
+ * of the same engine. `profile` names whose store to list (claude profiles →
204
+ * the Agent SDK store, codex profiles → CODEX_HOME threads); absent, the
205
+ * server resolves it implicitly when it declares exactly one profile, else
206
+ * lists the Claude engine's store. */
136
207
  listSdkSessions(params?: {
137
208
  dir?: string;
138
209
  limit?: number;
139
210
  offset?: number;
211
+ profile?: string;
140
212
  }): Promise<SdkSessionSummary[]>;
141
213
  /**
142
214
  * The host directories this server will let a client browse, and whether it
@@ -186,5 +258,5 @@ declare class WorkerDeckClient {
186
258
  openQueueSocket(): WebSocket;
187
259
  }
188
260
  //#endregion
189
- export { AttachOptions, ClientOptions, QueueHandle, QueueHandleEvents, SessionHandle, SessionHandleEvents, WorkerDeckClient };
261
+ export { AttachOptions, ClientOptions, FetchBody, QueueHandle, QueueHandleEvents, SessionHandle, SessionHandleEvents, WorkerDeckClient, WorkerDeckError };
190
262
  //# sourceMappingURL=index.d.mts.map
package/build/index.mjs CHANGED
@@ -1,4 +1,20 @@
1
1
  //#region src/index.ts
2
+ /**
3
+ * A REST call the gateway refused, carrying the status alongside the message.
4
+ *
5
+ * An `Error` subclass on purpose: every existing `e instanceof Error` check and
6
+ * every `e.message` read keeps working unchanged. The status is what lets a
7
+ * caller tell "this server doesn't have that route" (404 — stop asking) from
8
+ * "that file was too big" (413 — tell the user), which a message string can't.
9
+ */
10
+ var WorkerDeckError = class extends Error {
11
+ status;
12
+ constructor(message, status) {
13
+ super(message);
14
+ this.name = "WorkerDeckError";
15
+ this.status = status;
16
+ }
17
+ };
2
18
  var SessionHandle = class {
3
19
  sessionId;
4
20
  #client;
@@ -32,10 +48,15 @@ var SessionHandle = class {
32
48
  set.add(listener);
33
49
  return () => set.delete(listener);
34
50
  }
35
- send(text) {
51
+ /** Send a message, optionally naming attachments uploaded ahead of it with
52
+ * {@link WorkerDeckClient.uploadAttachment} (ids in the order they should reach
53
+ * the model). An unknown id fails the whole command — the server will not send a
54
+ * message that quietly lost its picture. */
55
+ send(text, attachmentIds) {
36
56
  this.#sendFrame({
37
57
  type: "user_message",
38
- text
58
+ text,
59
+ attachmentIds: attachmentIds?.length ? attachmentIds : void 0
39
60
  });
40
61
  }
41
62
  approve(requestId, updatedInput) {
@@ -96,6 +117,15 @@ var SessionHandle = class {
96
117
  this.#sendFrame({ type: "close" });
97
118
  this.detach();
98
119
  }
120
+ /** Skip the reconnect backoff and try again now — what a tab returning to the
121
+ * foreground should do, rather than sitting out the remaining delay. No-op
122
+ * while connected or after {@link SessionHandle.detach}. */
123
+ reconnectNow() {
124
+ if (this.#closed || this.#ws && this.#ws.readyState === 1) return;
125
+ clearTimeout(this.#connectTimer);
126
+ this.#retries = 0;
127
+ this.#connect();
128
+ }
99
129
  /** Disconnect this handle without touching the session. */
100
130
  detach() {
101
131
  this.#closed = true;
@@ -142,6 +172,7 @@ var SessionHandle = class {
142
172
  this.#emit("connectionChange", false);
143
173
  if (this.#closed || !this.#options.reconnect) return;
144
174
  const delay = Math.min(500 * 2 ** this.#retries++, 1e4);
175
+ this.#emit("reconnectAttempt", this.#retries);
145
176
  this.#connectTimer = setTimeout(() => this.#connect(), delay);
146
177
  };
147
178
  ws.onerror = () => {};
@@ -230,6 +261,11 @@ var WorkerDeckClient = class {
230
261
  async getSession(id) {
231
262
  return (await this.#call("GET", `/sessions/${encodeURIComponent(id)}`)).session;
232
263
  }
264
+ /** Rename a session (or clear the name with `null`, restoring the derived
265
+ * title). 409 when the session is parked. */
266
+ async updateSession(id, patch) {
267
+ return (await this.#call("PATCH", `/sessions/${encodeURIComponent(id)}`, patch)).session;
268
+ }
233
269
  async deleteSession(id) {
234
270
  return (await this.#call("DELETE", `/sessions/${encodeURIComponent(id)}`)).session;
235
271
  }
@@ -242,12 +278,63 @@ var WorkerDeckClient = class {
242
278
  /** Download one session file as text. */
243
279
  async fetchSessionFile(sessionId, path) {
244
280
  const res = await this.#fetch(this.sessionFileUrl(sessionId, path), { headers: this.#options.headers });
245
- if (!res.ok) {
246
- const payload = await res.json().catch(() => ({}));
247
- throw new Error(payload.error ?? `GET file failed with ${res.status}`);
248
- }
281
+ if (!res.ok) throw new WorkerDeckError((await res.json().catch(() => ({}))).error ?? `GET file failed with ${res.status}`, res.status);
249
282
  return await res.text();
250
283
  }
284
+ /**
285
+ * Upload one file for the session, ahead of the message that will carry it.
286
+ * The returned `id` goes to {@link SessionHandle.send}.
287
+ *
288
+ * The body is the raw bytes — no multipart — so anything `fetch` accepts as a
289
+ * body works: a `File`/`Blob` from a picker, a `Uint8Array`, a string.
290
+ */
291
+ async uploadAttachment(sessionId, file) {
292
+ const url = `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/attachments?name=${encodeURIComponent(file.name)}`;
293
+ const res = await this.#fetch(url, {
294
+ method: "POST",
295
+ headers: {
296
+ ...this.#options.headers,
297
+ "content-type": file.mediaType
298
+ },
299
+ body: file.data
300
+ });
301
+ if (!res.ok) throw new WorkerDeckError((await res.json().catch(() => ({}))).error ?? `upload failed with ${res.status}`, res.status);
302
+ return (await res.json()).attachment;
303
+ }
304
+ /** Direct URL for an uploaded attachment — an `<img src>` on a cookie-authenticated
305
+ * same-origin server. Header-authenticated clients must fetch it themselves. */
306
+ attachmentUrl(sessionId, attachmentId) {
307
+ return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/attachments/${encodeURIComponent(attachmentId)}`;
308
+ }
309
+ /**
310
+ * Direct URL for a file the session's ENGINE produced on the host — the
311
+ * `fileId` of a `file_produced` event. Same caveat as `attachmentUrl`: usable
312
+ * as an `<img src>` only where the credential is a same-origin cookie; a
313
+ * header-authenticated client (the phone) fetches it and makes its own blob.
314
+ *
315
+ * Unlike `/fs/read`, this needs no host-file roots and no raised byte cap —
316
+ * see the `file_produced` note in the protocol for why that is sound.
317
+ */
318
+ producedFileUrl(sessionId, fileId) {
319
+ return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/produced/${encodeURIComponent(fileId)}`;
320
+ }
321
+ /** Fetch a produced file's bytes. For clients that cannot put a credential on
322
+ * an `<img src>`. Throws {@link WorkerDeckError} with the response status —
323
+ * a 404 means the file is gone from disk, not that the route is missing. */
324
+ async readProducedFile(sessionId, fileId) {
325
+ const res = await this.#fetch(this.producedFileUrl(sessionId, fileId), { headers: { ...this.#options.headers } });
326
+ if (!res.ok) throw new WorkerDeckError((await res.json().catch(() => ({}))).error ?? `produced file request failed with ${res.status}`, res.status);
327
+ return await res.blob();
328
+ }
329
+ /** The session's MCP servers and their tools, live from the engine. 501 when the
330
+ * session's engine has no MCP surface; 409 while the session is parked. */
331
+ async listMcpServers(sessionId) {
332
+ return (await this.#call("GET", `/sessions/${encodeURIComponent(sessionId)}/mcp`)).servers;
333
+ }
334
+ /** Reconnect, enable or disable one MCP server; answers with the refreshed list. */
335
+ async mcpServerAction(sessionId, serverName, action) {
336
+ return (await this.#call("POST", `/sessions/${encodeURIComponent(sessionId)}/mcp/${encodeURIComponent(serverName)}`, { action })).servers;
337
+ }
251
338
  /** Direct download URL for a session file (e.g. an <a download> href). Carries
252
339
  * no headers — on authenticated servers, use fetchSessionFile instead. */
253
340
  sessionFileUrl(sessionId, path) {
@@ -306,13 +393,18 @@ var WorkerDeckClient = class {
306
393
  async deleteProfile(name) {
307
394
  await this.#call("DELETE", `/profiles/${encodeURIComponent(name)}`);
308
395
  }
309
- /** List the Agent SDK's on-disk sessions (for resume across server restarts).
310
- * Feed a result's `sessionId` to createSession({ resume }). */
396
+ /** List an engine's on-disk sessions (for resume across server restarts).
397
+ * Feed a result's `sessionId` to createSession({ resume }) — under a profile
398
+ * of the same engine. `profile` names whose store to list (claude profiles →
399
+ * the Agent SDK store, codex profiles → CODEX_HOME threads); absent, the
400
+ * server resolves it implicitly when it declares exactly one profile, else
401
+ * lists the Claude engine's store. */
311
402
  async listSdkSessions(params) {
312
403
  const search = new URLSearchParams();
313
404
  if (params?.dir) search.set("dir", params.dir);
314
405
  if (params?.limit !== void 0) search.set("limit", String(params.limit));
315
406
  if (params?.offset !== void 0) search.set("offset", String(params.offset));
407
+ if (params?.profile) search.set("profile", params.profile);
316
408
  const qs = search.size > 0 ? `?${search.toString()}` : "";
317
409
  return (await this.#call("GET", `/sdk-sessions${qs}`)).sdkSessions;
318
410
  }
@@ -407,11 +499,11 @@ var WorkerDeckClient = class {
407
499
  body: body !== void 0 ? JSON.stringify(body) : void 0
408
500
  });
409
501
  const payload = await res.json().catch(() => ({}));
410
- if (!res.ok) throw new Error(payload.error ?? `${method} ${path} failed with ${res.status}`);
502
+ if (!res.ok) throw new WorkerDeckError(payload.error ?? `${method} ${path} failed with ${res.status}`, res.status);
411
503
  return payload;
412
504
  }
413
505
  };
414
506
  //#endregion
415
- export { QueueHandle, SessionHandle, WorkerDeckClient };
507
+ export { QueueHandle, SessionHandle, WorkerDeckClient, WorkerDeckError };
416
508
 
417
509
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["#client","#options","#lastSeq","#connectTimer","#connect","#listeners","#sendFrame","#closed","#ws","#outbox","#retries","#emit","#reconnect","#fetch","#WebSocketImpl","#call"],"sources":["../src/index.ts"],"sourcesContent":["import type {\n AttachedFrame,\n ClientFrame,\n CreateJobRequest,\n CreateProfileRequest,\n CreateSessionRequest,\n JobEvent,\n JobInfo,\n FindHostFilesResponse,\n GetProfileResponse,\n ListHostDirResponse,\n ListHostRootsResponse,\n ListProfilesResponse,\n ListSessionFilesResponse,\n ReadHostFileResponse,\n WriteHostFileRequest,\n WriteHostFileResponse,\n PermissionMode,\n ProfileInfo,\n QueueServerFrame,\n QueueStats,\n ResolvePermissionRequest,\n SubmitExecutionResultRequest,\n SubmitExecutionResultResponse,\n SaveProfileResponse,\n SdkSessionSummary,\n ServerFrame,\n SessionEvent,\n SessionFileInfo,\n SessionInfo,\n ToolCallRequestFrame,\n ToolExecutionOutput,\n UpdateProfileRequest,\n} from '@workerdeck/protocol'\n\nexport type ClientOptions = {\n /** REST base, e.g. \"http://127.0.0.1:8787/v1\". The ws:// URL is derived from it. */\n baseUrl: string\n /** Extra headers for REST calls (auth). Browsers can't set WS headers — use\n * `buildWsUrl` (ticket query param) or cookies for WS auth. */\n headers?: Record<string, string>\n /** Override WS URL construction (auth tickets, proxies). */\n buildWsUrl?: (sessionId: string, afterSeq: number) => string\n /** Override the queue WS URL (`{baseUrl}/queue/ws` by default). */\n buildQueueWsUrl?: () => string\n /** Injectable for non-browser environments/tests. Defaults to globalThis.WebSocket. */\n WebSocketImpl?: typeof WebSocket\n fetchImpl?: typeof fetch\n}\n\nexport type AttachOptions = {\n /** Replay events with seq greater than this. Default 0 (full replay). */\n afterSeq?: number\n /** Auto-reconnect with backoff on unexpected disconnects. Default true. */\n reconnect?: boolean\n}\n\nexport type SessionHandleEvents = {\n /** Fired on every (re)attach with the server's session snapshot. */\n attached: AttachedFrame\n /** Every session event, replayed and live, in seq order. */\n event: SessionEvent\n protocolError: string\n /** WS connectivity: true on open, false on close. */\n connectionChange: boolean\n /**\n * The server is asking this client to execute a tool call in its own sandbox.\n * Answer with {@link SessionHandle.sendToolCallResult} or\n * {@link SessionHandle.sendToolCallError}, echoing the same `executionId`.\n * Ignoring it is safe: the server fails the execution at `expiresAt`.\n */\n toolCallRequest: ToolCallRequestFrame\n /** A bridged call no longer needs an answer (turn interrupted, timed out, or\n * the session closed) — abandon any work in progress for this executionId. */\n toolCallCanceled: { executionId: string; reason: string }\n}\n\ntype Listener<T> = (payload: T) => void\n\nexport class SessionHandle {\n readonly sessionId: string\n #client: WorkerDeckClient\n #options: Required<Pick<AttachOptions, 'reconnect'>> & AttachOptions\n #ws: WebSocket | undefined\n #listeners = new Map<keyof SessionHandleEvents, Set<Listener<never>>>()\n #lastSeq: number\n #closed = false\n #retries = 0\n #outbox: string[] = []\n #connectTimer: ReturnType<typeof setTimeout> | undefined\n\n constructor(client: WorkerDeckClient, sessionId: string, options: AttachOptions = {}) {\n this.#client = client\n this.sessionId = sessionId\n this.#options = { reconnect: true, ...options }\n this.#lastSeq = options.afterSeq ?? 0\n // Deferred a tick so an attach that is detached in the same tick (React\n // StrictMode's throwaway dev mount) never opens a socket — closing a\n // WebSocket mid-upgrade breaks proxies (vite logs EPIPE) for nothing.\n this.#connectTimer = setTimeout(() => this.#connect(), 0)\n }\n\n get lastSeq(): number {\n return this.#lastSeq\n }\n\n on<K extends keyof SessionHandleEvents>(\n kind: K,\n listener: Listener<SessionHandleEvents[K]>,\n ): () => void {\n let set = this.#listeners.get(kind)\n if (!set) {\n set = new Set()\n this.#listeners.set(kind, set)\n }\n set.add(listener as Listener<never>)\n return () => set.delete(listener as Listener<never>)\n }\n\n send(text: string): void {\n this.#sendFrame({ type: 'user_message', text })\n }\n\n approve(requestId: string, updatedInput?: Record<string, unknown>): void {\n this.#sendFrame({ type: 'permission_decision', requestId, behavior: 'allow', updatedInput })\n }\n\n deny(requestId: string, message?: string, interrupt?: boolean): void {\n this.#sendFrame({ type: 'permission_decision', requestId, behavior: 'deny', message, interrupt })\n }\n\n interrupt(): void {\n this.#sendFrame({ type: 'interrupt' })\n }\n\n setPermissionMode(mode: PermissionMode): void {\n this.#sendFrame({ type: 'set_permission_mode', mode })\n }\n\n /** Switch the model for subsequent responses; omit `model` for the default. */\n setModel(model?: string): void {\n this.#sendFrame({ type: 'set_model', model })\n }\n\n /** Answer a bridged tool call (see the `toolCallRequest` event). */\n sendToolCallResult(executionId: string, output: ToolExecutionOutput, logs?: string[]): void {\n this.#sendFrame({ type: 'tool_call_result', executionId, output, logs })\n }\n\n /** Report that a bridged tool call could not be executed. The failure is fed\n * to the model as tool output, so the agent can adapt rather than stall. */\n sendToolCallError(executionId: string, reason: string, error: string, logs?: string[]): void {\n this.#sendFrame({ type: 'tool_call_error', executionId, reason, error, logs })\n }\n\n /** Ask the server to terminate the session (the handle disconnects too). */\n closeSession(): void {\n this.#sendFrame({ type: 'close' })\n this.detach()\n }\n\n /** Disconnect this handle without touching the session. */\n detach(): void {\n this.#closed = true\n clearTimeout(this.#connectTimer)\n this.#ws?.close()\n this.#ws = undefined\n }\n\n #emit<K extends keyof SessionHandleEvents>(kind: K, payload: SessionHandleEvents[K]): void {\n const set = this.#listeners.get(kind)\n if (!set) return\n for (const listener of set) {\n try {\n ;(listener as Listener<SessionHandleEvents[K]>)(payload)\n } catch {\n // listener errors must not break the stream\n }\n }\n }\n\n #sendFrame(frame: ClientFrame): void {\n const payload = JSON.stringify(frame)\n // readyState 1 === OPEN (avoid touching the WebSocket global; impl may be injected)\n if (this.#ws && this.#ws.readyState === 1) this.#ws.send(payload)\n else this.#outbox.push(payload)\n }\n\n #connect(): void {\n if (this.#closed) return\n const ws = this.#client.openSocket(this.sessionId, this.#lastSeq)\n this.#ws = ws\n ws.onopen = () => {\n this.#retries = 0\n this.#emit('connectionChange', true)\n for (const payload of this.#outbox.splice(0)) ws.send(payload)\n }\n ws.onmessage = (msg: MessageEvent) => {\n const frame = JSON.parse(String(msg.data)) as ServerFrame\n if (frame.type === 'attached') {\n this.#emit('attached', frame)\n } else if (frame.type === 'event') {\n if (frame.event.seq <= this.#lastSeq) return\n this.#lastSeq = frame.event.seq\n this.#emit('event', frame.event)\n } else if (frame.type === 'tool_call_request') {\n this.#emit('toolCallRequest', frame)\n } else if (frame.type === 'tool_call_canceled') {\n this.#emit('toolCallCanceled', { executionId: frame.executionId, reason: frame.reason })\n } else if (frame.type === 'protocol_error') {\n this.#emit('protocolError', frame.message)\n }\n }\n ws.onclose = () => {\n this.#emit('connectionChange', false)\n if (this.#closed || !this.#options.reconnect) return\n const delay = Math.min(500 * 2 ** this.#retries++, 10_000)\n this.#connectTimer = setTimeout(() => this.#connect(), delay)\n }\n ws.onerror = () => {\n // onclose follows; reconnect handled there\n }\n }\n}\n\nexport type QueueHandleEvents = {\n /** Fired on every (re)attach with the server's current stats. */\n attached: QueueStats\n /** Every job lifecycle/progress event, live. */\n event: JobEvent\n /** Refreshed stats pushed after job lifecycle changes. */\n stats: QueueStats\n /** WS connectivity: true on open, false on close. */\n connectionChange: boolean\n}\n\n/**\n * Live view of the server's job queue over `{basePath}/queue/ws`. The stream is\n * read-only — submit/cancel stay on the REST methods. There is no replay: on\n * (re)connect, re-list jobs and treat the stream as updates from there.\n */\nexport class QueueHandle {\n #client: WorkerDeckClient\n #reconnect: boolean\n #ws: WebSocket | undefined\n #listeners = new Map<keyof QueueHandleEvents, Set<Listener<never>>>()\n #closed = false\n #retries = 0\n #connectTimer: ReturnType<typeof setTimeout> | undefined\n\n constructor(client: WorkerDeckClient, options: { reconnect?: boolean } = {}) {\n this.#client = client\n this.#reconnect = options.reconnect ?? true\n // Deferred a tick for the same StrictMode reason as SessionHandle.\n this.#connectTimer = setTimeout(() => this.#connect(), 0)\n }\n\n on<K extends keyof QueueHandleEvents>(\n kind: K,\n listener: Listener<QueueHandleEvents[K]>,\n ): () => void {\n let set = this.#listeners.get(kind)\n if (!set) {\n set = new Set()\n this.#listeners.set(kind, set)\n }\n set.add(listener as Listener<never>)\n return () => set.delete(listener as Listener<never>)\n }\n\n detach(): void {\n this.#closed = true\n clearTimeout(this.#connectTimer)\n this.#ws?.close()\n this.#ws = undefined\n }\n\n #emit<K extends keyof QueueHandleEvents>(kind: K, payload: QueueHandleEvents[K]): void {\n const set = this.#listeners.get(kind)\n if (!set) return\n for (const listener of set) {\n try {\n ;(listener as Listener<QueueHandleEvents[K]>)(payload)\n } catch {\n // listener errors must not break the stream\n }\n }\n }\n\n #connect(): void {\n if (this.#closed) return\n const ws = this.#client.openQueueSocket()\n this.#ws = ws\n ws.onopen = () => {\n this.#retries = 0\n this.#emit('connectionChange', true)\n }\n ws.onmessage = (msg: MessageEvent) => {\n const frame = JSON.parse(String(msg.data)) as QueueServerFrame\n if (frame.type === 'queue_attached') {\n this.#emit('attached', frame.stats)\n this.#emit('stats', frame.stats)\n } else if (frame.type === 'job_event') {\n this.#emit('event', frame.event)\n } else if (frame.type === 'queue_stats') {\n this.#emit('stats', frame.stats)\n }\n }\n ws.onclose = () => {\n this.#emit('connectionChange', false)\n if (this.#closed || !this.#reconnect) return\n const delay = Math.min(500 * 2 ** this.#retries++, 10_000)\n this.#connectTimer = setTimeout(() => this.#connect(), delay)\n }\n ws.onerror = () => {\n // onclose follows; reconnect handled there\n }\n }\n}\n\nexport class WorkerDeckClient {\n #options: ClientOptions\n #fetch: typeof fetch\n #WebSocketImpl: typeof WebSocket\n\n constructor(options: ClientOptions) {\n this.#options = options\n this.#fetch = options.fetchImpl ?? fetch.bind(globalThis)\n this.#WebSocketImpl = options.WebSocketImpl ?? WebSocket\n }\n\n async createSession(request: CreateSessionRequest): Promise<SessionInfo> {\n const body = await this.#call('POST', '/sessions', request)\n return (body as { session: SessionInfo }).session\n }\n\n async listSessions(): Promise<SessionInfo[]> {\n const body = await this.#call('GET', '/sessions')\n return (body as { sessions: SessionInfo[] }).sessions\n }\n\n async getSession(id: string): Promise<SessionInfo> {\n const body = await this.#call('GET', `/sessions/${encodeURIComponent(id)}`)\n return (body as { session: SessionInfo }).session\n }\n\n async deleteSession(id: string): Promise<SessionInfo> {\n const body = await this.#call('DELETE', `/sessions/${encodeURIComponent(id)}`)\n return (body as { session: SessionInfo }).session\n }\n\n /** List the files currently in a session's scratch filesystem (deliverables the\n * agent wrote; see the `file_delivered` event). 404s when the session's engine\n * has no file store (Claude-engine sessions). */\n async listSessionFiles(sessionId: string): Promise<SessionFileInfo[]> {\n const body = await this.#call('GET', `/sessions/${encodeURIComponent(sessionId)}/files`)\n return (body as ListSessionFilesResponse).files\n }\n\n /** Download one session file as text. */\n async fetchSessionFile(sessionId: string, path: string): Promise<string> {\n const res = await this.#fetch(this.sessionFileUrl(sessionId, path), {\n headers: this.#options.headers,\n })\n if (!res.ok) {\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(payload.error ?? `GET file failed with ${res.status}`)\n }\n return await res.text()\n }\n\n /** Direct download URL for a session file (e.g. an <a download> href). Carries\n * no headers — on authenticated servers, use fetchSessionFile instead. */\n sessionFileUrl(sessionId: string, path: string): string {\n const encoded = path\n .split('/')\n .filter(Boolean)\n .map(encodeURIComponent)\n .join('/')\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/files/${encoded}`\n }\n\n /** Resolve a pending permission over REST — the remote-controller counterpart of the\n * WS `permission_decision` command (e.g. answering a job's AskUserQuestion from a\n * webhook consumer; the request rides on job_progress deliveries). Throws if the\n * request is unknown, already resolved, or expired. */\n async resolvePermission(\n sessionId: string,\n requestId: string,\n decision: ResolvePermissionRequest,\n ): Promise<void> {\n await this.#call(\n 'POST',\n `/sessions/${encodeURIComponent(sessionId)}/permissions/${encodeURIComponent(requestId)}`,\n decision,\n )\n }\n\n /**\n * Deliver the result of a deferred tool execution — the callback a remote\n * worker (or a human) makes when the work a session parked on is done. The\n * session is rehydrated if its runner was torn down, and the agent loop\n * continues with this as the tool's output.\n *\n * Applied idempotently by `executionId`: a duplicate, or one racing the\n * execution watchdog, resolves with `applied: false` instead of applying twice.\n * Throws (404) when no session is waiting on that id.\n */\n async submitExecutionResult(\n executionId: string,\n result: SubmitExecutionResultRequest,\n ): Promise<SubmitExecutionResultResponse> {\n return (await this.#call(\n 'POST',\n `/executions/${encodeURIComponent(executionId)}/result`,\n result,\n )) as SubmitExecutionResultResponse\n }\n\n /** List the profiles (named Claude Code config dirs) this server declares, filtered\n * to what the caller may use. Feed a result's `name` to createSession({ profile }).\n * Servers predating profiles 404 here — catch and treat as none declared. */\n /** The profiles this caller may use, plus whether it may create new ones.\n * Each profile carries `managed: true` when it is store-backed and therefore\n * editable; profiles declared in server options are not. */\n async listProfiles(): Promise<ListProfilesResponse> {\n return (await this.#call('GET', '/profiles')) as ListProfilesResponse\n }\n\n /** One profile plus a fresh, view-only snapshot of its config directory (settings,\n * skills, agents, commands — env var names only, never values). */\n async getProfile(name: string): Promise<GetProfileResponse> {\n return (await this.#call('GET', `/profiles/${encodeURIComponent(name)}`)) as GetProfileResponse\n }\n\n /**\n * Create a managed profile. Requires a server with a profile store and a\n * principal allowed to manage profiles; 409 if the name is already taken by a\n * managed or a startup-declared profile.\n */\n async createProfile(profile: CreateProfileRequest): Promise<ProfileInfo> {\n const body = await this.#call('POST', '/profiles', profile)\n return (body as SaveProfileResponse).profile\n }\n\n /** Merge into a managed profile. The name is the route: profiles cannot be\n * renamed, since sessions and jobs are already pinned to the old one. */\n async updateProfile(name: string, patch: UpdateProfileRequest): Promise<ProfileInfo> {\n const body = await this.#call('PATCH', `/profiles/${encodeURIComponent(name)}`, patch)\n return (body as SaveProfileResponse).profile\n }\n\n /** Delete a managed profile. Startup-declared profiles are refused (403) —\n * they live in the server's options. */\n async deleteProfile(name: string): Promise<void> {\n await this.#call('DELETE', `/profiles/${encodeURIComponent(name)}`)\n }\n\n /** List the Agent SDK's on-disk sessions (for resume across server restarts).\n * Feed a result's `sessionId` to createSession({ resume }). */\n async listSdkSessions(params?: {\n dir?: string\n limit?: number\n offset?: number\n }): Promise<SdkSessionSummary[]> {\n const search = new URLSearchParams()\n if (params?.dir) search.set('dir', params.dir)\n if (params?.limit !== undefined) search.set('limit', String(params.limit))\n if (params?.offset !== undefined) search.set('offset', String(params.offset))\n const qs = search.size > 0 ? `?${search.toString()}` : ''\n const body = await this.#call('GET', `/sdk-sessions${qs}`)\n return (body as { sdkSessions: SdkSessionSummary[] }).sdkSessions\n }\n\n // -- Host filesystem (requires the server to be configured with `hostFiles`) -\n\n /**\n * The host directories this server will let a client browse, and whether it\n * accepts writes. Servers without host-file access configured 404 here — catch\n * and treat as \"no file browser\", the same way `listProfiles` handles an older\n * server.\n *\n * These are operator-privileged routes: the auth key is the whole authorization\n * story, and they bypass the agent permission flow entirely. See the protocol\n * package's `HostFileRoot` for why that framing is deliberate.\n */\n async listHostRoots(): Promise<ListHostRootsResponse> {\n return (await this.#call('GET', '/fs/roots')) as ListHostRootsResponse\n }\n\n /** One host directory, not recursive. Symlinks are reported as symlinks, never\n * followed here — read one to find out whether it resolves somewhere allowed. */\n async listHostDir(path: string): Promise<ListHostDirResponse> {\n const qs = `?path=${encodeURIComponent(path)}`\n return (await this.#call('GET', `/fs/list${qs}`)) as ListHostDirResponse\n }\n\n /** Recursive fuzzy file search under one host directory — the `@file` picker's\n * query. Cheap enough to call per keystroke: build directories are skipped and\n * the walk is bounded, truncating rather than erroring. */\n async findHostFiles(path: string, query = '', limit?: number): Promise<FindHostFilesResponse> {\n const search = new URLSearchParams({ path, q: query })\n if (limit !== undefined) search.set('limit', String(limit))\n return (await this.#call('GET', `/fs/find?${search.toString()}`)) as FindHostFilesResponse\n }\n\n /** Read one host file. Binary content comes back base64-encoded; the returned\n * `hash` is what a later `writeHostFile` needs as its `expectedHash`. */\n async readHostFile(path: string): Promise<ReadHostFileResponse> {\n const qs = `?path=${encodeURIComponent(path)}`\n return (await this.#call('GET', `/fs/read${qs}`)) as ReadHostFileResponse\n }\n\n /**\n * Write one host file, conditionally — always. Pass the `hash` from the read this\n * edit is based on; a 409 means the agent (or anything else) changed the file\n * underneath you, and the edit must be rebased rather than forced. Omit\n * `expectedHash` only to create a file that does not exist yet.\n */\n async writeHostFile(request: WriteHostFileRequest): Promise<WriteHostFileResponse> {\n return (await this.#call('PUT', '/fs/write', request)) as WriteHostFileResponse\n }\n\n // -- Job queue (requires the server to be configured with `queue`) ----------\n\n /** Schedule a one-shot run. The returned job's `sessionId` (once running) can be\n * fed to `attach()` to watch the run live. */\n async createJob(request: CreateJobRequest): Promise<JobInfo> {\n const body = await this.#call('POST', '/jobs', request)\n return (body as { job: JobInfo }).job\n }\n\n async listJobs(): Promise<JobInfo[]> {\n const body = await this.#call('GET', '/jobs')\n return (body as { jobs: JobInfo[] }).jobs\n }\n\n async getJob(id: string): Promise<JobInfo> {\n const body = await this.#call('GET', `/jobs/${encodeURIComponent(id)}`)\n return (body as { job: JobInfo }).job\n }\n\n /** Cancel a queued or running job. */\n async cancelJob(id: string): Promise<JobInfo> {\n const body = await this.#call('DELETE', `/jobs/${encodeURIComponent(id)}`)\n return (body as { job: JobInfo }).job\n }\n\n async queueStats(): Promise<QueueStats> {\n const body = await this.#call('GET', '/queue')\n return (body as { stats: QueueStats }).stats\n }\n\n attach(sessionId: string, options?: AttachOptions): SessionHandle {\n return new SessionHandle(this, sessionId, options)\n }\n\n /** Stream the job queue live (requires the server to be configured with `queue`).\n * Servers without a queue refuse the socket — check REST first or expect retries. */\n attachQueue(options?: { reconnect?: boolean }): QueueHandle {\n return new QueueHandle(this, options)\n }\n\n /** @internal used by SessionHandle */\n openSocket(sessionId: string, afterSeq: number): WebSocket {\n const url =\n this.#options.buildWsUrl?.(sessionId, afterSeq) ??\n `${this.#options.baseUrl.replace(/^http/, 'ws')}/sessions/${encodeURIComponent(sessionId)}/ws?afterSeq=${afterSeq}`\n return new this.#WebSocketImpl(url)\n }\n\n /** @internal used by QueueHandle */\n openQueueSocket(): WebSocket {\n const url =\n this.#options.buildQueueWsUrl?.() ??\n `${this.#options.baseUrl.replace(/^http/, 'ws')}/queue/ws`\n return new this.#WebSocketImpl(url)\n }\n\n async #call(method: string, path: string, body?: unknown): Promise<unknown> {\n const res = await this.#fetch(`${this.#options.baseUrl}${path}`, {\n method,\n headers: {\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n ...this.#options.headers,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n if (!res.ok) {\n throw new Error(payload.error ?? `${method} ${path} failed with ${res.status}`)\n }\n return payload\n }\n}\n"],"mappings":";AA+EA,IAAa,gBAAb,MAA2B;CACzB;CACA;CACA;CACA;CACA,6BAAa,IAAI,KAAsD;CACvE;CACA,UAAU;CACV,WAAW;CACX,UAAoB,EAAE;CACtB;CAEA,YAAY,QAA0B,WAAmB,UAAyB,EAAE,EAAE;AACpF,QAAA,SAAe;AACf,OAAK,YAAY;AACjB,QAAA,UAAgB;GAAE,WAAW;GAAM,GAAG;GAAS;AAC/C,QAAA,UAAgB,QAAQ,YAAY;AAIpC,QAAA,eAAqB,iBAAiB,MAAA,SAAe,EAAE,EAAE;;CAG3D,IAAI,UAAkB;AACpB,SAAO,MAAA;;CAGT,GACE,MACA,UACY;EACZ,IAAI,MAAM,MAAA,UAAgB,IAAI,KAAK;AACnC,MAAI,CAAC,KAAK;AACR,yBAAM,IAAI,KAAK;AACf,SAAA,UAAgB,IAAI,MAAM,IAAI;;AAEhC,MAAI,IAAI,SAA4B;AACpC,eAAa,IAAI,OAAO,SAA4B;;CAGtD,KAAK,MAAoB;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B,IAAI;;CAGrC,OAAA,KAAY,QAAgB,MAAc,MAAkC;EAC1E,MAAM,MAAM,MAAM,MAAA,MAAY,GAAG,MAAA,QAAc,UAAU,QAAQ;GAC/D;GACA,SAAS;IACP,GAAI,SAAS,KAAA,IAAY,EAAE,gBAAgB,oBAAoB,GAAG,EAAE;IACpE,GAAG,MAAA,QAAc;IAClB;GACD,MAAM,SAAS,KAAA,IAAY,KAAK,UAAU,KAAK,GAAG,KAAA;GACnD,CAAC;EACF,MAAM,UAAW,MAAM,IAAI,MAAM,CAAC,aAAa,EAAE,EAAE;AACnD,MAAI,CAAC,IAAI,GACP,OAAM,IAAI,MAAM,QAAQ,SAAS,GAAG,OAAO,GAAG,KAAK,eAAe,IAAI,SAAS;AAEjF,SAAO"}
1
+ {"version":3,"file":"index.mjs","names":["#client","#options","#lastSeq","#connectTimer","#connect","#listeners","#sendFrame","#closed","#ws","#retries","#outbox","#emit","#reconnect","#fetch","#WebSocketImpl","#call"],"sources":["../src/index.ts"],"sourcesContent":["import type {\n AttachedFrame,\n ClientFrame,\n CreateJobRequest,\n CreateProfileRequest,\n CreateSessionRequest,\n JobEvent,\n JobInfo,\n FindHostFilesResponse,\n GetProfileResponse,\n ListHostDirResponse,\n ListHostRootsResponse,\n ListProfilesResponse,\n ListSessionFilesResponse,\n McpServerActionRequest,\n McpServersResponse,\n McpServerStatusInfo,\n MessageAttachment,\n ReadHostFileResponse,\n UploadAttachmentResponse,\n WriteHostFileRequest,\n WriteHostFileResponse,\n PermissionMode,\n ProfileInfo,\n QueueServerFrame,\n QueueStats,\n ResolvePermissionRequest,\n UpdateSessionRequest,\n SubmitExecutionResultRequest,\n SubmitExecutionResultResponse,\n SaveProfileResponse,\n SdkSessionSummary,\n ServerFrame,\n SessionEvent,\n SessionFileInfo,\n SessionInfo,\n ToolCallRequestFrame,\n ToolExecutionOutput,\n UpdateProfileRequest,\n} from '@workerdeck/protocol'\n\n/** Whatever the ambient `fetch` accepts as a body — `Blob`/`File` in a browser,\n * `Uint8Array` or a string in Node. Derived rather than named (`BodyInit` is a\n * DOM-lib type, and this package compiles against both). */\nexport type FetchBody = NonNullable<NonNullable<Parameters<typeof fetch>[1]>['body']>\n\nexport type ClientOptions = {\n /** REST base, e.g. \"http://127.0.0.1:8787/v1\". The ws:// URL is derived from it. */\n baseUrl: string\n /** Extra headers for REST calls (auth). Browsers can't set WS headers — use\n * `buildWsUrl` (ticket query param) or cookies for WS auth. */\n headers?: Record<string, string>\n /** Override WS URL construction (auth tickets, proxies). */\n buildWsUrl?: (sessionId: string, afterSeq: number) => string\n /** Override the queue WS URL (`{baseUrl}/queue/ws` by default). */\n buildQueueWsUrl?: () => string\n /** Injectable for non-browser environments/tests. Defaults to globalThis.WebSocket. */\n WebSocketImpl?: typeof WebSocket\n fetchImpl?: typeof fetch\n}\n\n/**\n * A REST call the gateway refused, carrying the status alongside the message.\n *\n * An `Error` subclass on purpose: every existing `e instanceof Error` check and\n * every `e.message` read keeps working unchanged. The status is what lets a\n * caller tell \"this server doesn't have that route\" (404 — stop asking) from\n * \"that file was too big\" (413 — tell the user), which a message string can't.\n */\nexport class WorkerDeckError extends Error {\n readonly status: number\n constructor(message: string, status: number) {\n super(message)\n this.name = 'WorkerDeckError'\n this.status = status\n }\n}\n\nexport type AttachOptions = {\n /** Replay events with seq greater than this. Default 0 (full replay). */\n afterSeq?: number\n /** Auto-reconnect with backoff on unexpected disconnects. Default true. */\n reconnect?: boolean\n}\n\nexport type SessionHandleEvents = {\n /** Fired on every (re)attach with the server's session snapshot. */\n attached: AttachedFrame\n /** Every session event, replayed and live, in seq order. */\n event: SessionEvent\n protocolError: string\n /** WS connectivity: true on open, false on close. */\n connectionChange: boolean\n /**\n * A reconnect has been scheduled, carrying how many have failed in a row (1 on\n * the first). The handle retries forever, so \"offline\" is a judgement a UI makes\n * about how long it has been failing rather than a state reported here.\n */\n reconnectAttempt: number\n /**\n * The server is asking this client to execute a tool call in its own sandbox.\n * Answer with {@link SessionHandle.sendToolCallResult} or\n * {@link SessionHandle.sendToolCallError}, echoing the same `executionId`.\n * Ignoring it is safe: the server fails the execution at `expiresAt`.\n */\n toolCallRequest: ToolCallRequestFrame\n /** A bridged call no longer needs an answer (turn interrupted, timed out, or\n * the session closed) — abandon any work in progress for this executionId. */\n toolCallCanceled: { executionId: string; reason: string }\n}\n\ntype Listener<T> = (payload: T) => void\n\nexport class SessionHandle {\n readonly sessionId: string\n #client: WorkerDeckClient\n #options: Required<Pick<AttachOptions, 'reconnect'>> & AttachOptions\n #ws: WebSocket | undefined\n #listeners = new Map<keyof SessionHandleEvents, Set<Listener<never>>>()\n #lastSeq: number\n #closed = false\n #retries = 0\n #outbox: string[] = []\n #connectTimer: ReturnType<typeof setTimeout> | undefined\n\n constructor(client: WorkerDeckClient, sessionId: string, options: AttachOptions = {}) {\n this.#client = client\n this.sessionId = sessionId\n this.#options = { reconnect: true, ...options }\n this.#lastSeq = options.afterSeq ?? 0\n // Deferred a tick so an attach that is detached in the same tick (React\n // StrictMode's throwaway dev mount) never opens a socket — closing a\n // WebSocket mid-upgrade breaks proxies (vite logs EPIPE) for nothing.\n this.#connectTimer = setTimeout(() => this.#connect(), 0)\n }\n\n get lastSeq(): number {\n return this.#lastSeq\n }\n\n on<K extends keyof SessionHandleEvents>(\n kind: K,\n listener: Listener<SessionHandleEvents[K]>,\n ): () => void {\n let set = this.#listeners.get(kind)\n if (!set) {\n set = new Set()\n this.#listeners.set(kind, set)\n }\n set.add(listener as Listener<never>)\n return () => set.delete(listener as Listener<never>)\n }\n\n /** Send a message, optionally naming attachments uploaded ahead of it with\n * {@link WorkerDeckClient.uploadAttachment} (ids in the order they should reach\n * the model). An unknown id fails the whole command — the server will not send a\n * message that quietly lost its picture. */\n send(text: string, attachmentIds?: string[]): void {\n this.#sendFrame({\n type: 'user_message',\n text,\n attachmentIds: attachmentIds?.length ? attachmentIds : undefined,\n })\n }\n\n approve(requestId: string, updatedInput?: Record<string, unknown>): void {\n this.#sendFrame({ type: 'permission_decision', requestId, behavior: 'allow', updatedInput })\n }\n\n deny(requestId: string, message?: string, interrupt?: boolean): void {\n this.#sendFrame({ type: 'permission_decision', requestId, behavior: 'deny', message, interrupt })\n }\n\n interrupt(): void {\n this.#sendFrame({ type: 'interrupt' })\n }\n\n setPermissionMode(mode: PermissionMode): void {\n this.#sendFrame({ type: 'set_permission_mode', mode })\n }\n\n /** Switch the model for subsequent responses; omit `model` for the default. */\n setModel(model?: string): void {\n this.#sendFrame({ type: 'set_model', model })\n }\n\n /** Answer a bridged tool call (see the `toolCallRequest` event). */\n sendToolCallResult(executionId: string, output: ToolExecutionOutput, logs?: string[]): void {\n this.#sendFrame({ type: 'tool_call_result', executionId, output, logs })\n }\n\n /** Report that a bridged tool call could not be executed. The failure is fed\n * to the model as tool output, so the agent can adapt rather than stall. */\n sendToolCallError(executionId: string, reason: string, error: string, logs?: string[]): void {\n this.#sendFrame({ type: 'tool_call_error', executionId, reason, error, logs })\n }\n\n /** Ask the server to terminate the session (the handle disconnects too). */\n closeSession(): void {\n this.#sendFrame({ type: 'close' })\n this.detach()\n }\n\n /** Skip the reconnect backoff and try again now — what a tab returning to the\n * foreground should do, rather than sitting out the remaining delay. No-op\n * while connected or after {@link SessionHandle.detach}. */\n reconnectNow(): void {\n if (this.#closed || (this.#ws && this.#ws.readyState === 1)) return\n clearTimeout(this.#connectTimer)\n this.#retries = 0\n this.#connect()\n }\n\n /** Disconnect this handle without touching the session. */\n detach(): void {\n this.#closed = true\n clearTimeout(this.#connectTimer)\n this.#ws?.close()\n this.#ws = undefined\n }\n\n #emit<K extends keyof SessionHandleEvents>(kind: K, payload: SessionHandleEvents[K]): void {\n const set = this.#listeners.get(kind)\n if (!set) return\n for (const listener of set) {\n try {\n ;(listener as Listener<SessionHandleEvents[K]>)(payload)\n } catch {\n // listener errors must not break the stream\n }\n }\n }\n\n #sendFrame(frame: ClientFrame): void {\n const payload = JSON.stringify(frame)\n // readyState 1 === OPEN (avoid touching the WebSocket global; impl may be injected)\n if (this.#ws && this.#ws.readyState === 1) this.#ws.send(payload)\n else this.#outbox.push(payload)\n }\n\n #connect(): void {\n if (this.#closed) return\n const ws = this.#client.openSocket(this.sessionId, this.#lastSeq)\n this.#ws = ws\n ws.onopen = () => {\n this.#retries = 0\n this.#emit('connectionChange', true)\n for (const payload of this.#outbox.splice(0)) ws.send(payload)\n }\n ws.onmessage = (msg: MessageEvent) => {\n const frame = JSON.parse(String(msg.data)) as ServerFrame\n if (frame.type === 'attached') {\n this.#emit('attached', frame)\n } else if (frame.type === 'event') {\n if (frame.event.seq <= this.#lastSeq) return\n this.#lastSeq = frame.event.seq\n this.#emit('event', frame.event)\n } else if (frame.type === 'tool_call_request') {\n this.#emit('toolCallRequest', frame)\n } else if (frame.type === 'tool_call_canceled') {\n this.#emit('toolCallCanceled', { executionId: frame.executionId, reason: frame.reason })\n } else if (frame.type === 'protocol_error') {\n this.#emit('protocolError', frame.message)\n }\n }\n ws.onclose = () => {\n this.#emit('connectionChange', false)\n if (this.#closed || !this.#options.reconnect) return\n const delay = Math.min(500 * 2 ** this.#retries++, 10_000)\n this.#emit('reconnectAttempt', this.#retries)\n this.#connectTimer = setTimeout(() => this.#connect(), delay)\n }\n ws.onerror = () => {\n // onclose follows; reconnect handled there\n }\n }\n}\n\nexport type QueueHandleEvents = {\n /** Fired on every (re)attach with the server's current stats. */\n attached: QueueStats\n /** Every job lifecycle/progress event, live. */\n event: JobEvent\n /** Refreshed stats pushed after job lifecycle changes. */\n stats: QueueStats\n /** WS connectivity: true on open, false on close. */\n connectionChange: boolean\n}\n\n/**\n * Live view of the server's job queue over `{basePath}/queue/ws`. The stream is\n * read-only — submit/cancel stay on the REST methods. There is no replay: on\n * (re)connect, re-list jobs and treat the stream as updates from there.\n */\nexport class QueueHandle {\n #client: WorkerDeckClient\n #reconnect: boolean\n #ws: WebSocket | undefined\n #listeners = new Map<keyof QueueHandleEvents, Set<Listener<never>>>()\n #closed = false\n #retries = 0\n #connectTimer: ReturnType<typeof setTimeout> | undefined\n\n constructor(client: WorkerDeckClient, options: { reconnect?: boolean } = {}) {\n this.#client = client\n this.#reconnect = options.reconnect ?? true\n // Deferred a tick for the same StrictMode reason as SessionHandle.\n this.#connectTimer = setTimeout(() => this.#connect(), 0)\n }\n\n on<K extends keyof QueueHandleEvents>(\n kind: K,\n listener: Listener<QueueHandleEvents[K]>,\n ): () => void {\n let set = this.#listeners.get(kind)\n if (!set) {\n set = new Set()\n this.#listeners.set(kind, set)\n }\n set.add(listener as Listener<never>)\n return () => set.delete(listener as Listener<never>)\n }\n\n detach(): void {\n this.#closed = true\n clearTimeout(this.#connectTimer)\n this.#ws?.close()\n this.#ws = undefined\n }\n\n #emit<K extends keyof QueueHandleEvents>(kind: K, payload: QueueHandleEvents[K]): void {\n const set = this.#listeners.get(kind)\n if (!set) return\n for (const listener of set) {\n try {\n ;(listener as Listener<QueueHandleEvents[K]>)(payload)\n } catch {\n // listener errors must not break the stream\n }\n }\n }\n\n #connect(): void {\n if (this.#closed) return\n const ws = this.#client.openQueueSocket()\n this.#ws = ws\n ws.onopen = () => {\n this.#retries = 0\n this.#emit('connectionChange', true)\n }\n ws.onmessage = (msg: MessageEvent) => {\n const frame = JSON.parse(String(msg.data)) as QueueServerFrame\n if (frame.type === 'queue_attached') {\n this.#emit('attached', frame.stats)\n this.#emit('stats', frame.stats)\n } else if (frame.type === 'job_event') {\n this.#emit('event', frame.event)\n } else if (frame.type === 'queue_stats') {\n this.#emit('stats', frame.stats)\n }\n }\n ws.onclose = () => {\n this.#emit('connectionChange', false)\n if (this.#closed || !this.#reconnect) return\n const delay = Math.min(500 * 2 ** this.#retries++, 10_000)\n this.#connectTimer = setTimeout(() => this.#connect(), delay)\n }\n ws.onerror = () => {\n // onclose follows; reconnect handled there\n }\n }\n}\n\nexport class WorkerDeckClient {\n #options: ClientOptions\n #fetch: typeof fetch\n #WebSocketImpl: typeof WebSocket\n\n constructor(options: ClientOptions) {\n this.#options = options\n this.#fetch = options.fetchImpl ?? fetch.bind(globalThis)\n this.#WebSocketImpl = options.WebSocketImpl ?? WebSocket\n }\n\n async createSession(request: CreateSessionRequest): Promise<SessionInfo> {\n const body = await this.#call('POST', '/sessions', request)\n return (body as { session: SessionInfo }).session\n }\n\n async listSessions(): Promise<SessionInfo[]> {\n const body = await this.#call('GET', '/sessions')\n return (body as { sessions: SessionInfo[] }).sessions\n }\n\n async getSession(id: string): Promise<SessionInfo> {\n const body = await this.#call('GET', `/sessions/${encodeURIComponent(id)}`)\n return (body as { session: SessionInfo }).session\n }\n\n /** Rename a session (or clear the name with `null`, restoring the derived\n * title). 409 when the session is parked. */\n async updateSession(id: string, patch: UpdateSessionRequest): Promise<SessionInfo> {\n const body = await this.#call('PATCH', `/sessions/${encodeURIComponent(id)}`, patch)\n return (body as { session: SessionInfo }).session\n }\n\n async deleteSession(id: string): Promise<SessionInfo> {\n const body = await this.#call('DELETE', `/sessions/${encodeURIComponent(id)}`)\n return (body as { session: SessionInfo }).session\n }\n\n /** List the files currently in a session's scratch filesystem (deliverables the\n * agent wrote; see the `file_delivered` event). 404s when the session's engine\n * has no file store (Claude-engine sessions). */\n async listSessionFiles(sessionId: string): Promise<SessionFileInfo[]> {\n const body = await this.#call('GET', `/sessions/${encodeURIComponent(sessionId)}/files`)\n return (body as ListSessionFilesResponse).files\n }\n\n /** Download one session file as text. */\n async fetchSessionFile(sessionId: string, path: string): Promise<string> {\n const res = await this.#fetch(this.sessionFileUrl(sessionId, path), {\n headers: this.#options.headers,\n })\n if (!res.ok) {\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n throw new WorkerDeckError(payload.error ?? `GET file failed with ${res.status}`, res.status)\n }\n return await res.text()\n }\n\n /**\n * Upload one file for the session, ahead of the message that will carry it.\n * The returned `id` goes to {@link SessionHandle.send}.\n *\n * The body is the raw bytes — no multipart — so anything `fetch` accepts as a\n * body works: a `File`/`Blob` from a picker, a `Uint8Array`, a string.\n */\n async uploadAttachment(\n sessionId: string,\n file: { name: string; mediaType: string; data: FetchBody },\n ): Promise<MessageAttachment> {\n const url = `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/attachments?name=${encodeURIComponent(file.name)}`\n const res = await this.#fetch(url, {\n method: 'POST',\n headers: { ...this.#options.headers, 'content-type': file.mediaType },\n body: file.data,\n })\n if (!res.ok) {\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n throw new WorkerDeckError(payload.error ?? `upload failed with ${res.status}`, res.status)\n }\n return ((await res.json()) as UploadAttachmentResponse).attachment\n }\n\n /** Direct URL for an uploaded attachment — an `<img src>` on a cookie-authenticated\n * same-origin server. Header-authenticated clients must fetch it themselves. */\n attachmentUrl(sessionId: string, attachmentId: string): string {\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/attachments/${encodeURIComponent(attachmentId)}`\n }\n\n /**\n * Direct URL for a file the session's ENGINE produced on the host — the\n * `fileId` of a `file_produced` event. Same caveat as `attachmentUrl`: usable\n * as an `<img src>` only where the credential is a same-origin cookie; a\n * header-authenticated client (the phone) fetches it and makes its own blob.\n *\n * Unlike `/fs/read`, this needs no host-file roots and no raised byte cap —\n * see the `file_produced` note in the protocol for why that is sound.\n */\n producedFileUrl(sessionId: string, fileId: string): string {\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/produced/${encodeURIComponent(fileId)}`\n }\n\n /** Fetch a produced file's bytes. For clients that cannot put a credential on\n * an `<img src>`. Throws {@link WorkerDeckError} with the response status —\n * a 404 means the file is gone from disk, not that the route is missing. */\n async readProducedFile(sessionId: string, fileId: string): Promise<Blob> {\n const res = await this.#fetch(this.producedFileUrl(sessionId, fileId), {\n headers: { ...this.#options.headers },\n })\n if (!res.ok) {\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n throw new WorkerDeckError(\n payload.error ?? `produced file request failed with ${res.status}`,\n res.status,\n )\n }\n return await res.blob()\n }\n\n /** The session's MCP servers and their tools, live from the engine. 501 when the\n * session's engine has no MCP surface; 409 while the session is parked. */\n async listMcpServers(sessionId: string): Promise<McpServerStatusInfo[]> {\n const body = await this.#call('GET', `/sessions/${encodeURIComponent(sessionId)}/mcp`)\n return (body as McpServersResponse).servers\n }\n\n /** Reconnect, enable or disable one MCP server; answers with the refreshed list. */\n async mcpServerAction(\n sessionId: string,\n serverName: string,\n action: McpServerActionRequest['action'],\n ): Promise<McpServerStatusInfo[]> {\n const body = await this.#call(\n 'POST',\n `/sessions/${encodeURIComponent(sessionId)}/mcp/${encodeURIComponent(serverName)}`,\n { action },\n )\n return (body as McpServersResponse).servers\n }\n\n /** Direct download URL for a session file (e.g. an <a download> href). Carries\n * no headers — on authenticated servers, use fetchSessionFile instead. */\n sessionFileUrl(sessionId: string, path: string): string {\n const encoded = path\n .split('/')\n .filter(Boolean)\n .map(encodeURIComponent)\n .join('/')\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/files/${encoded}`\n }\n\n /** Resolve a pending permission over REST — the remote-controller counterpart of the\n * WS `permission_decision` command (e.g. answering a job's AskUserQuestion from a\n * webhook consumer; the request rides on job_progress deliveries). Throws if the\n * request is unknown, already resolved, or expired. */\n async resolvePermission(\n sessionId: string,\n requestId: string,\n decision: ResolvePermissionRequest,\n ): Promise<void> {\n await this.#call(\n 'POST',\n `/sessions/${encodeURIComponent(sessionId)}/permissions/${encodeURIComponent(requestId)}`,\n decision,\n )\n }\n\n /**\n * Deliver the result of a deferred tool execution — the callback a remote\n * worker (or a human) makes when the work a session parked on is done. The\n * session is rehydrated if its runner was torn down, and the agent loop\n * continues with this as the tool's output.\n *\n * Applied idempotently by `executionId`: a duplicate, or one racing the\n * execution watchdog, resolves with `applied: false` instead of applying twice.\n * Throws (404) when no session is waiting on that id.\n */\n async submitExecutionResult(\n executionId: string,\n result: SubmitExecutionResultRequest,\n ): Promise<SubmitExecutionResultResponse> {\n return (await this.#call(\n 'POST',\n `/executions/${encodeURIComponent(executionId)}/result`,\n result,\n )) as SubmitExecutionResultResponse\n }\n\n /** List the profiles (named Claude Code config dirs) this server declares, filtered\n * to what the caller may use. Feed a result's `name` to createSession({ profile }).\n * Servers predating profiles 404 here — catch and treat as none declared. */\n /** The profiles this caller may use, plus whether it may create new ones.\n * Each profile carries `managed: true` when it is store-backed and therefore\n * editable; profiles declared in server options are not. */\n async listProfiles(): Promise<ListProfilesResponse> {\n return (await this.#call('GET', '/profiles')) as ListProfilesResponse\n }\n\n /** One profile plus a fresh, view-only snapshot of its config directory (settings,\n * skills, agents, commands — env var names only, never values). */\n async getProfile(name: string): Promise<GetProfileResponse> {\n return (await this.#call('GET', `/profiles/${encodeURIComponent(name)}`)) as GetProfileResponse\n }\n\n /**\n * Create a managed profile. Requires a server with a profile store and a\n * principal allowed to manage profiles; 409 if the name is already taken by a\n * managed or a startup-declared profile.\n */\n async createProfile(profile: CreateProfileRequest): Promise<ProfileInfo> {\n const body = await this.#call('POST', '/profiles', profile)\n return (body as SaveProfileResponse).profile\n }\n\n /** Merge into a managed profile. The name is the route: profiles cannot be\n * renamed, since sessions and jobs are already pinned to the old one. */\n async updateProfile(name: string, patch: UpdateProfileRequest): Promise<ProfileInfo> {\n const body = await this.#call('PATCH', `/profiles/${encodeURIComponent(name)}`, patch)\n return (body as SaveProfileResponse).profile\n }\n\n /** Delete a managed profile. Startup-declared profiles are refused (403) —\n * they live in the server's options. */\n async deleteProfile(name: string): Promise<void> {\n await this.#call('DELETE', `/profiles/${encodeURIComponent(name)}`)\n }\n\n /** List an engine's on-disk sessions (for resume across server restarts).\n * Feed a result's `sessionId` to createSession({ resume }) — under a profile\n * of the same engine. `profile` names whose store to list (claude profiles →\n * the Agent SDK store, codex profiles → CODEX_HOME threads); absent, the\n * server resolves it implicitly when it declares exactly one profile, else\n * lists the Claude engine's store. */\n async listSdkSessions(params?: {\n dir?: string\n limit?: number\n offset?: number\n profile?: string\n }): Promise<SdkSessionSummary[]> {\n const search = new URLSearchParams()\n if (params?.dir) search.set('dir', params.dir)\n if (params?.limit !== undefined) search.set('limit', String(params.limit))\n if (params?.offset !== undefined) search.set('offset', String(params.offset))\n if (params?.profile) search.set('profile', params.profile)\n const qs = search.size > 0 ? `?${search.toString()}` : ''\n const body = await this.#call('GET', `/sdk-sessions${qs}`)\n return (body as { sdkSessions: SdkSessionSummary[] }).sdkSessions\n }\n\n // -- Host filesystem (requires the server to be configured with `hostFiles`) -\n\n /**\n * The host directories this server will let a client browse, and whether it\n * accepts writes. Servers without host-file access configured 404 here — catch\n * and treat as \"no file browser\", the same way `listProfiles` handles an older\n * server.\n *\n * These are operator-privileged routes: the auth key is the whole authorization\n * story, and they bypass the agent permission flow entirely. See the protocol\n * package's `HostFileRoot` for why that framing is deliberate.\n */\n async listHostRoots(): Promise<ListHostRootsResponse> {\n return (await this.#call('GET', '/fs/roots')) as ListHostRootsResponse\n }\n\n /** One host directory, not recursive. Symlinks are reported as symlinks, never\n * followed here — read one to find out whether it resolves somewhere allowed. */\n async listHostDir(path: string): Promise<ListHostDirResponse> {\n const qs = `?path=${encodeURIComponent(path)}`\n return (await this.#call('GET', `/fs/list${qs}`)) as ListHostDirResponse\n }\n\n /** Recursive fuzzy file search under one host directory — the `@file` picker's\n * query. Cheap enough to call per keystroke: build directories are skipped and\n * the walk is bounded, truncating rather than erroring. */\n async findHostFiles(path: string, query = '', limit?: number): Promise<FindHostFilesResponse> {\n const search = new URLSearchParams({ path, q: query })\n if (limit !== undefined) search.set('limit', String(limit))\n return (await this.#call('GET', `/fs/find?${search.toString()}`)) as FindHostFilesResponse\n }\n\n /** Read one host file. Binary content comes back base64-encoded; the returned\n * `hash` is what a later `writeHostFile` needs as its `expectedHash`. */\n async readHostFile(path: string): Promise<ReadHostFileResponse> {\n const qs = `?path=${encodeURIComponent(path)}`\n return (await this.#call('GET', `/fs/read${qs}`)) as ReadHostFileResponse\n }\n\n /**\n * Write one host file, conditionally — always. Pass the `hash` from the read this\n * edit is based on; a 409 means the agent (or anything else) changed the file\n * underneath you, and the edit must be rebased rather than forced. Omit\n * `expectedHash` only to create a file that does not exist yet.\n */\n async writeHostFile(request: WriteHostFileRequest): Promise<WriteHostFileResponse> {\n return (await this.#call('PUT', '/fs/write', request)) as WriteHostFileResponse\n }\n\n // -- Job queue (requires the server to be configured with `queue`) ----------\n\n /** Schedule a one-shot run. The returned job's `sessionId` (once running) can be\n * fed to `attach()` to watch the run live. */\n async createJob(request: CreateJobRequest): Promise<JobInfo> {\n const body = await this.#call('POST', '/jobs', request)\n return (body as { job: JobInfo }).job\n }\n\n async listJobs(): Promise<JobInfo[]> {\n const body = await this.#call('GET', '/jobs')\n return (body as { jobs: JobInfo[] }).jobs\n }\n\n async getJob(id: string): Promise<JobInfo> {\n const body = await this.#call('GET', `/jobs/${encodeURIComponent(id)}`)\n return (body as { job: JobInfo }).job\n }\n\n /** Cancel a queued or running job. */\n async cancelJob(id: string): Promise<JobInfo> {\n const body = await this.#call('DELETE', `/jobs/${encodeURIComponent(id)}`)\n return (body as { job: JobInfo }).job\n }\n\n async queueStats(): Promise<QueueStats> {\n const body = await this.#call('GET', '/queue')\n return (body as { stats: QueueStats }).stats\n }\n\n attach(sessionId: string, options?: AttachOptions): SessionHandle {\n return new SessionHandle(this, sessionId, options)\n }\n\n /** Stream the job queue live (requires the server to be configured with `queue`).\n * Servers without a queue refuse the socket — check REST first or expect retries. */\n attachQueue(options?: { reconnect?: boolean }): QueueHandle {\n return new QueueHandle(this, options)\n }\n\n /** @internal used by SessionHandle */\n openSocket(sessionId: string, afterSeq: number): WebSocket {\n const url =\n this.#options.buildWsUrl?.(sessionId, afterSeq) ??\n `${this.#options.baseUrl.replace(/^http/, 'ws')}/sessions/${encodeURIComponent(sessionId)}/ws?afterSeq=${afterSeq}`\n return new this.#WebSocketImpl(url)\n }\n\n /** @internal used by QueueHandle */\n openQueueSocket(): WebSocket {\n const url =\n this.#options.buildQueueWsUrl?.() ??\n `${this.#options.baseUrl.replace(/^http/, 'ws')}/queue/ws`\n return new this.#WebSocketImpl(url)\n }\n\n async #call(method: string, path: string, body?: unknown): Promise<unknown> {\n const res = await this.#fetch(`${this.#options.baseUrl}${path}`, {\n method,\n headers: {\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n ...this.#options.headers,\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n })\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n if (!res.ok) {\n throw new WorkerDeckError(payload.error ?? `${method} ${path} failed with ${res.status}`, res.status)\n }\n return payload\n }\n}\n"],"mappings":";;;;;;;;;AAqEA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA,YAAY,SAAiB,QAAgB;AAC3C,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;;;AAuClB,IAAa,gBAAb,MAA2B;CACzB;CACA;CACA;CACA;CACA,6BAAa,IAAI,KAAsD;CACvE;CACA,UAAU;CACV,WAAW;CACX,UAAoB,EAAE;CACtB;CAEA,YAAY,QAA0B,WAAmB,UAAyB,EAAE,EAAE;AACpF,QAAA,SAAe;AACf,OAAK,YAAY;AACjB,QAAA,UAAgB;GAAE,WAAW;GAAM,GAAG;GAAS;AAC/C,QAAA,UAAgB,QAAQ,YAAY;AAIpC,QAAA,eAAqB,iBAAiB,MAAA,SAAe,EAAE,EAAE;;CAG3D,IAAI,UAAkB;AACpB,SAAO,MAAA;;CAGT,GACE,MACA,UACY;EACZ,IAAI,MAAM,MAAA,UAAgB,IAAI,KAAK;AACnC,MAAI,CAAC,KAAK;AACR,yBAAM,IAAI,KAAK;AACf,SAAA,UAAgB,IAAI,MAAM,IAAI;;AAEhC,MAAI,IAAI,SAA4B;AACpC,eAAa,IAAI,OAAO,SAA4B;;;;;;CAOtD,KAAK,MAAc,eAAgC;AACjD,QAAA,UAAgB;GACd,MAAM;GACN;GACA,eAAe,eAAe,SAAS,gBAAgB,KAAA;GACxD,CAAC;;CAGJ,QAAQ,WAAmB,cAA8C;AACvE,QAAA,UAAgB;GAAE,MAAM;GAAuB;GAAW,UAAU;GAAS;GAAc,CAAC;;CAG9F,KAAK,WAAmB,SAAk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AAS,KAAK,CAAC,YAAY,mBAAmB,UAAU,CAAC,eAAe;AAC3G,SAAO,IAAI,MAAA,cAAoB,IAAI;;;CAIrC,kBAA6B;EAC3B,MAAM,MACJ,MAAA,QAAc,mBAAmB,IACjC,GAAG,MAAA,QAAc,QAAQ,QAAQ,SAAS,KAAK,CAAC;AAClD,SAAO,IAAI,MAAA,cAAoB,IAAI;;CAGrC,OAAA,KAAY,QAAgB,MAAc,MAAkC;EAC1E,MAAM,MAAM,MAAM,MAAA,MAAY,GAAG,MAAA,QAAc,UAAU,QAAQ;GAC/D;GACA,SAAS;IACP,GAAI,SAAS,KAAA,IAAY,EAAE,gBAAgB,oBAAoB,GAAG,EAAE;IACpE,GAAG,MAAA,QAAc;IAClB;GACD,MAAM,SAAS,KAAA,IAAY,KAAK,UAAU,KAAK,GAAG,KAAA;GACnD,CAAC;EACF,MAAM,UAAW,MAAM,IAAI,MAAM,CAAC,aAAa,EAAE,EAAE;AACnD,MAAI,CAAC,IAAI,GACP,OAAM,IAAI,gBAAgB,QAAQ,SAAS,GAAG,OAAO,GAAG,KAAK,eAAe,IAAI,UAAU,IAAI,OAAO;AAEvG,SAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workerdeck/client",
3
- "version": "0.7.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "Typed WorkerDeck protocol client for browsers and Node: REST session management plus a WebSocket attach with auto-reconnect and replay-from-last-seq. Uses the platform's fetch and WebSocket; zero runtime deps.",
6
6
  "license": "MIT",
@@ -17,7 +17,7 @@
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "@workerdeck/protocol": "0.7.0"
20
+ "@workerdeck/protocol": "0.11.0"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@types/node": "^22.10.0",
@@ -26,8 +26,8 @@
26
26
  "tsdown": "^0.21.10",
27
27
  "vitest": "^3.2.7",
28
28
  "ws": "^8.21.1",
29
- "@workerdeck/server": "0.7.0",
30
- "@workerdeck/core": "0.7.0"
29
+ "@workerdeck/core": "0.11.0",
30
+ "@workerdeck/server": "0.11.0"
31
31
  },
32
32
  "author": "Tobias Strebitzer",
33
33
  "repository": {