@workerdeck/client 0.23.0 → 1.1.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 +40 -324
- package/build/index.mjs +109 -333
- package/build/index.mjs.map +1 -1
- package/package.json +8 -8
package/build/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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/host-url.ts","../src/host-auth.ts","../src/index.ts"],"sourcesContent":["/**\n * Pure URL logic for gateway hosts — what an operator types, turned into the\n * `baseUrl` a `WorkerDeckClient` takes.\n *\n * Here rather than in each client because there were already two copies (the iOS\n * `Host.apiURL` and the VS Code extension's port) and a third was coming. Every\n * host that lets someone type a gateway address has to normalize it the same\n * way, or the same gateway saved on two devices is two gateways.\n */\nexport type HostUrl = { baseUrl: string }\n\n/** Normalized REST base for `WorkerDeckClient`, or undefined if unparseable. */\nexport function apiUrl(host: HostUrl): string | undefined {\n let text = host.baseUrl.trim()\n while (text.endsWith('/')) text = text.slice(0, -1)\n if (text === '') return undefined\n // A bare `mac.tailnet.ts.net:8787` is a host:port, not a scheme — tailnet\n // gateways are plain http, so that is the sane default to assume.\n if (!text.includes('://')) text = 'http://' + text\n if (!text.endsWith('/v1')) text += '/v1'\n try {\n // Validation only — the string, not the URL object, is what we keep.\n new URL(text)\n } catch {\n return undefined\n }\n return text\n}\n\n/**\n * Whether this gateway is the machine the caller runs on. Decided from the URL,\n * never by probing paths for existence — two checkouts of the same repo would\n * lie. In a remote development window the caller runs on the remote box, so\n * \"loopback\" correctly means *that* machine and its paths are real files there.\n */\nexport function isLoopbackHost(host: HostUrl): boolean {\n const api = apiUrl(host)\n if (!api) return false\n try {\n const { hostname } = new URL(api)\n return (\n hostname === '127.0.0.1' ||\n hostname === 'localhost' ||\n hostname === '::1' ||\n hostname === '[::1]'\n )\n } catch {\n return false\n }\n}\n","import type { ClientOptions } from './index.ts'\n\n/**\n * The `ClientOptions` a **browser** needs to reach a gateway that is not its own\n * origin.\n *\n * Here, beside `apiUrl`, for the same reason that is here: every host that lets\n * someone type a gateway address and a key has to present them identically, or\n * the same gateway works in one client and not another. It is browser-shaped on\n * purpose — a Node host (the VS Code extension) sends the key as a header on\n * both transports and needs none of this.\n *\n * Two transports, because a browser has no choice:\n *\n * - **REST** takes `Authorization: Bearer <key>`, like any service client.\n * - **WebSocket** takes `?key=<key>`, because a tab cannot put a header on an\n * upgrade handshake and the gateway's cookie belongs to another origin. The\n * CLI's auth accepts the key this way on upgrades *only*.\n *\n * The query-string transport is the weaker one and is worth naming: unlike a\n * header it is a permanent credential that lands in reverse-proxy access logs.\n * It is confined to the upgrade so what a leaked URL buys is one attach. If a\n * gateway later mints short-lived tickets, only the body of `buildWsUrl`\n * changes — callers of this function do not.\n */\nexport function hostAuth(options: {\n /** The gateway's API root, as `apiUrl()` returns it (ends in `/v1`). */\n baseUrl: string\n /** The operator's gateway key. Empty means an unauthenticated gateway. */\n key: string\n}): Pick<ClientOptions, 'headers' | 'buildWsUrl' | 'buildQueueWsUrl'> {\n const { baseUrl, key } = options\n if (key === '') return {}\n\n const wsRoot = baseUrl.replace(/^http/, 'ws')\n // Appended with the same `?`/`&` care the default URLs need: the session\n // socket already carries `afterSeq`, the queue socket carries nothing.\n const withKey = (url: string): string =>\n `${url}${url.includes('?') ? '&' : '?'}key=${encodeURIComponent(key)}`\n\n return {\n headers: { authorization: `Bearer ${key}` },\n buildWsUrl: (sessionId, afterSeq) =>\n withKey(`${wsRoot}/sessions/${encodeURIComponent(sessionId)}/ws?afterSeq=${afterSeq}`),\n buildQueueWsUrl: () => withKey(`${wsRoot}/queue/ws`),\n }\n}\n","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 ToolResultBlock,\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?: (\n sessionId: string,\n afterSeq: number,\n truncateResults?: boolean,\n imageRefs?: boolean,\n ) => 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 * Ask the gateway to replay an oversized tool result as its **head**, with\n * `truncated`/`total_chars` on the block and the whole thing one\n * {@link WorkerDeckClient.toolResult} call away. Measured after shipping, that\n * is a **0.3%** cut on a real session, not the 68% it was designed against —\n * the projection had counted base64 as text. The mechanism is right and the\n * bytes were elsewhere; see {@link AttachOptions.imageRefs}.\n *\n * Default off, and the default must stay off: **only the unit that renders may\n * ask for it**. `client` and `react` are separate packages an embedder can\n * skew, and a caller that asked for heads without knowing how to fetch the\n * rest would show one as though it were the whole result — the silent lie this\n * rule family exists to prevent. `useClaudeSession` sets it; nothing else here\n * does. Live events are never affected.\n */\n truncateResults?: boolean\n /**\n * Ask the gateway to deliver a tool result's base64 image parts as\n * `image_ref` addresses, their bytes one {@link\n * WorkerDeckClient.toolResultImage} call away.\n *\n * This is where the bytes actually were: measured across 214 local sessions,\n * **91% of all tool-result payload is base64 no client renders** — 489 MB\n * against 44 MB of text, two thirds of it from `Read` looking at a PNG. One\n * session's attach fell from 4,550 KB to 771 KB with no image in it.\n *\n * Default off under the same rule as {@link AttachOptions.truncateResults} —\n * only the unit that renders may ask — and its **own** flag rather than a\n * widening of that one, because this family's \"additive at protocol 7\"\n * argument rests on a client that never asked being unable to receive one, by\n * construction rather than by release archaeology.\n *\n * Unlike truncation this **also applies to live events**. The render path is\n * ref-then-fetch, so bytes arriving live would only be discarded or pinned in\n * client state.\n */\n imageRefs?: 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 /**\n * Reset the conversation in place: same session, empty context. The server\n * answers with a `conversation_reset` event.\n *\n * Gate the affordance on `EngineCapabilities.clearContext` (absent = false)\n * rather than calling this blindly — an engine or a server that cannot do it\n * answers with an error frame, which is the wrong way for a user to find out.\n */\n clearContext(): void {\n this.#sendFrame({ type: 'clear_context' })\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(\n this.sessionId,\n this.#lastSeq,\n this.#options.truncateResults,\n this.#options.imageRefs,\n )\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 /**\n * Stable identity of the (gateway, principal) pair this client speaks as:\n * the base URL plus the auth headers it sends, order-insensitively.\n *\n * Exists for client-side caches that must survive the client *instance*\n * being rebuilt (a `useMemo` recreating it when a view switches gateways)\n * without ever sharing an entry across gateways — a session id is unique\n * only within one — or across credentials. Auth that rides outside\n * `headers` (a same-origin cookie, a fetch shim adding the key host-side)\n * is chosen per origin in every such host, so the base URL still separates\n * principals there; an embedder whose principal varies some other way on\n * one base URL should not key anything on this.\n */\n get identityKey(): string {\n const headers = Object.entries(this.#options.headers ?? {}).map(\n ([name, value]) => [name.toLowerCase(), value] as const,\n )\n headers.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return JSON.stringify([this.#options.baseUrl, headers])\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 /**\n * The URL behind a `ProjectIcon.image`. Session-scoped, like\n * {@link producedFileUrl}: the fetch rides the same `canSee` gate as every\n * other `/sessions/:id/*` route, and it takes **no path** — the gateway\n * serves whatever its own discovery resolved for this session's cwd.\n */\n projectIconUrl(sessionId: string): string {\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/project/icon`\n }\n\n /**\n * Fetch a project icon's bytes.\n *\n * Here rather than left to each client for the reason `readProducedFile`\n * exists, plus one this route makes sharper: a VS Code webview has **no\n * external `connect-src` at all**, so it cannot point an `<img src>` at a\n * gateway even in principle — the bytes have to come back through a bridged\n * fetch, which is exactly what this wraps. Three clients building the same\n * URL from `baseUrl` was the other half of the argument.\n *\n * Cache the result by `ProjectIcon.image.hash`, never by session: two\n * sessions in one project serve identical bytes, and the hash is on the wire\n * precisely so a client fetches once per project.\n *\n * A 404 is the uniform \"no icon\" — no project, a glyph-only project, or an\n * icon the gateway refused. It is deliberately not distinguishable, so treat\n * it as \"draw no image\", never as an error worth reporting.\n */\n async projectIcon(sessionId: string): Promise<Blob> {\n const res = await this.#fetch(this.projectIconUrl(sessionId), {\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 ?? `project icon 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(\n sessionId: string,\n afterSeq: number,\n truncateResults = false,\n imageRefs = false,\n ): WebSocket {\n // A third *optional* parameter rather than an options object, so every\n // existing `buildWsUrl` implementation still typechecks. The hazard worth\n // naming: a custom one that ignores it yields a full replay — safe only\n // because every client keys its rendering off the server's own `truncated`\n // marker and never off what it asked for.\n const query =\n `afterSeq=${afterSeq}` +\n (truncateResults ? '&truncateResults=1' : '') +\n (imageRefs ? '&imageRefs=1' : '')\n const url =\n this.#options.buildWsUrl?.(sessionId, afterSeq, truncateResults, imageRefs) ??\n `${this.#options.baseUrl.replace(/^http/, 'ws')}/sessions/${encodeURIComponent(sessionId)}/ws?${query}`\n return new this.#WebSocketImpl(url)\n }\n\n /**\n * The whole of a tool result whose replay delivered only its head.\n *\n * `toolUseId` is required and the gateway verifies it against the block: a\n * woken dormant session has a fresh log with fresh seqs, so a `sourceSeq`\n * cached across a gateway restart can name a different event, and being handed\n * another tool's output under the row you pressed is the exact failure this\n * feature exists to remove. A 404 here means \"ask again with a fresh attach\",\n * not \"empty\".\n */\n async toolResult(\n sessionId: string,\n seq: number,\n toolUseId: string,\n options?: { imageRefs?: boolean },\n ): Promise<{ seq: number; toolUseId: string; content: ToolResultBlock['content']; isError: boolean }> {\n // `imageRefs` matters here for the same reason it does on the socket: without\n // it, pressing \"show everything\" on an image-bearing result ships every\n // screenshot's base64 in the JSON, and the reducer keeps only the text.\n return (await this.#call(\n 'GET',\n `/sessions/${encodeURIComponent(sessionId)}/events/${seq}/result?toolUseId=${encodeURIComponent(toolUseId)}` +\n (options?.imageRefs ? '&imageRefs=1' : ''),\n )) as { seq: number; toolUseId: string; content: ToolResultBlock['content']; isError: boolean }\n }\n\n /**\n * One image part's bytes, addressed by the `image_ref` a replay delivered in\n * its place.\n *\n * A `Blob` and not a URL, and that is the whole reason this method exists: an\n * `<img src>` pointing at the gateway carries a credential in exactly one of\n * this project's four clients (the dashboard's same-origin implicit host,\n * where the cookie rides along). Everywhere else — an added cross-origin\n * gateway on a Bearer header, the VS Code webview whose every byte crosses a\n * postMessage bridge, iOS — the URL is unauthenticated and the picture is a\n * broken icon. Fetched rather than pointed at, then handed to\n * `URL.createObjectURL`; `readProducedFile` is the shipped precedent.\n *\n * A 404 means \"ask again with a fresh attach\": a woken dormant session has a\n * fresh log with fresh seqs, and the gateway refuses a stale address rather\n * than serving another call's pixels under the row you are looking at.\n */\n async toolResultImage(\n sessionId: string,\n seq: number,\n toolUseId: string,\n partIndex: number,\n ): Promise<Blob> {\n const path =\n `/sessions/${encodeURIComponent(sessionId)}/events/${seq}/result` +\n `?toolUseId=${encodeURIComponent(toolUseId)}&part=${partIndex}`\n const res = await this.#fetch(`${this.#options.baseUrl}${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(\n payload.error ?? `image part request failed with ${res.status}`,\n res.status,\n )\n }\n return await res.blob()\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\nexport { apiUrl, isLoopbackHost } from './host-url.ts'\nexport type { HostUrl }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A,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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/lib/emitter.ts","../src/session-handle.ts","../src/queue-handle.ts","../src/host-url.ts","../src/host-auth.ts","../src/index.ts"],"sourcesContent":["export type Listener<T> = (payload: T) => void\n\n/**\n * The handles' listener registry. A throwing listener must never stop the ones queued behind it:\n * these fire from a socket callback, where an escaping error would take the connection with it.\n */\nexport class Emitter<Events> {\n #listeners = new Map<keyof Events, Set<Listener<never>>>()\n\n on<K extends keyof Events>(kind: K, listener: Listener<Events[K]>): () => 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 emit<K extends keyof Events>(kind: K, payload: Events[K]): void {\n const set = this.#listeners.get(kind)\n if (!set) {\n return\n }\n for (const listener of set) {\n try {\n ;(listener as Listener<Events[K]>)(payload)\n } catch {}\n }\n }\n}\n\n/** 500ms doubling from a zero-based attempt count, capped at 10s. */\nexport function reconnectDelay(retries: number): number {\n return Math.min(500 * 2 ** retries, 10_000)\n}\n","import type {\n AttachedFrame,\n ClientFrame,\n PermissionMode,\n ServerFrame,\n SessionEvent,\n ToolCallRequestFrame,\n ToolExecutionOutput,\n} from '@workerdeck/protocol'\nimport { Emitter, reconnectDelay, type Listener } from './lib/emitter.ts'\nimport type { WorkerDeckClient } from './index.ts'\n\nexport type AttachOptions = {\n afterSeq?: number\n reconnect?: boolean\n truncateResults?: boolean\n imageRefs?: boolean\n}\n\nexport type SessionHandleEvents = {\n attached: AttachedFrame\n event: SessionEvent\n protocolError: string\n connectionChange: boolean\n reconnectAttempt: number\n toolCallRequest: ToolCallRequestFrame\n toolCallCanceled: { executionId: string; reason: string }\n}\n\nexport class SessionHandle {\n readonly sessionId: string\n #client: WorkerDeckClient\n #options: Required<Pick<AttachOptions, 'reconnect'>> & AttachOptions\n #ws: WebSocket | undefined\n #events = new Emitter<SessionHandleEvents>()\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 a same-tick detach (React StrictMode's dev mount) never closes a WebSocket mid-upgrade, which breaks proxies.\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>(kind: K, listener: Listener<SessionHandleEvents[K]>): () => void {\n return this.#events.on(kind, listener)\n }\n\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 clearContext(): void {\n this.#sendFrame({ type: 'clear_context' })\n }\n\n setPermissionMode(mode: PermissionMode): void {\n this.#sendFrame({ type: 'set_permission_mode', mode })\n }\n\n setModel(model?: string): void {\n this.#sendFrame({ type: 'set_model', model })\n }\n\n sendToolCallResult(executionId: string, output: ToolExecutionOutput, logs?: string[]): void {\n this.#sendFrame({ type: 'tool_call_result', executionId, output, logs })\n }\n\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 closeSession(): void {\n this.#sendFrame({ type: 'close' })\n this.detach()\n }\n\n reconnectNow(): void {\n if (this.#closed || (this.#ws && this.#ws.readyState === 1)) {\n return\n }\n clearTimeout(this.#connectTimer)\n this.#retries = 0\n this.#connect()\n }\n\n detach(): void {\n this.#closed = true\n clearTimeout(this.#connectTimer)\n this.#ws?.close()\n this.#ws = undefined\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) {\n this.#ws.send(payload)\n } else {\n this.#outbox.push(payload)\n }\n }\n\n #connect(): void {\n if (this.#closed) {\n return\n }\n const ws = this.#client.openSocket(this.sessionId, this.#lastSeq, this.#options.truncateResults, this.#options.imageRefs)\n this.#ws = ws\n ws.onopen = () => {\n this.#retries = 0\n this.#events.emit('connectionChange', true)\n for (const payload of this.#outbox.splice(0)) {\n ws.send(payload)\n }\n }\n ws.onmessage = (msg: MessageEvent) => {\n const frame = JSON.parse(String(msg.data)) as ServerFrame\n if (frame.type === 'attached') {\n this.#events.emit('attached', frame)\n } else if (frame.type === 'event') {\n if (frame.event.seq <= this.#lastSeq) {\n return\n }\n this.#lastSeq = frame.event.seq\n this.#events.emit('event', frame.event)\n } else if (frame.type === 'tool_call_request') {\n this.#events.emit('toolCallRequest', frame)\n } else if (frame.type === 'tool_call_canceled') {\n this.#events.emit('toolCallCanceled', { executionId: frame.executionId, reason: frame.reason })\n } else if (frame.type === 'protocol_error') {\n this.#events.emit('protocolError', frame.message)\n }\n }\n ws.onclose = () => {\n this.#events.emit('connectionChange', false)\n if (this.#closed || !this.#options.reconnect) {\n return\n }\n const delay = reconnectDelay(this.#retries++)\n this.#events.emit('reconnectAttempt', this.#retries)\n this.#connectTimer = setTimeout(() => this.#connect(), delay)\n }\n ws.onerror = () => {}\n }\n}\n","import type { JobEvent, QueueServerFrame, QueueStats } from '@workerdeck/protocol'\nimport { Emitter, reconnectDelay, type Listener } from './lib/emitter.ts'\nimport type { WorkerDeckClient } from './index.ts'\n\nexport type QueueHandleEvents = {\n attached: QueueStats\n event: JobEvent\n stats: QueueStats\n connectionChange: boolean\n}\n\nexport class QueueHandle {\n #client: WorkerDeckClient\n #reconnect: boolean\n #ws: WebSocket | undefined\n #events = new Emitter<QueueHandleEvents>()\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>(kind: K, listener: Listener<QueueHandleEvents[K]>): () => void {\n return this.#events.on(kind, listener)\n }\n\n detach(): void {\n this.#closed = true\n clearTimeout(this.#connectTimer)\n this.#ws?.close()\n this.#ws = undefined\n }\n\n #connect(): void {\n if (this.#closed) {\n return\n }\n const ws = this.#client.openQueueSocket()\n this.#ws = ws\n ws.onopen = () => {\n this.#retries = 0\n this.#events.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.#events.emit('attached', frame.stats)\n this.#events.emit('stats', frame.stats)\n } else if (frame.type === 'job_event') {\n this.#events.emit('event', frame.event)\n } else if (frame.type === 'queue_stats') {\n this.#events.emit('stats', frame.stats)\n }\n }\n ws.onclose = () => {\n this.#events.emit('connectionChange', false)\n if (this.#closed || !this.#reconnect) {\n return\n }\n const delay = reconnectDelay(this.#retries++)\n this.#connectTimer = setTimeout(() => this.#connect(), delay)\n }\n ws.onerror = () => {}\n }\n}\n","export type HostUrl = { baseUrl: string }\n\nexport function apiUrl(host: HostUrl): string | undefined {\n let text = host.baseUrl.trim()\n while (text.endsWith('/')) {\n text = text.slice(0, -1)\n }\n if (text === '') {\n return undefined\n }\n // A bare `mac.tailnet.ts.net:8787` is a host:port, not a scheme, and tailnet gateways are plain http.\n if (!text.includes('://')) {\n text = 'http://' + text\n }\n if (!text.endsWith('/v1')) {\n text += '/v1'\n }\n try {\n // Validation only — the string, not the URL object, is what we keep.\n new URL(text)\n } catch {\n return undefined\n }\n return text\n}\n\nexport function isLoopbackHost(host: HostUrl): boolean {\n const api = apiUrl(host)\n if (!api) {\n return false\n }\n try {\n const { hostname } = new URL(api)\n return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1' || hostname === '[::1]'\n } catch {\n return false\n }\n}\n","import type { ClientOptions } from './index.ts'\n\nexport function hostAuth(options: { baseUrl: string; key: string }): Pick<ClientOptions, 'headers' | 'buildWsUrl' | 'buildQueueWsUrl'> {\n const { baseUrl, key } = options\n if (key === '') {\n return {}\n }\n\n const wsRoot = baseUrl.replace(/^http/, 'ws')\n const withKey = (url: string): string => `${url}${url.includes('?') ? '&' : '?'}key=${encodeURIComponent(key)}`\n\n return {\n headers: { authorization: `Bearer ${key}` },\n buildWsUrl: (sessionId, afterSeq) => withKey(`${wsRoot}/sessions/${encodeURIComponent(sessionId)}/ws?afterSeq=${afterSeq}`),\n buildQueueWsUrl: () => withKey(`${wsRoot}/queue/ws`),\n }\n}\n","import type {\n CreateJobRequest,\n CreateProfileRequest,\n CreateSessionRequest,\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 ProfileInfo,\n QueueStats,\n ResolvePermissionRequest,\n UpdateSessionRequest,\n SubmitExecutionResultRequest,\n SubmitExecutionResultResponse,\n SaveProfileResponse,\n SdkSessionSummary,\n SessionFileInfo,\n SessionInfo,\n UpdateProfileRequest,\n ToolResultBlock,\n} from '@workerdeck/protocol'\nimport { SessionHandle, type AttachOptions } from './session-handle.ts'\nimport { QueueHandle } from './queue-handle.ts'\n\nexport type FetchBody = NonNullable<NonNullable<Parameters<typeof fetch>[1]>['body']>\n\nexport type ClientOptions = {\n baseUrl: string\n headers?: Record<string, string>\n buildWsUrl?: (sessionId: string, afterSeq: number, truncateResults?: boolean, imageRefs?: boolean) => string\n buildQueueWsUrl?: () => string\n WebSocketImpl?: typeof WebSocket\n fetchImpl?: typeof fetch\n}\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 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 get identityKey(): string {\n const headers = Object.entries(this.#options.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value] as const)\n headers.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return JSON.stringify([this.#options.baseUrl, headers])\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 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 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 async fetchSessionFile(sessionId: string, path: string): Promise<string> {\n const res = await this.#callRaw(this.sessionFileUrl(sessionId, path), { headers: this.#options.headers }, 'GET file failed')\n return await res.text()\n }\n\n async uploadAttachment(sessionId: string, file: { name: string; mediaType: string; data: FetchBody }): Promise<MessageAttachment> {\n const url = `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/attachments?name=${encodeURIComponent(file.name)}`\n const res = await this.#callRaw(\n url,\n { method: 'POST', headers: { ...this.#options.headers, 'content-type': file.mediaType }, body: file.data },\n 'upload failed',\n )\n return ((await res.json()) as UploadAttachmentResponse).attachment\n }\n\n attachmentUrl(sessionId: string, attachmentId: string): string {\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/attachments/${encodeURIComponent(attachmentId)}`\n }\n\n producedFileUrl(sessionId: string, fileId: string): string {\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/produced/${encodeURIComponent(fileId)}`\n }\n\n async readProducedFile(sessionId: string, fileId: string): Promise<Blob> {\n const res = await this.#callRaw(\n this.producedFileUrl(sessionId, fileId),\n { headers: { ...this.#options.headers } },\n 'produced file request failed',\n )\n return await res.blob()\n }\n\n projectIconUrl(sessionId: string): string {\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/project/icon`\n }\n\n async projectIcon(sessionId: string): Promise<Blob> {\n const res = await this.#callRaw(\n this.projectIconUrl(sessionId),\n { headers: { ...this.#options.headers } },\n 'project icon request failed',\n )\n return await res.blob()\n }\n\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 async mcpServerAction(sessionId: string, serverName: string, action: McpServerActionRequest['action']): Promise<McpServerStatusInfo[]> {\n const body = await this.#call('POST', `/sessions/${encodeURIComponent(sessionId)}/mcp/${encodeURIComponent(serverName)}`, { action })\n return (body as McpServersResponse).servers\n }\n\n sessionFileUrl(sessionId: string, path: string): string {\n const encoded = path.split('/').filter(Boolean).map(encodeURIComponent).join('/')\n return `${this.#options.baseUrl}/sessions/${encodeURIComponent(sessionId)}/files/${encoded}`\n }\n\n async resolvePermission(sessionId: string, requestId: string, decision: ResolvePermissionRequest): Promise<void> {\n await this.#call('POST', `/sessions/${encodeURIComponent(sessionId)}/permissions/${encodeURIComponent(requestId)}`, decision)\n }\n\n async submitExecutionResult(executionId: string, result: SubmitExecutionResultRequest): Promise<SubmitExecutionResultResponse> {\n return (await this.#call('POST', `/executions/${encodeURIComponent(executionId)}/result`, result)) as SubmitExecutionResultResponse\n }\n\n async listProfiles(): Promise<ListProfilesResponse> {\n return (await this.#call('GET', '/profiles')) as ListProfilesResponse\n }\n\n async getProfile(name: string): Promise<GetProfileResponse> {\n return (await this.#call('GET', `/profiles/${encodeURIComponent(name)}`)) as GetProfileResponse\n }\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 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 async deleteProfile(name: string): Promise<void> {\n await this.#call('DELETE', `/profiles/${encodeURIComponent(name)}`)\n }\n\n async listSdkSessions(params?: { dir?: string; limit?: number; offset?: number; profile?: string }): Promise<SdkSessionSummary[]> {\n const search = new URLSearchParams()\n if (params?.dir) {\n search.set('dir', params.dir)\n }\n if (params?.limit !== undefined) {\n search.set('limit', String(params.limit))\n }\n if (params?.offset !== undefined) {\n search.set('offset', String(params.offset))\n }\n if (params?.profile) {\n search.set('profile', params.profile)\n }\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 async listHostRoots(): Promise<ListHostRootsResponse> {\n return (await this.#call('GET', '/fs/roots')) as ListHostRootsResponse\n }\n\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 async findHostFiles(path: string, query = '', limit?: number): Promise<FindHostFilesResponse> {\n const search = new URLSearchParams({ path, q: query })\n if (limit !== undefined) {\n search.set('limit', String(limit))\n }\n return (await this.#call('GET', `/fs/find?${search.toString()}`)) as FindHostFilesResponse\n }\n\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 async writeHostFile(request: WriteHostFileRequest): Promise<WriteHostFileResponse> {\n return (await this.#call('PUT', '/fs/write', request)) as WriteHostFileResponse\n }\n\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 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 attachQueue(options?: { reconnect?: boolean }): QueueHandle {\n return new QueueHandle(this, options)\n }\n\n openSocket(sessionId: string, afterSeq: number, truncateResults = false, imageRefs = false): WebSocket {\n const query = `afterSeq=${afterSeq}` + (truncateResults ? '&truncateResults=1' : '') + (imageRefs ? '&imageRefs=1' : '')\n const url =\n this.#options.buildWsUrl?.(sessionId, afterSeq, truncateResults, imageRefs) ??\n `${this.#options.baseUrl.replace(/^http/, 'ws')}/sessions/${encodeURIComponent(sessionId)}/ws?${query}`\n return new this.#WebSocketImpl(url)\n }\n\n async toolResult(\n sessionId: string,\n seq: number,\n toolUseId: string,\n options?: { imageRefs?: boolean },\n ): Promise<{ seq: number; toolUseId: string; content: ToolResultBlock['content']; isError: boolean }> {\n return (await this.#call(\n 'GET',\n `/sessions/${encodeURIComponent(sessionId)}/events/${seq}/result?toolUseId=${encodeURIComponent(toolUseId)}` +\n (options?.imageRefs ? '&imageRefs=1' : ''),\n )) as { seq: number; toolUseId: string; content: ToolResultBlock['content']; isError: boolean }\n }\n\n async toolResultImage(sessionId: string, seq: number, toolUseId: string, partIndex: number): Promise<Blob> {\n const path =\n `/sessions/${encodeURIComponent(sessionId)}/events/${seq}/result` + `?toolUseId=${encodeURIComponent(toolUseId)}&part=${partIndex}`\n const res = await this.#callRaw(\n `${this.#options.baseUrl}${path}`,\n { headers: { ...this.#options.headers } },\n 'image part request failed',\n )\n return await res.blob()\n }\n\n openQueueSocket(): WebSocket {\n const url = this.#options.buildQueueWsUrl?.() ?? `${this.#options.baseUrl.replace(/^http/, 'ws')}/queue/ws`\n return new this.#WebSocketImpl(url)\n }\n\n /** The byte-serving routes' shared failure arm: `#call` owns the same rule for JSON routes. */\n async #callRaw(url: string, init: NonNullable<Parameters<typeof fetch>[1]>, failure: string): Promise<Response> {\n const res = await this.#fetch(url, init)\n if (!res.ok) {\n const payload = (await res.json().catch(() => ({}))) as { error?: string }\n throw new WorkerDeckError(payload.error ?? `${failure} with ${res.status}`, res.status)\n }\n return res\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\nexport { SessionHandle } from './session-handle.ts'\nexport type { AttachOptions, SessionHandleEvents } from './session-handle.ts'\nexport { QueueHandle } from './queue-handle.ts'\nexport type { QueueHandleEvents } from './queue-handle.ts'\nexport { apiUrl, isLoopbackHost } from './host-url.ts'\nexport type { HostUrl } from './host-url.ts'\nexport { hostAuth } from './host-auth.ts'\n"],"mappings":";;;;;AAMA,IAAa,UAAb,MAA6B;CAC3B,6BAAa,IAAI,IAAwC;CAEzD,GAA2B,MAAS,UAA2C;EAC7E,IAAI,MAAM,KAAK,WAAW,IAAI,IAAI;EAClC,IAAI,CAAC,KAAK;GACR,sBAAM,IAAI,IAAI;GACd,KAAK,WAAW,IAAI,MAAM,GAAG;EAC/B;EACA,IAAI,IAAI,QAA2B;EACnC,aAAa,IAAI,OAAO,QAA2B;CACrD;CAEA,KAA6B,MAAS,SAA0B;EAC9D,MAAM,MAAM,KAAK,WAAW,IAAI,IAAI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,IAAI,MAAM;EAEtG,OAAO;CACT;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workerdeck/client",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.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,17 +17,17 @@
|
|
|
17
17
|
}
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@workerdeck/protocol": "
|
|
20
|
+
"@workerdeck/protocol": "1.1.0"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
-
"@types/node": "^
|
|
23
|
+
"@types/node": "^26.4.0",
|
|
24
24
|
"@types/ws": "^8.18.1",
|
|
25
25
|
"rimraf": "^6.1.3",
|
|
26
|
-
"tsdown": "^0.
|
|
27
|
-
"vitest": "^
|
|
28
|
-
"ws": "^8.21.
|
|
29
|
-
"@workerdeck/core": "
|
|
30
|
-
"@workerdeck/server": "
|
|
26
|
+
"tsdown": "^0.22.14",
|
|
27
|
+
"vitest": "^4.1.11",
|
|
28
|
+
"ws": "^8.21.3",
|
|
29
|
+
"@workerdeck/core": "1.1.0",
|
|
30
|
+
"@workerdeck/server": "1.1.0"
|
|
31
31
|
},
|
|
32
32
|
"author": "Tobias Strebitzer",
|
|
33
33
|
"repository": {
|