codai-sdk 0.68.0 → 0.69.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/dist/index.d.ts +689 -10
- package/dist/index.js +76 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["base64ToBytes","filePath","decodeBase64","abortableSleep","abortableSleep","path","abortableSleep","path","path","path","path","abortableSleep","BASE","abortableSleep","OPEN","path","abortableSleep","abortableSleep","enc","one","one","one"],"sources":["../src/http.ts","../src/resources/_shared.ts","../src/resources/account.ts","../src/resources/agents.ts","../src/resources/audio.ts","../src/resources/billing.ts","../src/resources/cards.ts","../src/resources/chat.ts","../src/resources/devices.ts","../src/resources/embeddings.ts","../src/resources/environments.ts","../src/resources/health.ts","../src/resources/hosts.ts","../src/resources/assets.ts","../src/resources/images.ts","../src/resources/media.ts","../src/resources/documents.ts","../src/resources/exports.ts","../src/resources/creatives.ts","../src/resources/brand-kits.ts","../src/resources/templates.ts","../src/resources/productions.ts","../src/resources/media-ops.ts","../src/resources/lyrics.ts","../src/resources/jam.ts","../src/resources/batches.ts","../src/resources/shares.ts","../src/resources/voice-revocations.ts","../src/resources/vault.ts","../src/resources/abuse-reports.ts","../src/resources/provenance.ts","../src/resources/messages.ts","../src/resources/models.ts","../src/resources/orgs.ts","../src/resources/projects.ts","../src/resources/realtime.ts","../src/resources/referrals.ts","../src/resources/resolve.ts","../src/resources/responses.ts","../src/resources/sessions.ts","../src/resources/settings.ts","../src/resources/os-gate.ts","../src/resources/sfx.ts","../src/resources/system-one.ts","../src/resources/tasks.ts","../src/resources/triggers.ts","../src/resources/prompts.ts","../src/resources/schedules.ts","../src/resources/lists.ts","../src/resources/memory.ts","../src/resources/sandboxes.ts","../src/resources/transcripts.ts","../src/resources/tokens.ts","../src/resources/tools.ts","../src/resources/research.ts","../src/resources/usage-keys.ts","../src/resources/verify.ts","../src/operations.ts","../src/resources/apps.ts","../src/index.ts"],"sourcesContent":["/**\n * Shared HTTP layer for every resource: base URL, bearer auth, `X-Codai-*`\n * extension headers, retries, timeouts, JSON + SSE helpers and the\n * `CodaiError` mapping of the gateway error envelope.\n */\n\nimport type { components } from './generated/gateway';\n\nexport type ErrorEnvelope = components['schemas']['Error'];\nexport type ErrorCode = ErrorEnvelope['error']['code'];\n\nexport class CodaiError extends Error {\n /** Stable gateway error code (`invalid_api_key`, `rate_limit_exceeded`, …) when the body was an error envelope. */\n readonly code: ErrorCode | null;\n /** `x-codai-trace-id` (or `x-request-id`) of the failed response, when present. */\n readonly requestId: string | null;\n /** Seconds to wait before retrying, from `Retry-After` on 429s. */\n readonly retryAfter: number | null;\n\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: unknown,\n meta: { code?: ErrorCode | null; requestId?: string | null; retryAfter?: number | null } = {},\n ) {\n super(message);\n this.name = 'CodaiError';\n this.code = meta.code ?? extractCode(body);\n this.requestId = meta.requestId ?? null;\n this.retryAfter = meta.retryAfter ?? null;\n }\n}\n\nfunction extractCode(body: unknown): ErrorCode | null {\n if (body && typeof body === 'object') {\n const err = (body as { error?: { code?: unknown } }).error;\n if (err && typeof err === 'object' && typeof err.code === 'string')\n return err.code as ErrorCode;\n }\n return null;\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (body && typeof body === 'object') {\n const err = (body as { error?: { message?: unknown } }).error;\n if (err && typeof err === 'object' && typeof err.message === 'string') return err.message;\n }\n return null;\n}\n\nconst RETRYABLE = new Set([429, 500, 502, 503, 504]);\n\n/**\n * Per-request `X-Codai-*` extension headers. Every field maps 1:1 to the\n * request header of the same name (`effort` → `x-codai-effort`). Values are\n * sent verbatim; booleans become `1` / `0`.\n */\nexport interface CodaiRequestExtensions {\n /** `x-codai-session-id` — groups requests of one conversation. */\n sessionId?: string;\n /** `x-request-id` — echoed as `x-codai-trace-id`. */\n requestId?: string;\n /** `x-codai-effort` */\n effort?: 'minimal' | 'low' | 'medium' | 'high' | 'max';\n /** `x-codai-thinking` */\n thinking?: boolean;\n /** `x-codai-thinking-budget` */\n thinkingBudget?: number;\n /** `x-codai-thinking-pin` */\n thinkingPin?: boolean;\n /** `x-codai-cache` (`false` disables caching on direct model ids). */\n cache?: boolean;\n /** `x-codai-no-task` */\n noTask?: boolean;\n /** `x-codai-task-id` */\n taskId?: string;\n /** `x-codai-task-outcome` */\n taskOutcome?: 'pass' | 'fail';\n /** `x-codai-task-evidence` */\n taskEvidence?: 'exec_verdict' | 'reexec';\n /** `x-codai-client` */\n client?: string;\n /** `x-codai-incognito` */\n incognito?: boolean;\n /** `x-codai-no-recall` */\n noRecall?: boolean;\n /** `x-codai-proven-only` */\n provenOnly?: boolean;\n /** `x-codai-new-session` */\n newSession?: boolean;\n /** `x-codai-repo` */\n repo?: string;\n /** `x-codai-agent-id` */\n agentId?: string;\n /** `x-codai-disable-subagents` */\n disableSubagents?: boolean;\n /** `x-codai-mode: agent` */\n mode?: 'agent';\n /** `x-codai-server-tools` */\n serverTools?: boolean;\n /** `x-codai-orchestrate` */\n orchestrate?: boolean;\n /** `x-codai-cascade` */\n cascade?: 'verify';\n /** `x-codai-best-of` (number or `off`). */\n bestOf?: number | 'off';\n /** `x-codai-best-of-depth` */\n bestOfDepth?: number;\n /** `x-codai-reflect` */\n reflect?: boolean;\n /** `x-codai-step-verify` */\n stepVerify?: boolean;\n /** `x-codai-plan` */\n plan?: boolean;\n /** `x-codai-consensus` */\n consensus?: boolean;\n /** `x-codai-compact` (`'auto'` and `true` both send `1`). */\n compact?: boolean | 'auto';\n /** `x-codai-retrieval` */\n retrieval?: boolean;\n /** `x-codai-heuristics` */\n heuristics?: boolean;\n /** `x-codai-identity` */\n identity?: 'on' | 'off' | 'shadow';\n /** `x-codai-playbook` */\n playbook?: string;\n /** `x-codai-no-playbook` */\n noPlaybook?: boolean;\n /** `x-codai-debug` */\n debug?: boolean;\n /** `x-codai-device` — shared-sessions / hosts device UUID. */\n device?: string;\n /** `x-codai-device-name` */\n deviceName?: string;\n /** `x-codai-device-platform` */\n devicePlatform?: 'android' | 'ios' | 'web' | 'desktop' | 'cli' | 'agent' | 'wear' | 'vscode';\n /** `x-codai-push-token` */\n pushToken?: string;\n /** `x-codai-share-token` */\n shareToken?: string;\n /**\n * `Idempotency-Key` — billed codai Studio POSTs (videos, music, renders, timelines, documents, creatives, batches):\n * a retry with the same key and body replays the first answer instead of charging twice (24 h).\n */\n idempotencyKey?: string;\n /** Escape hatch: any additional raw headers. */\n headers?: Record<string, string>;\n}\n\nconst EXTENSION_HEADERS: Record<Exclude<keyof CodaiRequestExtensions, 'headers'>, string> = {\n sessionId: 'x-codai-session-id',\n requestId: 'x-request-id',\n effort: 'x-codai-effort',\n thinking: 'x-codai-thinking',\n thinkingBudget: 'x-codai-thinking-budget',\n thinkingPin: 'x-codai-thinking-pin',\n cache: 'x-codai-cache',\n noTask: 'x-codai-no-task',\n taskId: 'x-codai-task-id',\n taskOutcome: 'x-codai-task-outcome',\n taskEvidence: 'x-codai-task-evidence',\n client: 'x-codai-client',\n incognito: 'x-codai-incognito',\n noRecall: 'x-codai-no-recall',\n provenOnly: 'x-codai-proven-only',\n newSession: 'x-codai-new-session',\n repo: 'x-codai-repo',\n agentId: 'x-codai-agent-id',\n disableSubagents: 'x-codai-disable-subagents',\n mode: 'x-codai-mode',\n serverTools: 'x-codai-server-tools',\n orchestrate: 'x-codai-orchestrate',\n cascade: 'x-codai-cascade',\n bestOf: 'x-codai-best-of',\n bestOfDepth: 'x-codai-best-of-depth',\n reflect: 'x-codai-reflect',\n stepVerify: 'x-codai-step-verify',\n plan: 'x-codai-plan',\n consensus: 'x-codai-consensus',\n compact: 'x-codai-compact',\n retrieval: 'x-codai-retrieval',\n heuristics: 'x-codai-heuristics',\n identity: 'x-codai-identity',\n playbook: 'x-codai-playbook',\n noPlaybook: 'x-codai-no-playbook',\n debug: 'x-codai-debug',\n device: 'x-codai-device',\n deviceName: 'x-codai-device-name',\n devicePlatform: 'x-codai-device-platform',\n pushToken: 'x-codai-push-token',\n shareToken: 'x-codai-share-token',\n idempotencyKey: 'Idempotency-Key',\n};\n\n/** Translate an extensions bag into raw `X-Codai-*` headers. Exported for tests. */\nexport function extensionHeaders(ext: CodaiRequestExtensions | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!ext) return out;\n for (const [key, header] of Object.entries(EXTENSION_HEADERS) as Array<\n [Exclude<keyof CodaiRequestExtensions, 'headers'>, string]\n >) {\n const value = ext[key];\n if (value === undefined || value === null) continue;\n if (typeof value === 'boolean') out[header] = value ? '1' : '0';\n else if (key === 'compact' && value === 'auto') out[header] = '1';\n else out[header] = String(value);\n }\n if (ext.headers) Object.assign(out, ext.headers);\n return out;\n}\n\nexport interface HttpClientOptions {\n apiKey: string;\n baseUrl: string;\n timeoutMs: number;\n maxRetries: number;\n /** Extensions applied to every request (per-call bags override per key). */\n defaults?: CodaiRequestExtensions;\n /** Injectable fetch (defaults to the global one). */\n fetch?: typeof fetch;\n}\n\nexport type Query = Record<string, string | number | boolean | undefined | null>;\n\nexport interface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\n /** Extra raw headers for this call (e.g. tus `Upload-Offset`); applied last. */\n headers?: Record<string, string>;\n /** JSON body (serialised) — pass `undefined` for no body. */\n body?: unknown;\n /** A pre-built body (FormData / Blob) sent as-is; disables retries. */\n rawBody?: BodyInit;\n query?: Query;\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n /** Override the client timeout for this call (ms). `0` disables it (streams). */\n timeoutMs?: number;\n /** Never retry this call (multipart uploads, streams). */\n noRetry?: boolean;\n /** Statuses treated as success besides 2xx (e.g. 503 on `/health/ready`). */\n acceptStatus?: number[];\n}\n\nexport class HttpClient {\n readonly apiKey: string;\n readonly baseUrl: string;\n readonly timeoutMs: number;\n readonly maxRetries: number;\n readonly defaults: CodaiRequestExtensions;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: HttpClientOptions) {\n this.apiKey = opts.apiKey;\n this.baseUrl = opts.baseUrl.replace(/\\/$/, '');\n this.timeoutMs = opts.timeoutMs;\n this.maxRetries = opts.maxRetries;\n this.defaults = opts.defaults ?? {};\n this.fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));\n }\n\n url(path: string, query?: Query): string {\n const url = new URL(`${this.baseUrl}${path}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined || v === null) continue;\n url.searchParams.set(k, typeof v === 'boolean' ? (v ? '1' : '0') : String(v));\n }\n }\n return url.toString();\n }\n\n headers(ext?: CodaiRequestExtensions, json = true): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n ...(json ? { 'Content-Type': 'application/json' } : {}),\n ...extensionHeaders(this.defaults),\n ...extensionHeaders(ext),\n };\n }\n\n /** Perform a request; throws `CodaiError` on non-2xx (after retries on 429/5xx). */\n async request(path: string, init: RequestOptions = {}): Promise<Response> {\n const url = this.url(path, init.query);\n const hasJson = init.body !== undefined;\n const headers = { ...this.headers(init.ext, hasJson), ...init.headers };\n const method = init.method ?? (hasJson || init.rawBody !== undefined ? 'POST' : 'GET');\n const retries = init.noRetry || init.rawBody !== undefined ? 0 : this.maxRetries;\n const timeout = init.timeoutMs ?? this.timeoutMs;\n const accept = new Set(init.acceptStatus ?? []);\n let lastErr: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n const signal = init.signal ?? (timeout > 0 ? AbortSignal.timeout(timeout) : undefined);\n try {\n const res = await this.fetchImpl(url, {\n method,\n headers,\n ...(hasJson ? { body: JSON.stringify(init.body) } : {}),\n ...(init.rawBody !== undefined ? { body: init.rawBody } : {}),\n ...(signal ? { signal } : {}),\n });\n if (res.ok || accept.has(res.status)) return res;\n if (RETRYABLE.has(res.status) && attempt < retries) {\n await sleep(500 * 2 ** attempt + Math.random() * 250);\n continue;\n }\n throw await this.toError(path, res);\n } catch (err) {\n if (err instanceof CodaiError) throw err;\n lastErr = err;\n // Caller aborts are never retried.\n if (init.signal?.aborted) throw err;\n if (attempt < retries) {\n await sleep(500 * 2 ** attempt);\n continue;\n }\n }\n }\n throw new CodaiError(`codai ${path} failed after retries: ${String(lastErr)}`, 0, null);\n }\n\n async json<T>(path: string, init: RequestOptions = {}): Promise<T> {\n const res = await this.request(path, init);\n return (await res.json()) as T;\n }\n\n /**\n * Open a `text/event-stream` and iterate parsed frames. Frames are\n * `\\n\\n`-separated blocks; each yields `{ event, data }` where `event`\n * defaults to `message` and `data` is the joined `data:` payload (raw\n * string — the caller decides whether it is JSON or `[DONE]`). Comment\n * lines (`: ping`) are skipped. The stream is retried like any request\n * up to the first byte; after that errors propagate.\n */\n async *sse(\n path: string,\n init: RequestOptions = {},\n ): AsyncGenerator<SseFrame, Response, undefined> {\n const res = await this.request(path, {\n ...init,\n timeoutMs: init.timeoutMs ?? 0,\n noRetry: true,\n });\n yield* readSse(res, init.signal);\n return res;\n }\n\n private async toError(path: string, res: Response): Promise<CodaiError> {\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n /* non-JSON error body */\n }\n const retryAfterRaw = res.headers.get('retry-after');\n const retryAfter = retryAfterRaw && /^\\d+$/.test(retryAfterRaw) ? Number(retryAfterRaw) : null;\n const message = extractMessage(body);\n return new CodaiError(\n message ? `codai ${path} → ${res.status}: ${message}` : `codai ${path} → ${res.status}`,\n res.status,\n body,\n {\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n retryAfter,\n },\n );\n }\n}\n\nexport interface SseFrame {\n /** `event:` name; `message` when the frame has none (OpenAI-style streams). */\n event: string;\n /** Joined `data:` lines (a multi-line data block is joined with `\\n`). */\n data: string;\n}\n\n/** Parse an SSE body into frames. Exported for the resources and for tests. */\nexport async function* readSse(res: Response, signal?: AbortSignal): AsyncGenerator<SseFrame> {\n const reader = res.body?.getReader();\n if (!reader) throw new CodaiError('no response body', res.status, null);\n const decoder = new TextDecoder();\n let buffer = '';\n const onAbort = () => void reader.cancel().catch(() => {});\n signal?.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n // Normalise CRLF so both `\\n\\n` and `\\r\\n\\r\\n` delimit frames.\n buffer = buffer.replace(/\\r\\n/g, '\\n');\n const blocks = buffer.split('\\n\\n');\n buffer = blocks.pop() ?? '';\n for (const block of blocks) {\n const frame = parseSseBlock(block);\n if (frame) yield frame;\n }\n }\n const tail = buffer.trim() ? parseSseBlock(buffer) : null;\n if (tail) yield tail;\n } finally {\n signal?.removeEventListener('abort', onAbort);\n reader.releaseLock?.();\n }\n}\n\nfunction parseSseBlock(block: string): SseFrame | null {\n let event = 'message';\n const data: string[] = [];\n for (const line of block.split('\\n')) {\n if (!line || line.startsWith(':')) continue;\n if (line.startsWith('event:')) event = line.slice(6).trim();\n else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));\n // `id:` / `retry:` are never emitted by the gateway; ignore anything else.\n }\n if (data.length === 0) return null;\n return { event, data: data.join('\\n') };\n}\n\n/** Parse a frame's data as JSON, returning `null` for `[DONE]` / non-JSON. */\nexport function frameJson<T = unknown>(frame: SseFrame): T | null {\n if (frame.data === '[DONE]') return null;\n try {\n return JSON.parse(frame.data) as T;\n } catch {\n return null;\n }\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n","/** Type helpers over the generated OpenAPI types shared by every resource. */\nimport type { components, operations } from '../generated/gateway';\n\nexport type Schemas = components['schemas'];\nexport type Schema<K extends keyof Schemas> = Schemas[K];\n\n/** JSON request body of an operation. */\nexport type Body<Op extends keyof operations> = operations[Op] extends {\n requestBody?: { content: { 'application/json': infer B } };\n}\n ? B\n : never;\n\n/** JSON response body of an operation for a given status (default 200). */\nexport type Reply<\n Op extends keyof operations,\n Status extends keyof operations[Op]['responses'] = 200 extends keyof operations[Op]['responses']\n ? 200\n : keyof operations[Op]['responses'],\n> = operations[Op]['responses'][Status] extends {\n content: { 'application/json': infer R };\n}\n ? R\n : never;\n\n/** Query parameters of an operation. */\nexport type QueryOf<Op extends keyof operations> = operations[Op]['parameters'] extends {\n query?: infer Q;\n}\n ? NonNullable<Q>\n : never;\n\n/**\n * Strip the `readonly` modifiers that `--immutable` adds, so callers can\n * build request bodies with plain mutable objects.\n */\nexport type Mutable<T> =\n T extends ReadonlyArray<infer U>\n ? Array<Mutable<U>>\n : T extends object\n ? { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\nexport function stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) if (v !== undefined) out[k] = v;\n return out as T;\n}\n","/** `/v1/account`, `/v1/receipt`, `/v1/feedback`, `/v1/phone/models`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type AccountView = Reply<'getAccount'>;\nexport type AccountPatchRequest = Mutable<Body<'patchAccount'>>;\nexport type AccountPatchResponse = Reply<'patchAccount'>;\nexport type Receipt = Reply<'getReceipt'>;\nexport type FeedbackRequest = Mutable<Body<'submitFeedback'>>;\nexport type FeedbackResponse = Reply<'submitFeedback'>;\nexport type PhoneModel = Schema<'AccountPhoneModel'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Account {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/account` — the full account card. */\n get(opts: CallOpts = {}): Promise<AccountView> {\n return this.http.json<AccountView>('/v1/account', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/account` — consents, username, referral (at least one field). */\n update(body: AccountPatchRequest, opts: CallOpts = {}): Promise<AccountPatchResponse> {\n return this.http.json<AccountPatchResponse>('/v1/account', {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Receipts {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `GET /v1/receipt` — spend receipt. `sessionId` wins over `since`; with\n * neither, the last 24 hours.\n */\n get(\n query: { sessionId?: string; since?: string | Date } = {},\n opts: CallOpts = {},\n ): Promise<Receipt> {\n return this.http.json<Receipt>('/v1/receipt', {\n query: {\n session_id: query.sessionId,\n since: query.since instanceof Date ? query.since.toISOString() : query.since,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Feedback {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/feedback` — rate one turn. Exactly one of `event_id`,\n * `session_id`, `client_request_id` must be present.\n */\n submit(body: FeedbackRequest, opts: CallOpts = {}): Promise<FeedbackResponse> {\n return this.http.json<FeedbackResponse>('/v1/feedback', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class PhoneModels {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/phone/models` — on-device model catalog with signed URLs. */\n async list(opts: CallOpts = {}): Promise<PhoneModel[]> {\n const raw = await this.http.json<Reply<'listPhoneModels'>>('/v1/phone/models', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.models ?? [])];\n }\n}\n","/** `/v1/agents/*` — synchronous runs and the persisted async run lifecycle. */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type AgentRunRequest = Mutable<Body<'runAgentSync'>>;\nexport type AgentRunCreateRequest = Mutable<Body<'createAgentRun'>>;\nexport type AgentSyncResult = Reply<'runAgentSync'>;\nexport type AgentRunAccepted = Reply<'createAgentRun', 202>;\nexport type AgentRun = Reply<'getAgentRun'>;\nexport type AgentRunStep = Schema<'AgentRunStep'>;\nexport type AgentRunStats = Reply<'getAgentRunStats'>;\nexport type AgentRunStatus = Schema<'AgentRunStatus'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface AgentRunResult {\n result: string;\n model: string;\n /** Usage-event id — exact target for `feedback.submit`. */\n eventId: string | null;\n usage: AgentSyncResult['usage'] | null;\n raw: AgentSyncResult;\n headers: Headers;\n}\n\n/** SSE frames of `GET /v1/agents/runs/{id}/stream`. */\nexport type AgentRunStreamEvent =\n | {\n event: 'step';\n data: {\n seq: number;\n kind: 'plan' | 'tool_call' | 'observation' | 'answer';\n summary: string | null;\n };\n }\n | {\n event: 'done';\n data: {\n status: 'completed' | 'failed' | 'cancelled';\n result: string | null;\n error: string | null;\n step_count: number;\n };\n }\n | { event: 'timeout'; data: Record<string, never> };\n\nexport class AgentRuns {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/agents/runs` — returns 202 with the run id. */\n create(body: AgentRunCreateRequest, opts: CallOpts = {}): Promise<AgentRunAccepted> {\n return this.http.json<AgentRunAccepted>('/v1/agents/runs', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/agents/runs/{id}` */\n get(id: string, opts: CallOpts = {}): Promise<AgentRun> {\n return this.http.json<AgentRun>(`/v1/agents/runs/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/agents/runs/{id}/steps` — newest first. */\n async steps(id: string, opts: CallOpts = {}): Promise<AgentRunStep[]> {\n const raw = await this.http.json<Reply<'listAgentRunSteps'>>(\n `/v1/agents/runs/${encodeURIComponent(id)}/steps`,\n { ext: opts.ext, signal: opts.signal },\n );\n return [...(raw.steps ?? [])];\n }\n\n /** `GET /v1/agents/runs/stats?days=` */\n stats(days?: number, opts: CallOpts = {}): Promise<AgentRunStats> {\n return this.http.json<AgentRunStats>('/v1/agents/runs/stats', {\n query: { days },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/agents/runs/{id}/cancel` */\n cancel(id: string, opts: CallOpts = {}): Promise<Reply<'cancelAgentRun'>> {\n return this.http.json<Reply<'cancelAgentRun'>>(\n `/v1/agents/runs/${encodeURIComponent(id)}/cancel`,\n { method: 'POST', body: {}, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /**\n * `GET /v1/agents/runs/{id}/stream` — async iterator over `step` / `done` /\n * `timeout` events. The iterator ends after `done`; on `timeout` (30 min)\n * it also ends and you may reconnect (full replay from seq 0).\n */\n async *stream(\n id: string,\n opts: CallOpts = {},\n ): AsyncGenerator<AgentRunStreamEvent, void, undefined> {\n const frames = this.http.sse(`/v1/agents/runs/${encodeURIComponent(id)}/stream`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data) continue;\n const ev = { event: frame.event, data } as AgentRunStreamEvent;\n yield ev;\n if (ev.event === 'done' || ev.event === 'timeout') return;\n }\n }\n}\n\nexport class Agents {\n readonly runs: AgentRuns;\n constructor(private readonly http: HttpClient) {\n this.runs = new AgentRuns(http);\n }\n\n /** `POST /v1/agents/run` — blocks until the agent loop finishes. */\n async run(body: AgentRunRequest, opts: CallOpts = {}): Promise<AgentRunResult> {\n const res = await this.http.request('/v1/agents/run', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as AgentSyncResult;\n return {\n result: String(raw.result ?? ''),\n model: String(raw.model ?? ''),\n eventId: raw.event_id ?? res.headers.get('x-codai-event-id'),\n usage: raw.usage ?? null,\n raw,\n headers: res.headers,\n };\n }\n}\n","/** `POST /v1/audio/transcriptions`, `POST /v1/audio/speech` and `POST /v1/audio/speech/stream`. */\nimport { type CodaiRequestExtensions, type HttpClient, frameJson } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type TranscriptionResponse = Reply<'createTranscription'>;\nexport type SpeechRequest = Mutable<Body<'createSpeech'>>;\nexport type SpeechStreamRequest = Mutable<Body<'createSpeechStream'>>;\n/** One word timing of a `speechJson()` result (seconds from the start of the audio). */\nexport type SpeechWord = Schema<'SpeechWord'>;\n/** JSON shape of `POST /v1/audio/speech` when `timestamps` or `store` is true. */\nexport type SpeechJson = Schema<'SpeechJson'>;\n\n/** One event of `audio.speechStream()` (Azure neural TTS with lip-sync timing). */\nexport type SpeechStreamEvent =\n | {\n type: 'start';\n model: string;\n voice: string;\n format: 'pcm' | 'mp3';\n content_type: string;\n sample_rate: number;\n }\n /** `delta` is base64; `audio` is the decoded bytes (PCM16 LE mono 24 kHz for `pcm`). */\n | { type: 'audio'; delta: string; audio: Uint8Array }\n /** Azure viseme id (0-21) at `offsetMs` on the audio timeline. */\n | { type: 'viseme'; id: number; offsetMs: number }\n | { type: 'word'; text: string; offsetMs: number; durationMs: number }\n | {\n type: 'done';\n audio_ms: number | null;\n audioBytes: number;\n visemes: number;\n words: number;\n }\n | { type: 'error'; error: { code: string; message: string } };\n/** Raw generated event schema (all fields optional). */\nexport type SpeechStreamEventSchema = Schema<'SpeechStreamEvent'>;\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nexport interface TranscriptionOptions {\n /** Audio file contents (max 25 MB). */\n file: Blob | Uint8Array | ArrayBuffer;\n /** Filename hint (extension drives format detection). Default `audio.webm`. */\n filename?: string;\n /** Default `codai-transcribe`. */\n model?: string;\n /** ISO-639-1 language hint. */\n language?: string;\n /** Text to guide style or spelling. */\n prompt?: string;\n /** `json` (default) or `verbose_json`. */\n responseFormat?: 'json' | 'verbose_json';\n /** Sampling temperature 0–1. */\n temperature?: number;\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface TranscriptionResult {\n text: string;\n raw: TranscriptionResponse;\n routedTo: string | null;\n headers: Headers;\n}\n\nexport interface SpeechResult {\n /** Raw audio bytes in the requested format (mp3 by default). */\n audio: ArrayBuffer;\n /** Upstream `content-type` (`audio/mpeg` when the upstream sent none). */\n contentType: string;\n routedTo: string | null;\n headers: Headers;\n}\n\nexport interface SpeechJsonResult {\n /** Decoded audio bytes (empty when `store: true` — use `asset.url`). */\n audio: Uint8Array;\n /** Word timings (`timestamps: true`); `null` when not requested or the timing pass failed. */\n words: SpeechWord[] | null;\n /** The stored studio asset (`store: true`), referenceable as `asset:<asset_id>` in renders. */\n asset: SpeechJson['asset'] | null;\n durationSeconds: number;\n /** Upstream cost of the request in micro-USD. */\n costMicroUsd: number | null;\n /** True when `timestamps` was requested but the gateway answered `x-codai-timestamps: unavailable`. */\n timestampsUnavailable: boolean;\n raw: SpeechJson;\n routedTo: string | null;\n headers: Headers;\n}\n\nexport class Audio {\n constructor(private readonly http: HttpClient) {}\n\n /** Speech-to-text (multipart upload; never retried). Returns the transcript (0.2.x shape). */\n async transcribe(opts: TranscriptionOptions): Promise<string> {\n return (await this.transcribeDetailed(opts)).text;\n }\n\n /** Speech-to-text with the raw upstream JSON and routing headers. */\n async transcribeDetailed(opts: TranscriptionOptions): Promise<TranscriptionResult> {\n const form = new FormData();\n const blob = opts.file instanceof Blob ? opts.file : new Blob([opts.file as BlobPart]);\n form.append('file', blob, opts.filename ?? 'audio.webm');\n form.append('model', opts.model ?? 'codai-transcribe');\n if (opts.language) form.append('language', opts.language);\n if (opts.prompt) form.append('prompt', opts.prompt);\n if (opts.responseFormat) form.append('response_format', opts.responseFormat);\n if (opts.temperature !== undefined) form.append('temperature', String(opts.temperature));\n const res = await this.http.request('/v1/audio/transcriptions', {\n method: 'POST',\n rawBody: form,\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as TranscriptionResponse;\n return {\n text: typeof raw.text === 'string' ? raw.text : '',\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n /** Text-to-speech. Returns the raw audio bytes (0.2.x shape); see `speechDetailed()` for headers. */\n async speech(\n body: Omit<SpeechRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ArrayBuffer> {\n return (await this.speechDetailed(body, opts)).audio;\n }\n\n /** Text-to-speech with the upstream `content-type` and routing headers. */\n async speechDetailed(\n body: Omit<SpeechRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SpeechResult> {\n const model = body.model ?? 'codai-tts';\n // codai-speech* pick their own default (Aoede / Kore); `alloy` is an Azure voice name.\n const voice = body.voice ?? (model.startsWith('codai-speech') ? undefined : 'alloy');\n const res = await this.http.request('/v1/audio/speech', {\n body: { ...body, model, ...(voice === undefined ? {} : { voice }) },\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n audio: await res.arrayBuffer(),\n contentType: res.headers.get('content-type') ?? 'audio/mpeg',\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n /**\n * Text-to-speech with JSON output: per-word timings (`timestamps`, default true here) and/or a stored studio\n * asset (`store`). Works for every speech model; `codai-speech` (Chirp 3 HD) and `codai-speech-expressive`\n * (Gemini TTS, honours `instructions`) speak Romanian natively (`language`, default `ro-RO`).\n */\n async speechJson(\n body: Omit<SpeechRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SpeechJsonResult> {\n const timestamps = body.timestamps ?? (body.store ? undefined : true);\n const res = await this.http.request('/v1/audio/speech', {\n body: {\n ...body,\n model: body.model ?? 'codai-speech',\n ...(timestamps === undefined ? {} : { timestamps }),\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as SpeechJson;\n const cost = raw.cost_micro_usd ?? res.headers.get('x-codai-cost-micro-usd');\n return {\n audio: raw.b64_json ? base64ToBytes(raw.b64_json) : new Uint8Array(0),\n words: raw.words ? [...raw.words] : null,\n asset: raw.asset ?? null,\n durationSeconds: raw.duration_seconds,\n costMicroUsd: cost === null || cost === undefined ? null : Number(cost),\n timestampsUnavailable: res.headers.get('x-codai-timestamps') === 'unavailable',\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n /**\n * Streaming neural TTS with visemes + word boundaries (`codai-tts-ro`, Azure AI Speech).\n * Yields `start`, then `audio` / `viseme` / `word` in synthesis order, then `done` (or `error`).\n * Voices: `alina` (default), `emil`, or any Azure neural voice name. Default format `pcm`\n * (PCM16 mono 24 kHz). Works with an ephemeral token of scope `audio` or `live`.\n */\n async *speechStream(\n body: SpeechStreamRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): AsyncGenerator<SpeechStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/audio/speech/stream', {\n body: { ...body, model: body.model ?? 'codai-tts-ro' },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data || typeof data.type !== 'string') continue;\n if (data.type === 'audio' && typeof data.delta === 'string') {\n yield { type: 'audio', delta: data.delta, audio: base64ToBytes(data.delta) };\n continue;\n }\n yield data as SpeechStreamEvent;\n if (data.type === 'done' || data.type === 'error') return;\n }\n }\n}\n","/**\n * `/v1/billing`, `/v1/billing/invoices`, `/v1/studio/quote` — READ-ONLY billing overview and Studio price quotes.\n *\n * Nothing here starts a payment: plan, top-up and portal actions are browser\n * links in `Billing.links` (open them; the SDK never creates checkout sessions).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type BillingOverview = Reply<'getBilling'>;\nexport type BillingPlan = Schema<'BillingPlan'>;\nexport type BillingWallet = Schema<'BillingWallet'>;\nexport type BillingAutoTopup = Schema<'BillingAutoTopup'>;\nexport type BillingPaymentMethod = Schema<'BillingPaymentMethod'>;\nexport type BillingLinks = Schema<'BillingLinks'>;\nexport type BillingInvoice = Schema<'BillingInvoice'>;\nexport type BillingInvoiceList = Reply<'listBillingInvoices'>;\nexport type StudioQuote = Reply<'getStudioQuote'>;\n\n/** `GET /v1/studio/quote` parameters: `action` picks the price function, the rest are its inputs. */\nexport interface StudioQuoteQuery {\n action: 'video' | 'music' | 'render' | 'preview' | 'frames' | 'captions' | 'speech' | 'image';\n seconds?: number;\n resolution?: '720p' | '1080p';\n audio?: boolean;\n quality?: 'draft' | 'final';\n pages?: number;\n chars?: number;\n model?: string;\n n?: number;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface WatchBalanceOptions {\n /** Call `onLow` when `wallet.balance_eur` drops below this (EUR). */\n thresholdEur: number;\n /** Poll interval (ms). Default 60_000, minimum 1_000. */\n intervalMs?: number;\n /** Stops the watcher (same as calling the returned function). */\n signal?: AbortSignal;\n /**\n * Called once per crossing below the threshold (again only after the\n * balance went back to >= threshold). Read `billing.links.topup` to offer a\n * top-up link; the watcher itself never pays.\n */\n onLow: (balanceEur: number, billing: BillingOverview) => void | Promise<void>;\n /** Called when a poll fails; polling continues. Default: ignore. */\n onError?: (err: unknown) => void;\n}\n\nexport class Billing {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/billing` — plan, wallet, auto top-up, cards and pay links (read-only). */\n get(opts: CallOpts = {}): Promise<BillingOverview> {\n return this.http.json<BillingOverview>('/v1/billing', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/billing/invoices` — fiscal invoices and credit notes, newest first. */\n async invoices(query: { limit?: number } = {}, opts: CallOpts = {}): Promise<BillingInvoice[]> {\n const raw = await this.http.json<BillingInvoiceList>('/v1/billing/invoices', {\n query: { limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...raw.invoices];\n }\n\n /**\n * `GET /v1/studio/quote` — what a Studio action costs (USD and wallet EUR micros) and your spendable balance,\n * before you run it. Paid Studio calls answer 402 `insufficient_funds` when `sufficient` is false. Free.\n */\n studioQuote(query: StudioQuoteQuery, opts: CallOpts = {}): Promise<StudioQuote> {\n return this.http.json<StudioQuote>('/v1/studio/quote', {\n // The gateway reads `audio` as the literal `true` / `false` (the client would send 1 / 0 for a boolean).\n query: { ...query, audio: query.audio === undefined ? undefined : String(query.audio) },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Poll `get()` every `intervalMs` and call `onLow` once each time the wallet\n * balance crosses below `thresholdEur`. Read-only: never creates a checkout.\n * Returns a function that stops the watcher.\n */\n watchBalance(opts: WatchBalanceOptions): () => void {\n const intervalMs = Math.max(1_000, opts.intervalMs ?? 60_000);\n const ctrl = new AbortController();\n const stop = () => ctrl.abort();\n if (opts.signal) {\n if (opts.signal.aborted) stop();\n else opts.signal.addEventListener('abort', stop, { once: true });\n }\n let low = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tick = async (): Promise<void> => {\n if (ctrl.signal.aborted) return;\n try {\n const billing = await this.get({ signal: ctrl.signal });\n const balance = billing.wallet.balance_eur;\n if (balance < opts.thresholdEur) {\n if (!low) {\n low = true;\n await opts.onLow(balance, billing);\n }\n } else low = false;\n } catch (err) {\n if (!ctrl.signal.aborted) opts.onError?.(err);\n }\n if (!ctrl.signal.aborted) timer = setTimeout(() => void tick(), intervalMs);\n };\n ctrl.signal.addEventListener('abort', () => clearTimeout(timer), { once: true });\n void tick();\n return stop;\n }\n}\n","/**\n * `/v1/cards/*` — server-side DATA for typed cards (`@codai/cards`). Every JSON method returns `{ block, provenance }`\n * where `block` is already a valid card block (weather, places, map, metric, table or links) that can be dropped into\n * a card unchanged; `staticMap` returns PNG bytes.\n *\n * Weather and FX are free. Places, geocode and static maps are Google calls billed to your usage at Google's list price\n * (Places text/nearby $0.032, geocoding $0.005, static map $0.002) and limited per user per UTC day (200 Places,\n * 500 maps); `unfurl` and `product` are free but share a limit of 500 fetches per day (cache hits do not count). Maps methods throw a 503\n * `CodaiError` with code `maps_not_configured` when the gateway has no maps key — fall back to text.\n *\n * `render` turns a `chart` or `qr` block into a PNG or SVG on the gateway (free, 2000 per day) for surfaces that\n * cannot draw cards; Mermaid / math blocks throw a 422 `CodaiError` with code `render_unsupported`.\n *\n * `route` is Google Routes travel time (billed: $0.010 traffic-aware driving, $0.005 walk/bike/transit; maps limit).\n * `track` follows a parcel (Sameday live; FAN Courier, Cargus, DPD only when the gateway has their contract) and\n * `efactura` lists your fiscal documents issued through Brivio with their ANAF e-Factura status; both free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type QueryOf, type Reply, type Schema } from './_shared';\n\n/** `{ block, provenance }` (+ `results` for geocode) as returned by every JSON card endpoint. */\nexport type CardDataResponse = Schema<'CardDataResponse'>;\nexport type CardsWeatherParams = QueryOf<'cardsWeather'>;\nexport type CardsPlacesParams = QueryOf<'cardsPlaces'>;\nexport type CardsGeocodeParams = QueryOf<'cardsGeocode'>;\nexport type CardsStaticMapParams = QueryOf<'cardsStaticMap'>;\nexport type CardsFxParams = QueryOf<'cardsFx'>;\nexport type CardsRouteParams = QueryOf<'cardsRoute'>;\nexport type CardsTrackParams = QueryOf<'cardsTrack'>;\nexport type CardsEfacturaParams = QueryOf<'cardsEfactura'>;\nexport type CardsUnfurlBody = Body<'cardsUnfurl'>;\nexport type CardsProductBody = Body<'cardsProduct'>;\nexport type CardsRenderBody = Body<'cardsRender'>;\nexport type CardsWeatherResponse = Reply<'cardsWeather'>;\nexport type CardsPlacesResponse = Reply<'cardsPlaces'>;\nexport type CardsGeocodeResponse = Reply<'cardsGeocode'>;\nexport type CardsFxResponse = Reply<'cardsFx'>;\nexport type CardsRouteResponse = Reply<'cardsRoute'>;\nexport type CardsTrackResponse = Reply<'cardsTrack'>;\nexport type CardsEfacturaResponse = Reply<'cardsEfactura'>;\nexport type CardsUnfurlResponse = Reply<'cardsUnfurl'>;\nexport type CardsProductResponse = Reply<'cardsProduct'>;\n\n/** A rendered static map: PNG bytes plus the attribution the gateway sent (`x-codai-attribution`). */\nexport interface CardsStaticMap {\n bytes: Uint8Array;\n contentType: string;\n attribution: string | null;\n}\n\n/** A rendered card block: image bytes, `image/png` or `image/svg+xml`, and the pixel size (`x-codai-render-size`). */\nexport interface CardsRendered {\n bytes: Uint8Array;\n contentType: string;\n width: number | null;\n height: number | null;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\ntype Q = Record<string, string | number | boolean | undefined | null>;\n\nexport class Cards {\n constructor(private readonly http: HttpClient) {}\n\n private get<T>(path: string, query: object, opts: CallOpts): Promise<T> {\n return this.http.json<T>(path, { query: query as Q, ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/cards/weather` — `weather` block from MET Norway (cached 30–60 min per 0.01°, free). */\n weather(params: CardsWeatherParams, opts: CallOpts = {}): Promise<CardsWeatherResponse> {\n return this.get('/v1/cards/weather', params, opts);\n }\n\n /**\n * `GET /v1/cards/places` — `places` block from Google Places: Text Search with `q` (biased to `lat`/`lng`/`radius`),\n * Nearby Search without it. Billed per call; `block` is null when nothing matched.\n */\n places(params: CardsPlacesParams, opts: CallOpts = {}): Promise<CardsPlacesResponse> {\n return this.get('/v1/cards/places', params, opts);\n }\n\n /** `GET /v1/cards/geocode` — `map` block (≤ 5 markers) plus raw `results` (Google Geocoding, billed). */\n geocode(params: CardsGeocodeParams, opts: CallOpts = {}): Promise<CardsGeocodeResponse> {\n return this.get('/v1/cards/geocode', params, opts);\n }\n\n /**\n * `GET /v1/cards/static-map` — PNG from Google Maps Static proxied through the gateway (no maps key on the client).\n * Needs `center` or `markers` (`lat,lng[,L]` joined by `|`); ≤ 640×400 points. Billed per call.\n */\n async staticMap(params: CardsStaticMapParams, opts: CallOpts = {}): Promise<CardsStaticMap> {\n const res = await this.http.request('/v1/cards/static-map', {\n query: params as Q,\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n contentType: res.headers.get('content-type') ?? 'image/png',\n attribution: res.headers.get('x-codai-attribution'),\n };\n }\n\n /**\n * `GET /v1/cards/fx` — BNR (default) or ECB reference rates: a `metric` block with `from`+`to`, otherwise a `table`\n * block against `quote`, optionally limited to `symbols` (comma-separated). Free.\n */\n fx(params: CardsFxParams = {}, opts: CallOpts = {}): Promise<CardsFxResponse> {\n return this.get('/v1/cards/fx', params, opts);\n }\n\n /**\n * `GET /v1/cards/route` — travel time from Google Routes: `route` { mode, durationS, staticDurationS, distanceM,\n * polyline } and a `map` block. `origin`/`destination` as \"lat,lng\" or `from`/`to` as addresses; `mode` drive\n * (traffic-aware, default), walk, bicycle, transit, two_wheeler. Billed per call; both null when no route exists.\n */\n route(params: CardsRouteParams, opts: CallOpts = {}): Promise<CardsRouteResponse> {\n return this.get('/v1/cards/route', params, opts);\n }\n\n /**\n * `GET /v1/cards/track` — parcel history as a `timeline` block plus `result` (carrier, configured, found,\n * delivered, events, trackingUrl). `carrier` (sameday | fan | cargus | dpd) is guessed from the AWB when omitted;\n * carriers without gateway credentials answer `configured: false` with only the tracking link. Free.\n */\n track(params: CardsTrackParams, opts: CallOpts = {}): Promise<CardsTrackResponse> {\n return this.get('/v1/cards/track', params, opts);\n }\n\n /**\n * `GET /v1/cards/efactura` — your fiscal documents issued through Brivio with their ANAF e-Factura status\n * (`documents[]` + a `table` block, null when there are none). Free.\n */\n efactura(params: CardsEfacturaParams = {}, opts: CallOpts = {}): Promise<CardsEfacturaResponse> {\n return this.get('/v1/cards/efactura', params, opts);\n }\n\n /**\n * `POST /v1/cards/unfurl` — `links` block (variant `preview`) for a public https page; SSRF-guarded, cached 24 h.\n * Private targets throw 400 `unfurl_blocked`, non-https pages 422 `unfurl_not_https`.\n */\n unfurl(url: string, opts: CallOpts = {}): Promise<CardsUnfurlResponse> {\n const body: CardsUnfurlBody = { url };\n return this.http.json<CardsUnfurlResponse>('/v1/cards/unfurl', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/cards/product` — `products` block with one item from a public https product page's schema.org\n * `Product` JSON-LD (or OpenGraph product tags): name, image, price + currency (lowest offer), old price, rating\n * (0–5), reviews, seller, availability badge in `lang` (en default). Only what the page states; never sponsored.\n * SSRF-guarded like `unfurl`, cached 6 h. No product data throws 422 `product_not_found`.\n */\n product(url: string, lang?: 'en' | 'ro', opts: CallOpts = {}): Promise<CardsProductResponse> {\n const body: CardsProductBody = lang ? { url, lang } : { url };\n return this.http.json<CardsProductResponse>('/v1/cards/product', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/cards/render` — renders a `chart` or `qr` block to `format` (`png` default, or `svg`) at\n * `width` x `height` CSS px (64–1200, defaults 480 x 300; QR is square) times `scale` (1–3, PNG only).\n * Other block types (Mermaid `diagram`, `math`, …) throw 422 `render_unsupported`. Free; 2000 renders per day.\n */\n async render(body: CardsRenderBody, opts: CallOpts = {}): Promise<CardsRendered> {\n const res = await this.http.request('/v1/cards/render', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n const size = /^(\\d+)x(\\d+)$/.exec(res.headers.get('x-codai-render-size') ?? '');\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n contentType: res.headers.get('content-type') ?? 'image/png',\n width: size ? Number(size[1]) : null,\n height: size ? Number(size[2]) : null,\n };\n }\n}\n","/** `POST /v1/chat/completions` — OpenAI-compatible completions (JSON + SSE). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient, readSse } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type ChatCompletionRequest = Mutable<Body<'createChatCompletion'>>;\n/** Request body as accepted by the SDK: `stream` is set by the method and `model` defaults to `codai`. */\nexport type ChatCompletionInput = Omit<ChatCompletionRequest, 'stream' | 'model'> & {\n model?: string;\n};\nexport type ChatCompletionResponse = Reply<'createChatCompletion'>;\nexport type ChatMessage = Mutable<Schema<'ChatMessage'>>;\nexport type ChatTool = Mutable<Schema<'ChatTool'>>;\nexport type ChatToolCall = Mutable<Schema<'ChatToolCall'>>;\nexport type ChatUsage = Schema<'ChatUsage'>;\n\nexport interface TokenUsage {\n promptTokens: number;\n completionTokens: number;\n /** Prompt tokens served from the provider cache, when reported. */\n cachedTokens?: number;\n}\n\n/** Per-call options accepted by every chat method. */\nexport interface ChatCallOptions {\n /** `X-Codai-*` extension headers for this call. */\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface ChatResult {\n /** Assistant message content (first choice). */\n content: string;\n /** Tool calls on the first choice (empty if none). */\n toolCalls: ChatToolCall[];\n /** Raw OpenAI-shaped response. */\n raw: ChatCompletionResponse;\n /** Request id (`x-codai-trace-id` / `x-request-id`) — pass to `feedback`. */\n requestId: string | null;\n /** Usage-event id (`x-codai-event-id`) — exact target for `feedback.submit`. */\n eventId: string | null;\n /** Which upstream model actually served (`x-codai-routed-to`). */\n routedTo: string | null;\n /** Verification status for verified-execution responses, if present. */\n execVerify: string | null;\n usage: TokenUsage | null;\n /** Response headers, for the long tail of `x-codai-*` metadata. */\n headers: Headers;\n}\n\n/** Final metadata for a completed stream — resolved via `stream.final`. */\nexport interface ChatStreamResult {\n content: string;\n toolCalls: ChatToolCall[];\n requestId: string | null;\n routedTo: string | null;\n execVerify: string | null;\n usage: TokenUsage | null;\n /** `finish_reason` of the last content chunk, when sent. */\n finishReason: string | null;\n headers: Headers | null;\n}\n\n/**\n * A live chat stream. Async-iterate it for text deltas, then await `.final`\n * for metadata. `.chunks()` yields the raw `chat.completion.chunk` objects.\n */\nexport interface ChatStream extends AsyncIterable<string> {\n readonly final: Promise<ChatStreamResult>;\n chunks(): AsyncIterable<ChatCompletionChunk>;\n}\n\nexport interface ChatCompletionChunk {\n id?: string;\n object?: 'chat.completion.chunk';\n model?: string;\n choices?: Array<{\n index?: number;\n delta?: {\n role?: string;\n content?: string | null;\n tool_calls?: Array<{ index?: number } & Record<string, unknown>>;\n };\n finish_reason?: string | null;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n };\n [key: string]: unknown;\n}\n\nfunction toUsage(u: ChatCompletionChunk['usage'] | undefined): TokenUsage | null {\n if (!u) return null;\n const cached = u.prompt_tokens_details?.cached_tokens;\n return {\n promptTokens: u.prompt_tokens ?? 0,\n completionTokens: u.completion_tokens ?? 0,\n ...(cached !== undefined ? { cachedTokens: cached } : {}),\n };\n}\n\n/**\n * Merge a streamed tool-call fragment into the accumulator at `index`.\n * OpenAI streams tool calls piecewise: id/name arrive first, then the\n * `arguments` string is appended across many deltas.\n */\nexport function mergeToolCall(\n acc: Map<number, Record<string, unknown>>,\n index: number,\n fragment: Record<string, unknown>,\n): void {\n const existing = acc.get(index) ?? { index };\n for (const [key, val] of Object.entries(fragment)) {\n if (key === 'index') continue;\n if (key === 'function' && val && typeof val === 'object') {\n const fn = (existing.function as Record<string, unknown>) ?? {};\n for (const [fk, fv] of Object.entries(val as Record<string, unknown>)) {\n if (fk === 'arguments') fn.arguments = String(fn.arguments ?? '') + String(fv ?? '');\n else fn[fk] = fv;\n }\n existing.function = fn;\n } else {\n existing[key] = val;\n }\n }\n acc.set(index, existing);\n}\n\nexport class ChatCompletions {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Non-streaming completion. `stream` is forced to `false`; use\n * `stream()` for SSE.\n */\n async create(body: ChatCompletionInput, opts: ChatCallOptions = {}): Promise<ChatResult> {\n const res = await this.http.request('/v1/chat/completions', {\n body: { ...body, model: body.model ?? 'codai', stream: false },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as ChatCompletionResponse;\n const first = raw.choices?.[0];\n const usage = raw.usage as ChatCompletionChunk['usage'] | undefined;\n return {\n content: typeof first?.message?.content === 'string' ? first.message.content : '',\n toolCalls: [...((first?.message?.tool_calls ?? []) as ChatToolCall[])],\n raw,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n eventId: res.headers.get('x-codai-event-id'),\n routedTo: res.headers.get('x-codai-routed-to'),\n execVerify: res.headers.get('x-codai-exec-verify'),\n usage: toUsage(usage),\n headers: res.headers,\n };\n }\n\n /** Streaming completion (`stream: true`). */\n stream(body: ChatCompletionInput, opts: ChatCallOptions = {}): ChatStream {\n const requestPromise = this.http.request('/v1/chat/completions', {\n body: { ...body, model: body.model ?? 'codai', stream: true },\n ext: opts.ext,\n signal: opts.signal,\n timeoutMs: 0,\n noRetry: true,\n });\n\n let resolveFinal!: (r: ChatStreamResult) => void;\n let rejectFinal!: (e: unknown) => void;\n const final = new Promise<ChatStreamResult>((resolve, reject) => {\n resolveFinal = resolve;\n rejectFinal = reject;\n });\n final.catch(() => {}); // no unhandled-rejection noise when `final` is never awaited\n\n const toolCallsByIndex = new Map<number, Record<string, unknown>>();\n let content = '';\n let usage: TokenUsage | null = null;\n let finishReason: string | null = null;\n let res: Response | null = null;\n\n const buildResult = (): ChatStreamResult => ({\n content,\n toolCalls: [...toolCallsByIndex.values()] as ChatToolCall[],\n requestId: res?.headers.get('x-codai-trace-id') ?? res?.headers.get('x-request-id') ?? null,\n routedTo: res?.headers.get('x-codai-routed-to') ?? null,\n execVerify: res?.headers.get('x-codai-exec-verify') ?? null,\n usage,\n finishReason,\n headers: res?.headers ?? null,\n });\n\n async function* chunks(): AsyncGenerator<ChatCompletionChunk, void, undefined> {\n try {\n res = await requestPromise;\n for await (const frame of readSse(res, opts.signal)) {\n if (frame.data === '[DONE]') break;\n const chunk = frameJson<ChatCompletionChunk>(frame);\n if (!chunk) continue;\n if (chunk.usage) usage = toUsage(chunk.usage);\n const choice = chunk.choices?.[0];\n if (choice?.finish_reason) finishReason = choice.finish_reason;\n const delta = choice?.delta;\n if (delta?.tool_calls) {\n for (const tc of delta.tool_calls) {\n mergeToolCall(toolCallsByIndex, typeof tc.index === 'number' ? tc.index : 0, tc);\n }\n }\n if (delta?.content) content += delta.content;\n yield chunk;\n }\n resolveFinal(buildResult());\n } catch (err) {\n rejectFinal(err);\n throw err;\n }\n }\n\n async function* text(): AsyncGenerator<string, void, undefined> {\n for await (const chunk of chunks()) {\n const delta = chunk.choices?.[0]?.delta?.content;\n if (delta) yield delta;\n }\n }\n\n return {\n [Symbol.asyncIterator]: () => text(),\n chunks: () => ({ [Symbol.asyncIterator]: () => chunks() }),\n final,\n };\n }\n}\n\nexport class Chat {\n readonly completions: ChatCompletions;\n constructor(http: HttpClient) {\n this.completions = new ChatCompletions(http);\n }\n}\n","/** `/v1/devices/*` — devices bound to your account + the aggregated dispatch inbox. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Device = Schema<'DeviceListItem'>;\nexport type DevicePatch = Mutable<Body<'updateDevice'>>;\nexport type DevicePatched = Reply<'updateDevice'>;\nexport type DispatchInbox = Reply<'getMyDispatchInbox'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Devices {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/devices` — most recently seen first. */\n async list(opts: CallOpts = {}): Promise<Device[]> {\n const raw = await this.http.json<Reply<'listDevices'>>('/v1/devices', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.devices ?? [])];\n }\n\n /** `PATCH /v1/devices/{id}` — push token and/or capabilities. */\n update(id: string, body: DevicePatch, opts: CallOpts = {}): Promise<DevicePatched> {\n return this.http.json<DevicePatched>(`/v1/devices/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/devices/{id}` */\n delete(id: string, opts: CallOpts = {}): Promise<Reply<'deleteDevice'>> {\n return this.http.json<Reply<'deleteDevice'>>(`/v1/devices/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/keys/self/revoke` — the API key this client uses revokes ITSELF (sign out).\n * Every later call with it fails with 401.\n */\n revokeSelfKey(opts: CallOpts = {}): Promise<Reply<'revokeSelfKey'>> {\n return this.http.json<Reply<'revokeSelfKey'>>('/v1/keys/self/revoke', {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/devices/me/dispatch?limit=` — pending controls dispatched at the\n * calling device (`x-codai-device` required) across all owned sessions.\n */\n dispatchInbox(query: { limit?: number } = {}, opts: CallOpts = {}): Promise<DispatchInbox> {\n return this.http.json<DispatchInbox>('/v1/devices/me/dispatch', {\n query: { limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `POST /v1/embeddings`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type EmbeddingsRequest = Mutable<Body<'createEmbeddings'>>;\nexport type EmbeddingsResponse = Reply<'createEmbeddings'>;\n\nexport interface EmbeddingsResult {\n /** One vector per input, in order. */\n embeddings: number[][];\n raw: EmbeddingsResponse;\n /** Upstream embedding model that produced the vectors (`x-codai-routed-to`). */\n routedTo: string | null;\n /** `<requested>-><served>` when a different model was substituted; vectors live in another space. */\n fallback: string | null;\n headers: Headers;\n}\n\nexport class Embeddings {\n constructor(private readonly http: HttpClient) {}\n\n async create(\n body: Omit<EmbeddingsRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<EmbeddingsResult> {\n const res = await this.http.request('/v1/embeddings', {\n body: { ...body, model: body.model ?? 'codai-embed' },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as EmbeddingsResponse;\n return {\n embeddings: (raw.data ?? []).map((d) => [...(d.embedding as readonly number[])]),\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n fallback: res.headers.get('x-codai-embed-fallback'),\n headers: res.headers,\n };\n }\n}\n","/** `/v1/environments/*` — cloud / BYO dev environments, their members, ports and secrets. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Environment = Schema<'Environment'>;\nexport type EnvironmentDetail = Schema<'EnvironmentDetail'>;\nexport type EnvironmentState = Schema<'EnvironmentState'>;\nexport type EnvironmentProvider = Schema<'EnvironmentProvider'>;\nexport type EnvironmentRole = Schema<'EnvironmentRole'>;\nexport type EnvironmentTransition = Schema<'EnvironmentTransition'>;\nexport type EnvironmentEnrollToken = Schema<'EnvironmentEnrollToken'>;\nexport type EnvironmentEnrolled = Schema<'EnvironmentEnrolled'>;\nexport type EnvironmentMember = Schema<'EnvironmentMember'>;\nexport type EnvironmentMemberCreated = Schema<'EnvironmentMemberCreated'>;\nexport type EnvironmentPort = Schema<'EnvironmentPort'>;\nexport type EnvironmentSecret = Schema<'EnvironmentSecret'>;\nexport type EnvironmentSecretSet = Schema<'EnvironmentSecretSet'>;\nexport type EnvironmentCreateBody = Mutable<Body<'createEnvironment'>>;\nexport type EnvironmentPatchBody = Mutable<Body<'updateEnvironment'>>;\nexport type EnvironmentEnrollBody = Mutable<Body<'enrollEnvironment'>>;\nexport type EnvironmentAddMemberBody = Mutable<Body<'addEnvironmentMember'>>;\nexport type EnvironmentPortBody = Mutable<Body<'setEnvironmentPort'>>;\nexport type ListEnvironmentsQuery = Mutable<QueryOf<'listEnvironments'>>;\nexport type EnvironmentSshCert = Reply<'issueMyEnvironmentSshCert'>;\nexport type EnvironmentSshCertBody = Mutable<Body<'issueMyEnvironmentSshCert'>>;\nexport type EnvironmentSshCa = Reply<'getEnvironmentSshCa'>;\nexport type EnvironmentTaskList = Reply<'listEnvironmentTasks'>;\nexport type EnvironmentTaskCreateBody = Mutable<Body<'createEnvironmentTask'>>;\nexport type EnvironmentTaskCreated = Reply<'createEnvironmentTask'>;\nexport type EnvironmentTaskDetail = Reply<'getEnvironmentTask'>;\nexport type EnvironmentExecBody = Mutable<Body<'execEnvironment'>>;\nexport type EnvironmentExecResult = Schema<'EnvironmentExecResult'>;\nexport type EnvironmentFileList = Schema<'EnvironmentFileList'>;\nexport type EnvironmentFile = Schema<'EnvironmentFile'>;\nexport type EnvironmentFileWritten = Schema<'EnvironmentFileWritten'>;\nexport type EnvironmentJobStartBody = Mutable<Body<'startEnvironmentJob'>>;\nexport type EnvironmentJobStarted = Schema<'EnvironmentJobStarted'>;\nexport type EnvironmentJob = Schema<'EnvironmentJob'>;\nexport type GetEnvironmentJobQuery = Mutable<QueryOf<'getEnvironmentJob'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst envPath = (id: string, suffix = ''): string =>\n `/v1/environments/${encodeURIComponent(id)}${suffix}`;\n\n/** Absolute environment path → `/files/<each segment URL-encoded>`. */\nconst filePath = (path: string): string =>\n path\n .replace(/^\\/+/, '')\n .split('/')\n .map((s) => encodeURIComponent(s))\n .join('/');\n\nexport class EnvironmentMembers {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/members` — any role. */\n async list(envId: string, opts: CallOpts = {}): Promise<EnvironmentMember[]> {\n const raw = await this.http.json<Reply<'listEnvironmentMembers'>>(envPath(envId, '/members'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.members ?? [])];\n }\n\n /** `POST /v1/environments/{id}/members` — exactly one of `user_id` / `email`. */\n async add(\n envId: string,\n body: EnvironmentAddMemberBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentMemberCreated> {\n const raw = await this.http.json<Reply<'addEnvironmentMember', 201>>(\n envPath(envId, '/members'),\n { body, ext: opts.ext, signal: opts.signal },\n );\n return raw.member;\n }\n\n /** `PUT /v1/environments/{id}/members/me/ssh-key` — one `authorized_keys` line. */\n setSshKey(\n envId: string,\n publicKey: string,\n opts: CallOpts = {},\n ): Promise<Reply<'setMyEnvironmentSshKey'>> {\n const body: Mutable<Body<'setMyEnvironmentSshKey'>> = { public_key: publicKey };\n return this.http.json<Reply<'setMyEnvironmentSshKey'>>(envPath(envId, '/members/me/ssh-key'), {\n method: 'PUT',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/environments/{id}/members/{userId}` — 409 `last_owner` on demoting the last owner. */\n async setRole(\n envId: string,\n userId: string,\n role: EnvironmentRole,\n opts: CallOpts = {},\n ): Promise<Reply<'setEnvironmentMemberRole'>['member']> {\n const raw = await this.http.json<Reply<'setEnvironmentMemberRole'>>(\n envPath(envId, `/members/${encodeURIComponent(userId)}`),\n { method: 'PATCH', body: { role }, ext: opts.ext, signal: opts.signal },\n );\n return raw.member;\n }\n\n /** `DELETE /v1/environments/{id}/members/{userId}` — pass your own id to leave. */\n remove(\n envId: string,\n userId: string,\n opts: CallOpts = {},\n ): Promise<Reply<'removeEnvironmentMember'>> {\n return this.http.json<Reply<'removeEnvironmentMember'>>(\n envPath(envId, `/members/${encodeURIComponent(userId)}`),\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `POST /v1/environments/{id}/members/me/ssh-cert` — 12 h OpenSSH user certificate for your key. */\n sshCert(\n envId: string,\n body: EnvironmentSshCertBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentSshCert> {\n return this.http.json<EnvironmentSshCert>(envPath(envId, '/members/me/ssh-cert'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n\n/** `/v1/environments/{id}/tasks` — fire-and-forget agent tasks run in the environment. */\nexport class EnvironmentTasks {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/tasks` */\n list(envId: string, opts: CallOpts = {}): Promise<EnvironmentTaskList> {\n return this.http.json<EnvironmentTaskList>(envPath(envId, '/tasks'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/environments/{id}/tasks` — queued; you get a notification when it finishes. */\n create(\n envId: string,\n body: EnvironmentTaskCreateBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentTaskCreated> {\n return this.http.json<EnvironmentTaskCreated>(envPath(envId, '/tasks'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}/tasks/{taskId}` */\n get(envId: string, taskId: string, opts: CallOpts = {}): Promise<EnvironmentTaskDetail> {\n return this.http.json<EnvironmentTaskDetail>(\n envPath(envId, `/tasks/${encodeURIComponent(taskId)}`),\n { ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\n/** `/v1/environments/{id}/files` — read/write/list over the relay (developer role or higher). */\nexport class EnvironmentFiles {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/files?path=` — directory entries; no path → your workspace. */\n list(envId: string, path?: string, opts: CallOpts = {}): Promise<EnvironmentFileList> {\n return this.http.json<EnvironmentFileList>(envPath(envId, '/files'), {\n query: { path },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/environments/{id}/files/{path}` — UTF-8 text (64 KB default, `maxBytes` ≤ 512 KB). */\n get(\n envId: string,\n path: string,\n options: { maxBytes?: number } & CallOpts = {},\n ): Promise<EnvironmentFile> {\n return this.http.json<EnvironmentFile>(envPath(envId, `/files/${filePath(path)}`), {\n query: { max_bytes: options.maxBytes },\n ext: options.ext,\n signal: options.signal,\n });\n }\n\n /** `PUT /v1/environments/{id}/files/{path}` — replace with UTF-8 text (≤ 2 MB). */\n put(\n envId: string,\n path: string,\n content: string,\n opts: CallOpts = {},\n ): Promise<EnvironmentFileWritten> {\n return this.http.json<EnvironmentFileWritten>(envPath(envId, `/files/${filePath(path)}`), {\n method: 'PUT',\n rawBody: content,\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** `/v1/environments/{id}/jobs` — background jobs on the environment daemon. */\nexport class EnvironmentJobs {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/environments/{id}/jobs` — returns at once with `job_id`. */\n start(\n envId: string,\n body: EnvironmentJobStartBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentJobStarted> {\n return this.http.json<EnvironmentJobStarted>(envPath(envId, '/jobs'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}/jobs/{jobId}` — status + output (`since` = previous `next_offset`). */\n get(\n envId: string,\n jobId: string | number,\n query: GetEnvironmentJobQuery = {},\n opts: CallOpts = {},\n ): Promise<EnvironmentJob> {\n return this.http.json<EnvironmentJob>(\n envPath(envId, `/jobs/${encodeURIComponent(String(jobId))}`),\n {\n query: { since: query.since, tail: query.tail, session: query.session },\n ext: opts.ext,\n signal: opts.signal,\n },\n );\n }\n}\n\nexport class EnvironmentPorts {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/ports` — published (forwarded) ports. */\n async list(envId: string, opts: CallOpts = {}): Promise<EnvironmentPort[]> {\n const raw = await this.http.json<Reply<'listEnvironmentPorts'>>(envPath(envId, '/ports'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.ports ?? [])];\n }\n\n /** `PUT /v1/environments/{id}/ports/{port}` — publish or change visibility (upsert). */\n async set(\n envId: string,\n port: number,\n body: EnvironmentPortBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentPort> {\n const raw = await this.http.json<Reply<'setEnvironmentPort'>>(\n envPath(envId, `/ports/${encodeURIComponent(String(port))}`),\n { method: 'PUT', body, ext: opts.ext, signal: opts.signal },\n );\n return raw.port;\n }\n\n /** `DELETE /v1/environments/{id}/ports/{port}` — unpublish. */\n remove(\n envId: string,\n port: number,\n opts: CallOpts = {},\n ): Promise<Reply<'removeEnvironmentPort'>> {\n return this.http.json<Reply<'removeEnvironmentPort'>>(\n envPath(envId, `/ports/${encodeURIComponent(String(port))}`),\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class EnvironmentSecrets {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/secrets` — names and timestamps only, never values. */\n async list(envId: string, opts: CallOpts = {}): Promise<EnvironmentSecret[]> {\n const raw = await this.http.json<Reply<'listEnvironmentSecrets'>>(envPath(envId, '/secrets'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.secrets ?? [])];\n }\n\n /** `PUT /v1/environments/{id}/secrets/{name}` — upsert; `name` is `ENV_STYLE`. */\n set(\n envId: string,\n name: string,\n value: string,\n opts: CallOpts = {},\n ): Promise<EnvironmentSecretSet> {\n const body: Mutable<Body<'setEnvironmentSecret'>> = { value };\n return this.http.json<EnvironmentSecretSet>(\n envPath(envId, `/secrets/${encodeURIComponent(name)}`),\n { method: 'PUT', body, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `DELETE /v1/environments/{id}/secrets/{name}` */\n remove(\n envId: string,\n name: string,\n opts: CallOpts = {},\n ): Promise<Reply<'removeEnvironmentSecret'>> {\n return this.http.json<Reply<'removeEnvironmentSecret'>>(\n envPath(envId, `/secrets/${encodeURIComponent(name)}`),\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class Environments {\n readonly members: EnvironmentMembers;\n readonly ports: EnvironmentPorts;\n readonly secrets: EnvironmentSecrets;\n readonly tasks: EnvironmentTasks;\n readonly files: EnvironmentFiles;\n readonly jobs: EnvironmentJobs;\n\n constructor(private readonly http: HttpClient) {\n this.members = new EnvironmentMembers(http);\n this.ports = new EnvironmentPorts(http);\n this.secrets = new EnvironmentSecrets(http);\n this.tasks = new EnvironmentTasks(http);\n this.files = new EnvironmentFiles(http);\n this.jobs = new EnvironmentJobs(http);\n }\n\n /**\n * `POST /v1/environments/{id}/exec` — run one relay op and wait (developer+). `op` defaults to\n * `shell` with `command`; 409 `environment_offline`, 504 `host_timeout`.\n */\n exec(\n envId: string,\n body: EnvironmentExecBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentExecResult> {\n return this.http.json<EnvironmentExecResult>(envPath(envId, '/exec'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}/ssh-ca` — CA public keys to trust (`@cert-authority` lines). */\n sshCa(envId: string, opts: CallOpts = {}): Promise<EnvironmentSshCa> {\n return this.http.json<EnvironmentSshCa>(envPath(envId, '/ssh-ca'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/environments?project_id=&for_user_id=me` — newest first, every state. */\n async list(query: ListEnvironmentsQuery = {}, opts: CallOpts = {}): Promise<Environment[]> {\n const raw = await this.http.json<Reply<'listEnvironments'>>('/v1/environments', {\n query: { project_id: query.project_id, for_user_id: query.for_user_id },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.environments ?? [])];\n }\n\n /**\n * `POST /v1/environments` — `byo` starts `pending`; managed providers start\n * `creating`. 409 `already_has_env` in a `vm_per_dev` project (the error\n * body carries the `environment_id` to reuse).\n */\n async create(body: EnvironmentCreateBody, opts: CallOpts = {}): Promise<Environment> {\n const raw = await this.http.json<Reply<'createEnvironment', 201>>('/v1/environments', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return raw.environment;\n }\n\n /**\n * `POST /v1/environments/enroll` — daemon side. The one-time `codai_env_…`\n * token in the body is the only credential; the client's API key header is\n * ignored by this route. Managed environments additionally receive a\n * freshly minted `api_key`, returned exactly once.\n */\n enroll(body: EnvironmentEnrollBody, opts: CallOpts = {}): Promise<EnvironmentEnrolled> {\n return this.http.json<EnvironmentEnrolled>('/v1/environments/enroll', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n // The token is consumed on success; a retried POST would 401.\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}` — environment, your role, members, ports, recent events. */\n get(envId: string, opts: CallOpts = {}): Promise<EnvironmentDetail> {\n return this.http.json<EnvironmentDetail>(envPath(envId), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/environments/{id}` — `name` and/or `idle_timeout_minutes` (5..1440). */\n async update(\n envId: string,\n body: EnvironmentPatchBody,\n opts: CallOpts = {},\n ): Promise<Environment> {\n const raw = await this.http.json<Reply<'updateEnvironment'>>(envPath(envId), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n return raw.environment;\n }\n\n /** `POST /v1/environments/{id}/start` — managed providers only (`stopped` → `starting`). */\n start(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'start', opts);\n }\n\n /** `POST /v1/environments/{id}/stop` — managed providers only (`running` → `stopping`). */\n stop(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'stop', opts);\n }\n\n /** `POST /v1/environments/{id}/archive` — keeps history, releases the machine. */\n archive(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'archive', opts);\n }\n\n /** `POST /v1/environments/{id}/destroy` — owner only; terminal. */\n destroy(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'destroy', opts);\n }\n\n /**\n * `POST /v1/environments/{id}/enroll-token` — `byo` only; a 30-minute\n * one-time token for `enroll()`. Minting again replaces the previous one.\n */\n enrollToken(envId: string, opts: CallOpts = {}): Promise<EnvironmentEnrollToken> {\n return this.http.json<EnvironmentEnrollToken>(envPath(envId, '/enroll-token'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n private transition(\n envId: string,\n action: 'start' | 'stop' | 'archive' | 'destroy',\n opts: CallOpts,\n ): Promise<EnvironmentTransition> {\n return this.http.json<EnvironmentTransition>(envPath(envId, `/${action}`), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** Unauthenticated probes at the root: `/health`, `/health/ready`, `/status`. */\nimport { type HttpClient } from '../http';\nimport { type Reply } from './_shared';\n\nexport type HealthResponse = Reply<'getHealth'>;\nexport type HealthReadyResponse = Reply<'getHealthReady'>;\nexport type StatusResponse = Reply<'getStatus'>;\n\nexport class Health {\n constructor(private readonly http: HttpClient) {}\n\n /** Liveness probe. */\n get(opts: { signal?: AbortSignal } = {}): Promise<HealthResponse> {\n return this.http.json<HealthResponse>('/health', { signal: opts.signal, noRetry: true });\n }\n\n /**\n * Deep readiness probe. A 503 is returned as `{ ok: false, ... }` rather\n * than thrown, so callers can read the failing check.\n */\n async ready(\n opts: { signal?: AbortSignal } = {},\n ): Promise<HealthReadyResponse & { httpStatus: number }> {\n const res = await this.http.request('/health/ready', {\n signal: opts.signal,\n noRetry: true,\n acceptStatus: [503],\n });\n const body = (await res.json()) as HealthReadyResponse;\n return { ...body, httpStatus: res.status };\n }\n\n /** Registry snapshot (aliases + provider health). */\n status(opts: { signal?: AbortSignal } = {}): Promise<StatusResponse> {\n return this.http.json<StatusResponse>('/status', { signal: opts.signal, noRetry: true });\n }\n}\n","/** `/v1/hosts/*` — host relay (desktop announces itself; clients exec ops on it). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type HostPresence = Schema<'HostPresence'>;\nexport type HostOp = Schema<'HostOp'>;\nexport type HostExecBody = Mutable<Body<'execOnHost'>>;\nexport type HostExecResponse = Reply<'execOnHost'>;\nexport type HostExecRequest = Schema<'HostExecRequest'>;\nexport type HostExecResultBody = Mutable<Body<'postHostExecResult'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\n/** Frames of `GET /v1/hosts/stream`. */\nexport type HostStreamEvent =\n | { event: 'hello'; data: { device_id: string; heartbeat_ms: number } }\n | { event: 'ping'; data: { t: number } }\n | { event: 'exec'; data: HostExecRequest }\n | { event: string; data: Record<string, unknown> };\n\nexport class Hosts {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/hosts` — your devices currently connected as hosts. */\n async list(opts: CallOpts = {}): Promise<HostPresence[]> {\n const raw = await this.http.json<Reply<'listHosts'>>('/v1/hosts', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.hosts ?? [])];\n }\n\n /**\n * `POST /v1/hosts/{deviceId}/exec` — run one op on a connected host and\n * block until it answers (or `timeout_ms`, default 60 s).\n */\n exec(\n deviceId: string,\n op: HostOp,\n args: Record<string, unknown> = {},\n extra: { timeoutMs?: number; label?: string } & CallOpts = {},\n ): Promise<HostExecResponse> {\n const body: HostExecBody = {\n op,\n args,\n ...(extra.timeoutMs !== undefined ? { timeout_ms: extra.timeoutMs } : {}),\n ...(extra.label !== undefined ? { label: extra.label } : {}),\n };\n return this.http.json<HostExecResponse>(`/v1/hosts/${encodeURIComponent(deviceId)}/exec`, {\n body,\n ext: extra.ext,\n signal: extra.signal,\n // The gateway itself waits up to timeout_ms + 2 s; give the HTTP layer headroom.\n timeoutMs: (extra.timeoutMs ?? 60_000) + 10_000,\n noRetry: true,\n });\n }\n\n /** `POST /v1/hosts/exec/{reqId}/result` — host side: deliver an exec result. */\n postResult(\n reqId: string,\n body: HostExecResultBody,\n opts: CallOpts = {},\n ): Promise<Reply<'postHostExecResult'>> {\n return this.http.json<Reply<'postHostExecResult'>>(\n `/v1/hosts/exec/${encodeURIComponent(reqId)}/result`,\n { body, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /**\n * `GET /v1/hosts/stream?os=&hostname=&roots=` — host side: announce this\n * device and receive `hello` / `ping` / `exec` events. Closed by the server\n * after 6 h; reconnect to re-announce presence.\n */\n async *stream(\n query: { os?: string; hostname?: string; roots?: string[] } = {},\n opts: CallOpts = {},\n ): AsyncGenerator<HostStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/hosts/stream', {\n query: {\n os: query.os,\n hostname: query.hostname,\n roots: query.roots?.length ? query.roots.join(',') : undefined,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data) continue;\n yield { event: frame.event, data } as HostStreamEvent;\n }\n }\n}\n","/**\n * `/v1/assets` — the caller's codai Studio assets (media generated with `response_format: 'url'` and every finished\n * video job). Owner-scoped (a foreign id is 404), kept 90 days; each `ready` asset carries a 1 h V4 signed `url`.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type QueryOf, type Reply, type Schema } from './_shared';\n\n/** A stored asset (`GET /v1/assets/{id}`; `data` items with `response_format: 'url'`). */\nexport type AssetDto = Schema<'AssetDto'>;\nexport type AssetKind = Schema<'AssetKind'>;\nexport type AssetList = Reply<'listAssets'>;\nexport type AssetDeleted = Reply<'deleteAsset'>;\nexport type AssetListQuery = QueryOf<'listAssets'>;\n/** `b64_json` (default, inline bytes) or `url` (stored asset + 1 h signed URL; 503 `assets_unavailable` without storage). */\nexport type MediaResponseFormat = Schema<'MediaResponseFormat'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\n/** True for a `data` item that is a stored asset rather than inline base64. */\nexport function isAssetDto(item: unknown): item is AssetDto {\n return typeof item === 'object' && item !== null && 'asset_id' in item;\n}\n\nexport class Assets {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/assets` — newest first, `limit` ≤ 100 (default 30). Paginate by passing `next_before` as `before`. */\n list(query: AssetListQuery = {}, opts: CallOpts = {}): Promise<AssetList> {\n return this.http.json<AssetList>('/v1/assets', {\n query: { kind: query.kind, before: query.before, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Iterate every asset across pages (`list` with `before` = previous `next_before`). */\n async *iterate(\n query: Omit<AssetListQuery, 'before'> = {},\n opts: CallOpts = {},\n ): AsyncGenerator<AssetDto, void, undefined> {\n let before: string | undefined;\n for (;;) {\n const page = await this.list({ ...query, before }, opts);\n yield* page.data;\n if (!page.next_before) return;\n before = page.next_before;\n }\n }\n\n /** `GET /v1/assets/{id}` — one asset with a fresh 1 h signed `url` (`null` while not `ready`). */\n retrieve(id: string, opts: CallOpts = {}): Promise<AssetDto> {\n return this.http.json<AssetDto>(`/v1/assets/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * A fresh signed URL of the asset's bytes (valid 1 h), from `GET /v1/assets/{id}`. Throws when the asset has no\n * content yet. Use it in `<audio>`/`<video>`/`fetch` — it needs no Authorization header.\n */\n async contentUrl(id: string, opts: CallOpts = {}): Promise<string> {\n const a = await this.retrieve(id, opts);\n if (!a.url) throw new Error(`codai asset ${id} has no content yet (status ${a.status})`);\n return a.url;\n }\n\n /**\n * The authenticated redirect endpoint `GET /v1/assets/{id}/content` (302 to the signed URL). Useful for tools that\n * follow redirects with the API key (`curl -L -H 'Authorization: Bearer …'`); browsers should use `contentUrl()`.\n */\n contentPath(id: string): string {\n return this.http.url(`/v1/assets/${encodeURIComponent(id)}/content`);\n }\n\n /** Download the asset's bytes (fetches the signed URL, no API key sent to storage). */\n async content(id: string, opts: CallOpts = {}): Promise<Uint8Array> {\n const url = await this.contentUrl(id, opts);\n const res = await fetch(url, opts.signal ? { signal: opts.signal } : {});\n if (!res.ok) throw new Error(`codai asset ${id} download failed: HTTP ${res.status}`);\n return new Uint8Array(await res.arrayBuffer());\n }\n\n /** `DELETE /v1/assets/{id}` — deletes the object; signed URLs already handed out stop working. */\n delete(id: string, opts: CallOpts = {}): Promise<AssetDeleted> {\n return this.http.json<AssetDeleted>(`/v1/assets/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `POST /v1/images/generations` and `POST /v1/images/edits` — Gemini image models on Vertex AI.\n * `codai-image` (default, gemini-3.1-flash-image, EU), `codai-image-fast`, `codai-image-pro`.\n * Output from the EU endpoint carries C2PA credentials + SynthID: keep the bytes as returned.\n *\n * `response_format: 'url'` stores each image as a codai Studio asset (kept 90 days) and returns `assets`\n * (1 h signed URLs) instead of decoded bytes; the default `b64_json` is unchanged.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\nimport { type AssetDto, isAssetDto } from './assets';\n\nexport type ImagesRequest = Mutable<Body<'createImage'>>;\nexport type ImagesResponse = Reply<'createImage'>;\nexport type ImageEditRequest = Mutable<Body<'editImage'>>;\n\nexport interface ImagesResult {\n /** Decoded image bytes, one per generated image (see `mimeTypes`). Empty with `response_format: 'url'`. */\n images: Uint8Array[];\n /** MIME type of each generated image (usually `image/png`). */\n mimeTypes: string[];\n /** Stored assets with signed URLs (`response_format: 'url'` only; empty otherwise). */\n assets: AssetDto[];\n raw: ImagesResponse;\n /** Upstream model that produced the images (`x-codai-routed-to`). */\n routedTo: string | null;\n /** Vertex location that processed the request, `eu` or `global` (`x-codai-data-region`). */\n dataRegion: string | null;\n /** Usage-based charge for this request in micro-USD (`x-codai-cost-micro-usd`). */\n costMicroUsd: number | null;\n headers: Headers;\n}\n\n/** Image generation typically takes 5–30 s; the gateway allows 120 s upstream. */\nconst MIN_IMAGE_TIMEOUT_MS = 150_000;\n\nfunction decodeBase64(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nexport class Images {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Generate images. Needs a real API key (ephemeral tokens are rejected).\n * Pass `reference_images` to keep a logo/palette/product consistent.\n */\n async generate(\n body: Omit<ImagesRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ImagesResult> {\n return this.post(\n '/v1/images/generations',\n { ...body, model: body.model ?? 'codai-image' },\n opts,\n );\n }\n\n /**\n * Edit one or more input images (`image`: one `{ b64_json, mime_type }` or an array of up to 14)\n * from a text instruction. JSON body; `mask` is not supported — describe the region in `prompt`.\n */\n async edit(\n body: Omit<ImageEditRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ImagesResult> {\n return this.post('/v1/images/edits', { ...body, model: body.model ?? 'codai-image' }, opts);\n }\n\n private async post(\n path: string,\n body: unknown,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<ImagesResult> {\n const res = await this.http.request(path, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n // 0 = timeout disabled on the client; otherwise never cap below the image floor.\n timeoutMs:\n this.http.timeoutMs === 0 ? 0 : Math.max(this.http.timeoutMs, MIN_IMAGE_TIMEOUT_MS),\n });\n const raw = (await res.json()) as ImagesResponse;\n const cost = res.headers.get('x-codai-cost-micro-usd');\n const data = raw.data ?? [];\n const assets = data.filter(isAssetDto);\n const inline = data.filter((d): d is Exclude<typeof d, AssetDto> => !isAssetDto(d));\n return {\n images: inline.map((d) => decodeBase64(d.b64_json)),\n mimeTypes: data.map((d) => d.mime_type ?? 'image/png'),\n assets,\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n dataRegion: res.headers.get('x-codai-data-region'),\n costMicroUsd: cost === null ? null : Number(cost),\n headers: res.headers,\n };\n }\n}\n","/**\n * codai Studio media lanes (US-only, English prompts; refused for EU data-residency keys).\n *\n * `POST /v1/audio/music` — `codai-music` (Lyria 3 Clip, 30 s MP3 with vocals/lyrics), `codai-music-pro`\n * (Lyria 3 Pro, full song up to 184 s), `codai-music-legacy` (Lyria 2, 30 s instrumental WAV).\n * `POST /v1/videos` — Veo 3.1 Fast: starts a job (HTTP 202).\n * `GET /v1/videos/{id}` — polls the job; the MP4 is returned (and billed once) when it succeeds.\n * `POST /v1/studio/renders` — `codai-render`: renders a HyperFrames HTML composition to MP4 (HTTP 202).\n * `GET /v1/studio/renders/{id}` — polls the render; the MP4 asset is returned (and billed once) when it succeeds.\n * `GET /v1/studio/renders` — lists renders (no polling, no URLs); `root_render_id` = one timeline's versions.\n * `POST /v1/studio/timelines` — renders a list of image/video scenes (optional narration + music), HTTP 202.\n * `POST /v1/studio/renders/{id}/scenes/{sceneId}/regenerate` — new render with one timeline scene replaced (202).\n *\n * `response_format: 'url'` (music body, video poll query) returns stored assets with 1 h signed URLs (`assets`)\n * instead of base64 bytes; the default `b64_json` shape is unchanged. Wire types are declared here.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type AssetDto, type MediaResponseFormat, isAssetDto } from './assets';\n\nexport interface MusicRequest {\n /** `codai-music` (default, Lyria 3 Clip), `codai-music-pro` (Lyria 3 Pro) or `codai-music-legacy` (Lyria 2). */\n model?: 'codai-music' | 'codai-music-pro' | 'codai-music-legacy' | (string & {});\n /** Music description (genre, mood, instruments; no artist names). English is most reliable. */\n prompt: string;\n /** Lyrics to sing exactly (Lyria 3, <= 3000 chars). Non-English lyrics are best effort (see `lyrics_match`). */\n lyrics?: string;\n /** Instrumental only, no vocals (Lyria 3). */\n instrumental?: boolean;\n /** Target tempo, 40-220 (Lyria 3). */\n bpm?: number;\n /** Target length 10-184 s; `codai-music-pro` only (`codai-music` is always ~30 s). */\n duration_seconds?: number;\n /** Lyrics language hint, e.g. `ro`. */\n language?: string;\n /** `codai-music-legacy` only (400 for Lyria 3). */\n negative_prompt?: string;\n /** `codai-music-legacy` only (400 for Lyria 3). A seed forces a single clip. */\n seed?: number;\n /** Number of clips, 1-4; more than 1 only with `codai-music-legacy` (ignored when `seed` is set). */\n n?: number;\n /** `b64_json` (default) or `url` — store each clip as an asset and return signed URLs in `assets`. */\n response_format?: MediaResponseFormat;\n}\n\n/** Extra per-item fields returned by the Lyria 3 models (also present on `AssetDto` items). */\nexport interface MusicTrackMeta {\n /** Lyrics as sung, with `[start:end]` timing per line (Lyria 3 only). */\n lyrics?: string | null;\n /** The model's description of the track (may include `bpm` / `duration_secs`). */\n caption?: string | null;\n /** 0..1 match between the supplied `lyrics` and the sung words; `null` when not checked. */\n lyrics_match?: number | null;\n /** e.g. `lyrics_mismatch`, `lyrics_check_unavailable`. */\n warnings?: string[];\n}\n\nexport interface MusicClip extends MusicTrackMeta {\n b64_json: string;\n mime_type: string;\n duration_seconds: number;\n sample_rate?: number;\n}\n\nexport interface MusicResponse {\n created: number;\n model: string;\n /** `MusicClip` items by default; `AssetDto` items with `response_format: 'url'`. */\n data: Array<MusicClip | (AssetDto & MusicTrackMeta)>;\n}\n\nexport interface MusicResult {\n /** Decoded audio bytes (MP3 for Lyria 3, WAV for legacy), one per clip. Empty with `response_format: 'url'`. */\n clips: Uint8Array[];\n /** MIME type of each clip (`audio/mpeg` or `audio/wav`). */\n mimeTypes: string[];\n /** Stored assets with signed URLs (`response_format: 'url'` only; empty otherwise). */\n assets: AssetDto[];\n /** Per-item lyrics / caption / lyrics_match / warnings, in `data` order. */\n tracks: MusicTrackMeta[];\n /** All warnings across items (deduplicated), e.g. `lyrics_mismatch`. */\n warnings: string[];\n raw: MusicResponse;\n /** Upstream model (`x-codai-routed-to`). */\n routedTo: string | null;\n /** Charge in micro-USD (`x-codai-cost-micro-usd`). */\n costMicroUsd: number | null;\n headers: Headers;\n}\n\nexport interface VideoRequest {\n model?: string;\n /** English prompt. */\n prompt: string;\n negative_prompt?: string;\n seconds?: 4 | 6 | 8;\n aspect_ratio?: '16:9' | '9:16';\n resolution?: '720p' | '1080p';\n /** Generate an audio track (default true). */\n audio?: boolean;\n /** Optional first frame (image-to-video); forces 8 s. */\n image?: { b64_json: string; mime_type?: 'image/png' | 'image/jpeg' };\n seed?: number;\n}\n\nexport interface VideoJob {\n id: string;\n object: 'video.job';\n status: 'running';\n model: string;\n seconds: number;\n /** Price of the job in micro-USD (string, bigint-safe). */\n estimated_cost_micro_usd: string;\n}\n\nexport type VideoStatus = 'running' | 'succeeded' | 'failed' | 'filtered';\n\nexport interface VideoJobStatus {\n id: string;\n object: 'video.job';\n status: VideoStatus;\n error?: string;\n model?: string;\n seconds?: number;\n /** Inline MP4 by default; one `AssetDto` when polled with `responseFormat: 'url'`. */\n data?: Array<{ b64_json: string; mime_type: string } | AssetDto>;\n}\n\nexport interface VideoResult {\n /** Decoded MP4 bytes. Empty with `responseFormat: 'url'` (use `asset.url`). */\n video: Uint8Array;\n mimeType: string;\n id: string;\n seconds: number | null;\n /** The stored asset (`responseFormat: 'url'` only). */\n asset: AssetDto | null;\n raw: VideoJobStatus;\n}\n\nexport type RenderAspectRatio = '16:9' | '9:16' | '1:1' | '4:5';\nexport type RenderQuality = 'draft' | 'final';\nexport type RenderStatus = 'queued' | 'rendering' | 'succeeded' | 'failed';\n/**\n * Visible AI label burned into the video (EU AI Act art. 50(4)): `corner` = small \"AI-generated\" label bottom-right\n * for the whole video, `end_card` = final ~2 s card with the label, `none` = nothing. Default: `corner` when the\n * render uses TTS narration or AI-generated images, else `none`; `none` with TTS narration is 400 `ai_label_required`.\n */\nexport type RenderAiLabel = 'none' | 'corner' | 'end_card';\n\nexport interface RenderRequest {\n /** Defaults to `codai-render`. */\n model?: string;\n /**\n * A complete HyperFrames composition (`index.html`, <= 2,000,000 chars). Reference Studio assets as\n * `asset:<asset_id>` in any `src` / `href` / `url(...)` (max 50 distinct assets).\n */\n html: string;\n /** HyperFrames composition variables. */\n variables?: Record<string, unknown>;\n /** Must match the root `data-width` / `data-height` (default `16:9`). */\n aspect_ratio?: RenderAspectRatio;\n /** `final` (default) or `draft` (15 fps, 540p short side, no loudness pass, half price). */\n quality?: RenderQuality;\n /** `final` only (default 30). */\n fps?: 24 | 25 | 30;\n title?: string;\n /** EU AI Act art. 50(4) label; omit for the default (`corner` with TTS narration or AI images, else `none`). */\n ai_label?: RenderAiLabel;\n}\n\nexport interface RenderJob {\n id: string;\n object: 'studio.render';\n status: 'queued';\n model: string;\n quality: RenderQuality;\n aspect_ratio: RenderAspectRatio;\n fps: number;\n /** Micro-USD per output second (string, bigint-safe). */\n price_micro_usd_per_second: string;\n /** Minimum charge in micro-USD (string, bigint-safe). */\n minimum_micro_usd: string;\n /** The resolved AI label. */\n ai_label?: RenderAiLabel;\n}\n\nexport interface RenderQa {\n duration_seconds: number;\n width: number;\n height: number;\n lufs: number | null;\n warnings: Array<'silent_audio' | 'no_audio' | 'lufs_off_target'>;\n}\n\nexport interface RenderJobStatus {\n id: string;\n object: 'studio.render';\n status: RenderStatus;\n /** 0..1 */\n progress: number;\n quality: RenderQuality;\n aspect_ratio: RenderAspectRatio;\n fps: number;\n /** `<code>: <message>` when `failed`. */\n error: string | null;\n qa?: RenderQa | null;\n /** Charge in micro-USD (string), once succeeded. */\n cost_micro_usd?: string | null;\n /** The MP4 as one `AssetDto` (`kind: 'render'`), only when succeeded. */\n data?: AssetDto[];\n /** Signed JPEG poster URL, only when succeeded. */\n poster_url?: string | null;\n /** Worker stage while rendering; `generating_scene` while a regenerated video scene is generated (status `queued`). */\n stage?: string | null;\n title?: string | null;\n /** Timeline renders: the render this one was regenerated from. */\n parent_render_id?: string | null;\n /** Timeline renders: the original render of the version chain. */\n root_render_id?: string | null;\n /** Scenes of a timeline render; `null` for HTML and deck renders. */\n timeline?: RenderTimeline | null;\n /** The resolved AI label (EU AI Act art. 50(4)). */\n ai_label?: RenderAiLabel;\n}\n\nexport type SceneKind = 'image' | 'video';\nexport type SceneFit = 'cover' | 'contain';\n\nexport interface SceneNarration {\n text: string;\n asset_id: string | null;\n seconds: number | null;\n}\n\nexport interface TimelineScene {\n /** Stable id (`^[a-z0-9-]{1,32}$`); pass it to `regenerateScene`. */\n id: string;\n kind: SceneKind;\n asset_id: string;\n seconds: number;\n fit: SceneFit;\n /** Video scenes only. */\n video_volume?: number;\n prompt: string | null;\n narration: SceneNarration | null;\n revision: number;\n /** The visual (`url` signed only with `expandAssets`). */\n asset: AssetDto | null;\n /** The narration audio (`url` signed only with `expandAssets`). */\n narration_asset: AssetDto | null;\n}\n\nexport interface RenderTimeline {\n transition: 'fade' | 'none';\n music: { asset_id: string; volume: number } | null;\n scenes: TimelineScene[];\n}\n\nexport interface RenderListItem {\n id: string;\n object: 'studio.render';\n status: RenderStatus;\n title: string | null;\n quality: RenderQuality;\n aspect_ratio: RenderAspectRatio;\n fps: number;\n duration_seconds: number | null;\n /** Micro-USD (string); `\"0\"` until succeeded. */\n cost_micro_usd: string;\n created_at: string;\n parent_render_id: string | null;\n root_render_id: string | null;\n has_timeline: boolean;\n scene_count: number;\n}\n\nexport interface RenderList {\n object: 'list';\n data: RenderListItem[];\n /** Pass as `before` for the next page; `null` on the last page. */\n next_before: string | null;\n}\n\nexport interface TimelineSceneInput {\n /** Optional stable id, unique in the timeline (default `s1`…`sN`). */\n id?: string;\n kind: SceneKind;\n /** One of your ready image (kind `image`) or video (kind `video`) assets. */\n asset_id: string;\n /** 2..30 (default 5); a narrated scene lasts at least narration + 0.6 s. */\n seconds?: number;\n fit?: SceneFit;\n /** 0..1, video scenes only (default 1, or 0 when narrated). */\n video_volume?: number;\n /** Stored and reused by a later `regenerateScene` without a prompt. */\n prompt?: string;\n /** Narrated now (billed per call); not available for EU data-residency accounts. */\n narration?: { text: string; voice?: string; language?: string };\n}\n\nexport interface TimelineRequest {\n /** Defaults to `codai-render`. */\n model?: string;\n title?: string;\n aspect_ratio?: RenderAspectRatio;\n quality?: RenderQuality;\n /** `final` only (default 30). */\n fps?: 24 | 25 | 30;\n /** Default `fade` (0.5 s crossfade). */\n transition?: 'fade' | 'none';\n /** One of your ready audio assets, played under the whole timeline. */\n music_asset_id?: string;\n /** 0..1 (default 0.126). */\n music_volume?: number;\n narration_defaults?: {\n model?: 'codai-speech' | 'codai-speech-expressive';\n voice?: string;\n /** BCP-47, default `ro-RO`. */\n language?: string;\n instructions?: string;\n };\n /** 1..30 scenes, at most 180 s in total. */\n scenes: TimelineSceneInput[];\n}\n\nexport interface TimelineJob extends RenderJob {\n /** Narration already charged by this request, micro-USD (string). */\n narration_cost_micro_usd: string;\n scene_count: number;\n duration_seconds: number;\n /** Equal to `id`; regenerated versions keep it. */\n root_render_id: string;\n}\n\nexport interface SceneRegenerateRequest {\n /** Reuse an owned image/video asset, or generate: `codai-image` (image scene) / `codai-video` 4|6|8 s (video scene). */\n visual?: { asset_id: string } | { prompt?: string; model?: string; seconds?: 4 | 6 | 8 };\n /** Reuse an owned audio asset, re-narrate (`text` omitted = stored text), or `null` to remove the narration. */\n narration?: { asset_id: string } | { text?: string; voice?: string } | null;\n quality?: RenderQuality;\n}\n\nexport interface SceneRegenerateJob {\n id: string;\n object: 'studio.render';\n status: 'queued';\n parent_render_id: string;\n root_render_id: string;\n scene_id: string;\n /** Generation already charged (image, narration, video clip), micro-USD (string). */\n scene_cost_micro_usd: string;\n price_micro_usd_per_second: string;\n minimum_micro_usd: string;\n /** The resolved AI label of the new render. */\n ai_label?: RenderAiLabel;\n}\n\nexport interface RenderResult {\n id: string;\n /** The stored MP4 (1 h signed `url`; refresh with `assets.retrieve(id)`). */\n asset: AssetDto;\n posterUrl: string | null;\n qa: RenderQa | null;\n costMicroUsd: number | null;\n raw: RenderJobStatus;\n}\n\n/** Lyria 3 Pro can take minutes for a long song; the gateway allows 240 s upstream (+ lyrics check). */\nconst MIN_MUSIC_TIMEOUT_MS = 300_000;\n\nfunction decodeBase64(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Music {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Generate music (`POST /v1/audio/music`): `codai-music` 30 s clip with vocals, `codai-music-pro` full song up to\n * 184 s, `codai-music-legacy` instrumental Lyria 2. List price $0.04 / $0.08 / $0.06 per call.\n */\n async generate(\n body: MusicRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<MusicResult> {\n const res = await this.http.request('/v1/audio/music', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n // 0 = timeout disabled on the client; otherwise never cap below the music floor.\n timeoutMs:\n this.http.timeoutMs === 0 ? 0 : Math.max(this.http.timeoutMs, MIN_MUSIC_TIMEOUT_MS),\n });\n const raw = (await res.json()) as MusicResponse;\n const cost = res.headers.get('x-codai-cost-micro-usd');\n const data = raw.data ?? [];\n const inline = data.filter((d): d is MusicClip => !isAssetDto(d));\n const tracks = data.map((d): MusicTrackMeta => ({\n lyrics: d.lyrics ?? null,\n caption: d.caption ?? null,\n lyrics_match: d.lyrics_match ?? null,\n warnings: d.warnings ?? [],\n }));\n return {\n clips: inline.map((d) => decodeBase64(d.b64_json)),\n mimeTypes: data.map((d) => d.mime_type ?? 'audio/wav'),\n assets: data.filter(isAssetDto),\n tracks,\n warnings: [...new Set(tracks.flatMap((t) => t.warnings ?? []))],\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n costMicroUsd: cost === null ? null : Number(cost),\n headers: res.headers,\n };\n }\n}\n\nexport class Videos {\n constructor(private readonly http: HttpClient) {}\n\n /** Start a video job (`POST /v1/videos`, HTTP 202). Nothing is charged until it succeeds. */\n async create(\n body: VideoRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<VideoJob> {\n const res = await this.http.request('/v1/videos', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return (await res.json()) as VideoJob;\n }\n\n /**\n * Poll a job (`GET /v1/videos/{id}`). Billed exactly once ($0.10 / s) on the first `succeeded` poll, across gateway\n * instances. `responseFormat: 'url'` returns the stored MP4 as one `AssetDto` (1 h signed URL) instead of base64.\n */\n async retrieve(\n id: string,\n opts: {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n responseFormat?: MediaResponseFormat;\n } = {},\n ): Promise<VideoJobStatus> {\n const res = await this.http.request(`/v1/videos/${encodeURIComponent(id)}`, {\n method: 'GET',\n query: { response_format: opts.responseFormat },\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as VideoJobStatus;\n }\n\n /** Create a job and poll until it succeeds. Throws on `failed`, `filtered` or timeout. */\n async generate(\n body: VideoRequest,\n opts: {\n pollIntervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n ext?: CodaiRequestExtensions;\n /** `url`: the final poll returns the stored asset (`result.asset`) instead of the MP4 bytes. */\n responseFormat?: MediaResponseFormat;\n } = {},\n ): Promise<VideoResult> {\n const { pollIntervalMs = 5000, timeoutMs = 300_000, signal, ext, responseFormat } = opts;\n const job = await this.create(body, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrieve(job.id, { ext, signal, responseFormat });\n if (st.status === 'succeeded') {\n const d = st.data?.[0];\n if (isAssetDto(d)) {\n return {\n video: new Uint8Array(0),\n mimeType: d.mime_type,\n id: job.id,\n seconds: st.seconds ?? job.seconds ?? null,\n asset: d,\n raw: st,\n };\n }\n if (!d?.b64_json) throw new Error(`codai video job ${job.id} succeeded without video data`);\n return {\n video: decodeBase64(d.b64_json),\n mimeType: d.mime_type ?? 'video/mp4',\n id: job.id,\n seconds: st.seconds ?? job.seconds ?? null,\n asset: null,\n raw: st,\n };\n }\n if (st.status === 'failed' || st.status === 'filtered') {\n throw new Error(`codai video job ${st.status}: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai video job ${job.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n}\n\nexport class Renders {\n constructor(private readonly http: HttpClient) {}\n\n /** Queue a render (`POST /v1/studio/renders`, HTTP 202). Nothing is charged until it succeeds. */\n async create(\n body: RenderRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<RenderJob> {\n const res = await this.http.request('/v1/studio/renders', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return (await res.json()) as RenderJob;\n }\n\n /**\n * Poll a render (`GET /v1/studio/renders/{id}`). Billed exactly once (final $0.01 / s, min $0.05; draft half) on the\n * first poll that sees the finished render; failed renders cost nothing.\n * `expandAssets` signs the timeline's scene and narration assets (`?expand=assets`).\n */\n async retrieve(\n id: string,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal; expandAssets?: boolean } = {},\n ): Promise<RenderJobStatus> {\n const res = await this.http.request(`/v1/studio/renders/${encodeURIComponent(id)}`, {\n method: 'GET',\n query: { expand: opts.expandAssets ? 'assets' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as RenderJobStatus;\n }\n\n /**\n * List renders newest first (`GET /v1/studio/renders`) — no polling, no signed URLs. `rootRenderId` restricts the\n * list to one timeline's version chain; pass `next_before` as `before` for the next page.\n */\n async list(\n params: { before?: string; limit?: number; rootRenderId?: string } = {},\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<RenderList> {\n const res = await this.http.request('/v1/studio/renders', {\n method: 'GET',\n query: {\n before: params.before,\n limit: params.limit,\n root_render_id: params.rootRenderId,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as RenderList;\n }\n\n /**\n * Render a scene timeline (`POST /v1/studio/timelines`, HTTP 202): image/video scenes, optional narration (billed\n * now, `narration_cost_micro_usd`) and music. Poll with `retrieve(id)`; the render is billed once when it succeeds.\n */\n async createTimeline(\n body: TimelineRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<TimelineJob> {\n const res = await this.http.request('/v1/studio/timelines', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return (await res.json()) as TimelineJob;\n }\n\n /**\n * Regenerate one scene (`POST /v1/studio/renders/{id}/scenes/{sceneId}/regenerate`, HTTP 202): a NEW render with\n * `parent_render_id` = `renderId`; the source must be a succeeded timeline render (409 `not_a_timeline`).\n */\n async regenerateScene(\n renderId: string,\n sceneId: string,\n body: SceneRegenerateRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SceneRegenerateJob> {\n const res = await this.http.request(\n `/v1/studio/renders/${encodeURIComponent(renderId)}/scenes/${encodeURIComponent(sceneId)}/regenerate`,\n { body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n return (await res.json()) as SceneRegenerateJob;\n }\n\n /** Queue a render and poll until it succeeds. Throws on `failed` or timeout. */\n async render(\n body: RenderRequest,\n opts: {\n pollIntervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n ext?: CodaiRequestExtensions;\n } = {},\n ): Promise<RenderResult> {\n const { pollIntervalMs = 5000, timeoutMs = 900_000, signal, ext } = opts;\n const job = await this.create(body, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrieve(job.id, { ext, signal });\n if (st.status === 'succeeded') {\n const asset = st.data?.find(isAssetDto);\n if (!asset) throw new Error(`codai render ${job.id} succeeded without an asset`);\n const cost = st.cost_micro_usd;\n return {\n id: job.id,\n asset,\n posterUrl: st.poster_url ?? null,\n qa: st.qa ?? null,\n costMicroUsd: cost === null || cost === undefined ? null : Number(cost),\n raw: st,\n };\n }\n if (st.status === 'failed') {\n throw new Error(`codai render failed: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai render ${job.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio documents (EU-served, everything runs in europe-west1).\n *\n * `POST /v1/studio/documents` — `codai-docs`: builds a deck (PPTX), doc (DOCX) or sheet (XLSX)\n * synchronously from a JSON `spec` (free; asset `kind: 'document'`).\n * `GET /v1/studio/documents/{id}` — the document, a fresh signed `file.url` and the stored `spec`.\n * `POST /v1/studio/documents/{id}/previews` — `codai-docs-preview`: tagged PDF + page PNGs + contact sheet (HTTP 202).\n * `GET /v1/studio/previews/{id}` — polls the preview; billed once ($0.002 / page, min $0.01) when done.\n * `POST /v1/studio/documents/{id}/video` — deck -> MP4 slideshow, queued as a `codai-render` (HTTP 202); poll it\n * with `renders.retrieve` (narration is billed at POST).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { isAssetDto } from './assets';\nimport { type RenderResult, Renders } from './media';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type DocumentType = 'deck' | 'doc' | 'sheet';\nexport type DocumentTheme = Schema<'DocumentTheme'>;\nexport type DeckSpec = Mutable<Schema<'DeckSpec'>>;\nexport type DocSpec = Mutable<Schema<'DocSpec'>>;\nexport type SheetSpec = Mutable<Schema<'SheetSpec'>>;\nexport type DocumentCreateRequest = Mutable<Body<'createDocument'>>;\n/** `POST` adds `cost_micro_usd` / `preview`; `GET` adds `spec` / `latest_preview_id`. */\nexport type StudioDocument = Reply<'createDocument'>;\nexport type DocumentPreviewRequest = Mutable<Body<'createDocumentPreview'>>;\nexport type DocumentPreviewAccepted = Reply<'createDocumentPreview', 202>;\nexport type DocumentPreview = Reply<'retrievePreview'>;\nexport type DocumentPreviewStatus = DocumentPreview['status'];\nexport type DocumentVideoRequest = Mutable<Body<'createDocumentVideo'>>;\nexport type DocumentVideoAccepted = Reply<'createDocumentVideo', 202>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\nexport interface DocumentPollOptions extends CallOpts {\n /** Delay between polls (default 3000 ms for previews, 5000 ms for videos). */\n pollIntervalMs?: number;\n /** Give up after this long (default 300 000 ms for previews, 900 000 ms for videos). */\n timeoutMs?: number;\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Documents {\n private readonly renders: Renders;\n\n constructor(private readonly http: HttpClient) {\n this.renders = new Renders(http);\n }\n\n /**\n * Build a document (`POST /v1/studio/documents`). `spec` must match `type` (`deck` -> `DeckSpec`, `doc` -> `DocSpec`,\n * `sheet` -> `SheetSpec`); invalid specs are 400 `invalid_spec`. Files are free. `based_on` creates the next version\n * of one of your documents; `preview: true` also queues a (billed) preview, returned as `preview`.\n */\n create(body: DocumentCreateRequest, opts: CallOpts = {}): Promise<StudioDocument> {\n return this.http.json<StudioDocument>('/v1/studio/documents', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/studio/documents/{id}` — fresh 1 h signed `file.url`, the stored `spec` and `latest_preview_id`. */\n retrieve(id: string, opts: CallOpts = {}): Promise<StudioDocument> {\n return this.http.json<StudioDocument>(`/v1/studio/documents/${encodeURIComponent(id)}`, {\n method: 'GET',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Queue a preview (`POST /v1/studio/documents/{id}/previews`, HTTP 202): tagged PDF, page PNGs (1280 px) and a\n * contact sheet. Billed once on the first poll that sees the result; at most 3 active previews per user (429).\n */\n preview(\n id: string,\n body: DocumentPreviewRequest = {},\n opts: CallOpts = {},\n ): Promise<DocumentPreviewAccepted> {\n return this.http.json<DocumentPreviewAccepted>(\n `/v1/studio/documents/${encodeURIComponent(id)}/previews`,\n { method: 'POST', body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /** Poll a preview (`GET /v1/studio/previews/{id}`): `queued` | `rendering` | `succeeded` | `failed`. */\n retrievePreview(previewId: string, opts: CallOpts = {}): Promise<DocumentPreview> {\n return this.http.json<DocumentPreview>(`/v1/studio/previews/${encodeURIComponent(previewId)}`, {\n method: 'GET',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Turn a deck into an MP4 (`POST /v1/studio/documents/{id}/video`, HTTP 202). Returns a render: poll it with\n * `renders.retrieve(id)` or use `videoAndWait`. Narration (`narrate`) is synthesized and billed now.\n */\n video(\n id: string,\n body: DocumentVideoRequest = {},\n opts: CallOpts = {},\n ): Promise<DocumentVideoAccepted> {\n return this.http.json<DocumentVideoAccepted>(\n `/v1/studio/documents/${encodeURIComponent(id)}/video`,\n { method: 'POST', body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /** Queue a preview and poll until it succeeds. Throws on `failed` or timeout. */\n async createPreviewAndWait(\n id: string,\n opts: DocumentPollOptions & { body?: DocumentPreviewRequest } = {},\n ): Promise<DocumentPreview> {\n const { pollIntervalMs = 3000, timeoutMs = 300_000, signal, ext, body } = opts;\n const job = await this.preview(id, body ?? {}, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrievePreview(job.id, { ext, signal });\n if (st.status === 'succeeded') return st;\n if (st.status === 'failed') {\n throw new Error(`codai document preview failed: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai document preview ${job.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n\n /** Queue a deck video and poll `renders.retrieve` until it succeeds. Throws on `failed` or timeout. */\n async videoAndWait(\n id: string,\n body: DocumentVideoRequest = {},\n opts: DocumentPollOptions = {},\n ): Promise<RenderResult & { accepted: DocumentVideoAccepted }> {\n const { pollIntervalMs = 5000, timeoutMs = 900_000, signal, ext } = opts;\n const accepted = await this.video(id, body, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.renders.retrieve(accepted.id, { ext, signal });\n if (st.status === 'succeeded') {\n const asset = st.data?.find(isAssetDto);\n if (!asset) throw new Error(`codai render ${accepted.id} succeeded without an asset`);\n const cost = st.cost_micro_usd;\n return {\n id: accepted.id,\n asset,\n posterUrl: st.poster_url ?? null,\n qa: st.qa ?? null,\n costMicroUsd: cost === null || cost === undefined ? null : Number(cost),\n raw: st,\n accepted,\n };\n }\n if (st.status === 'failed') {\n throw new Error(`codai deck video failed: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai deck video ${accepted.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio exports — FCPXML project zips of your video creatives, for Final Cut Pro, DaVinci Resolve or Premiere,\n * and Lottie JSON / dotLottie animations (`kind` tells them apart).\n *\n * `GET /v1/studio/creatives/{id}/export.fcpxml` — queue an export (`creatives.exportFcpxml`), HTTP 202\n * `GET /v1/studio/creatives/{id}/export.lottie` — a Lottie export, ready at once (`creatives.exportLottie`), HTTP 200\n * `GET /v1/studio/exports/{id}` — the export state; a signed zip `url` once `succeeded` (`retrieve`)\n *\n * `wait(id)` polls `retrieve` until the export has `succeeded` or `failed`. Only newly rendered seconds are billed (at\n * the final render price); polling is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type QueryOf, type Schema } from './_shared';\n\nexport type StudioExport = Schema<'StudioExport'>;\nexport type ExportFcpxmlQuery = QueryOf<'exportCreativeFcpxml'>;\n/** `creatives.exportLottie` / `downloadLottie` options (`download` is chosen by the method). */\nexport type ExportLottieQuery = Omit<QueryOf<'exportCreativeLottie'>, 'download'>;\n/** `creatives.downloadLottie`: the file bytes (`application/json` or `application/zip`) and its suggested name. */\nexport interface LottieDownload {\n bytes: Uint8Array;\n filename: string | null;\n contentType: string | null;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface ExportWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 900 000 ms = 15 min). */\n timeoutMs?: number;\n}\n\nconst path = (id: string) => `/v1/studio/exports/${encodeURIComponent(id)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Exports {\n constructor(private readonly http: HttpClient) {}\n\n /** The export: `queued` / `running`, then `succeeded` (signed `url`, valid 1 h) or `failed` (`error`). Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<StudioExport> {\n return this.http.json<StudioExport>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Poll `retrieve` every `intervalMs` (default 3 s) until the export is `succeeded` or `failed` and resolve with it\n * (a `failed` export resolves too — check `status` / `error`). Throws when it is not done within `timeoutMs`\n * (default 15 min) or when `signal` aborts.\n */\n async wait(id: string, opts: ExportWaitOptions = {}): Promise<StudioExport> {\n const { intervalMs = 3000, timeoutMs = 900_000, signal, ext } = opts;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrieve(id, { ext, signal });\n if (st.status === 'succeeded' || st.status === 'failed') return st;\n if (Date.now() + intervalMs > deadline) {\n throw new Error(`codai export ${id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(intervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio creatives — editable creative documents (ECD) with an append-only version history.\n *\n * `POST /v1/studio/creatives` — create (empty doc per `kind`, your `doc`, or a `template` + `vars`;\n * `brand_kit_id`), HTTP 201\n * `GET /v1/studio/creatives` — list (`kind`, `before`, `limit`)\n * `GET /v1/studio/creatives/{id}` — the doc at the head (or `seq`) + signed assets\n * `GET /v1/studio/creatives/{id}/outline` — compact text outline for prompts\n * `POST /v1/studio/creatives/{id}/find` — node ids matching a query\n * `POST /v1/studio/creatives/{id}/subtree` — full JSON of ids / a scene\n * `POST /v1/studio/creatives/{id}/ops` — apply ops against `baseSeq` (rebased when possible, 409 `stale` else)\n * `GET /v1/studio/creatives/{id}/versions` — history; `revert`, `fork`, `lint`, `compiled`, `render`, `frame`\n * `GET /v1/studio/creatives/{id}/frames/{jobId}` — poll a frame job (`frameJob`)\n * `POST /v1/studio/creatives/{id}/comments` — turn a frame comment into an edit (`comment`, token-metered)\n * `POST /v1/studio/creatives/{id}/variants` — A/B variants as forks (`variants`, token-metered + draft renders)\n * `GET /v1/studio/creatives/{id}/variants` — the latest variant group (`listVariants`)\n * `POST /v1/studio/creatives/{id}/variants/{variantId}/pick` — apply the winner to the original (`pickVariant`)\n * `POST /v1/studio/creatives/{id}/template` — save as a private template (`saveTemplate`; see `templates`)\n * `GET /v1/studio/creatives/{id}/export.fcpxml` — queue an FCPXML project zip (`exportFcpxml`; see `exports`)\n * `GET /v1/studio/creatives/{id}/export.lottie` — Lottie JSON / dotLottie, free and ready at once (`exportLottie`;\n * `downloadLottie` for the file itself)\n * `POST /v1/studio/documents/{id}/creative` — edit a Studio document as a creative (`fromDocument`; 201 / 200)\n * `POST /v1/studio/creatives/{id}/build` — build a deck / doc / sheet creative into PPTX / DOCX / XLSX (`build`)\n * `POST /v1/studio/creatives/{id}/restyle` — re-apply a brand kit / token map as one new version (`restyle`)\n * `POST /v1/studio/creatives/{id}/captions` — auto-captions from a voice clip (`captions`; transcription billed)\n * `GET /v1/studio/creatives/{id}/captions.srt|.vtt` — captions as SRT / WebVTT text (`captionsSrt`, `captionsVtt`)\n * `POST /v1/studio/creatives/{id}/adapt` — add platform formats with safe zones (`adapt`; vision focal billed)\n * `POST /v1/studio/creatives/{id}/lint/fix` — fix lint issues (`lintFix`; deterministic free, `agent` billed)\n * `GET /v1/studio/creatives/{id}/controls` — the tweak panel model (`controls`)\n * `GET /v1/studio/creatives/{id}/locales` — localisation state + units of a locale (`locales`)\n * `POST /v1/studio/creatives/{id}/localize` — translate into up to 10 locales (`localize`; token-metered)\n * `POST /v1/studio/creatives/{id}/locales/{locale}/fork` — a locale as a new creative (`forkLocale`)\n * `POST /v1/studio/creatives/{id}/shares` — a public view / review link, token shown once (`createShare`)\n * `GET /v1/studio/creatives/{id}/shares` — active links (`listShares`); `DELETE …/shares/{shareId}` (`revokeShare`)\n * `GET|POST /v1/studio/creatives/{id}/review` — review state; request review / back to draft (`review`,\n * `requestReview`, `resetReview`)\n * `GET|POST /v1/studio/creatives/{id}/review/threads` — comment threads (`reviewThreads`, `createReviewThread`);\n * `…/{threadId}/replies|resolve|reopen`, `DELETE …/review/comments/{commentId}`\n * `DELETE /v1/studio/creatives/{id}`\n *\n * `POST /v1/studio/creatives/{id}/render` (audio creative) — mixdown + master + stems / LRC (`renderAudio`), HTTP 202\n *\n * Everything but `render`, `comment` / `variants` (token-metered `codai` calls; variants also queue draft renders)\n * and frames beyond the daily free quota is free. `render` queues a `codai-render`\n * (HTTP 202; poll it with `renders.retrieve`) or returns an identical existing render (HTTP 200, `cached: true`).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport {\n type Body,\n type Mutable,\n type QueryOf,\n type Reply,\n type Schema,\n stripUndefined,\n} from './_shared';\nimport {\n type ExportFcpxmlQuery,\n type ExportLottieQuery,\n type LottieDownload,\n type StudioExport,\n} from './exports';\n\nexport type CreativeKind = Schema<'CreativeKind'>;\nexport type CreativeDoc = Mutable<Schema<'CreativeDoc'>>;\nexport type CreativeOp = Mutable<Schema<'CreativeOp'>>;\nexport type CreativeCreateRequest = Mutable<Body<'createCreative'>>;\nexport type Creative = Reply<'createCreative', 201>;\nexport type CreativeDetail = Reply<'getCreative'>;\nexport type CreativeList = Reply<'listCreatives'>;\nexport type CreativeListQuery = QueryOf<'listCreatives'>;\nexport type CreativeOutline = Reply<'getCreativeOutline'>;\nexport type CreativeFindRequest = Mutable<Body<'findCreativeNodes'>>;\nexport type CreativeFindResult = Reply<'findCreativeNodes'>;\nexport type CreativeSubtreeRequest = Mutable<Body<'getCreativeSubtree'>>;\nexport type CreativeSubtree = Reply<'getCreativeSubtree'>;\nexport type CreativeOpsResult = Reply<'applyCreativeOps'>;\nexport type CreativeVersionList = Reply<'listCreativeVersions'>;\nexport type CreativeVersionListQuery = QueryOf<'listCreativeVersions'>;\nexport type CreativeRevertResult = Reply<'revertCreative'>;\nexport type CreativeForkRequest = Mutable<Body<'forkCreative'>>;\nexport type CreativeLintResult = Reply<'lintCreative'>;\nexport type CreativeCompiled = Reply<'getCreativeCompiled'>;\nexport type CreativeRenderRequest = Mutable<Schema<'CreativeRenderRequest'>>;\nexport type CreativeRenderAccepted = Schema<'CreativeRenderAccepted'>;\nexport type CreativeRenderCached = Reply<'renderCreative', 200>;\n/** `render` answer: a new queued render (202, `cached: false`) or the identical existing one (200, `cached: true`). */\nexport type CreativeRenderResult = CreativeRenderAccepted | CreativeRenderCached;\n/** `renderAudio` body (MU-05): `formats` (wav | mp3 | flac), `stems`, `lrc`, `loudness` (preset or LUFS), `title`. */\nexport type CreativeAudioRenderRequest = Mutable<Schema<'CreativeAudioRenderRequest'>>;\n/** `renderAudio` answer (202): the queued mixdown with its planned `outputs` and `quote_micro_usd`. */\nexport type CreativeAudioRenderAccepted = Schema<'CreativeAudioRenderAccepted'>;\nexport type CreativeAudioRenderOutput = Schema<'CreativeAudioRenderOutput'>;\n/** `GET /v1/studio/renders/{id}` of an audio render (`target: 'audio'`): one `data[]` asset per output. */\nexport type StudioAudioRender = Schema<'StudioAudioRender'>;\nexport type CreativeFrameRequest = Mutable<Body<'createCreativeFrame'>>;\nexport type CreativeFrame = Schema<'CreativeFrame'>;\nexport type CreativeFrames = Reply<'createCreativeFrame', 200>;\nexport type CreativeFrameJob = Reply<'createCreativeFrame', 202>;\n/** `frame` / `frameJob` answer: frames ready (`status: succeeded`) or a running job to poll (`status: running`). */\nexport type CreativeFrameResult = CreativeFrames | CreativeFrameJob;\nexport type CreativeDeleted = Reply<'deleteCreative'>;\nexport type CreativeCommentRequest = Mutable<Body<'commentCreative'>>;\nexport type CreativeCommentResult = Reply<'commentCreative'>;\nexport type CreativeVariantsRequest = Mutable<Body<'createCreativeVariants'>>;\nexport type CreativeVariantsResult = Reply<'createCreativeVariants'>;\nexport type CreativeVariant = Schema<'CreativeVariant'>;\nexport type CreativeVariantList = Reply<'listCreativeVariants'>;\nexport type CreativeVariantPickRequest = Mutable<Body<'pickCreativeVariant'>>;\nexport type CreativeVariantPickResult = Reply<'pickCreativeVariant'>;\nexport type SaveTemplateRequest = Mutable<Body<'saveCreativeTemplate'>>;\nexport type CreativeTemplate = Schema<'CreativeTemplate'>;\n/** `fromDocument` answer: the creative (`existing: false`, HTTP 201) or the one already linked (`existing: true`, 200). */\nexport type StudioCreativeFromDocument = Schema<'StudioCreativeFromDocument'>;\nexport type CreativeBuildRequest = Mutable<Schema<'CreativeBuildRequest'>>;\nexport type StudioCreativeBuild = Schema<'StudioCreativeBuild'>;\n/** `{ brand_kit_id }` or `{ tokens }` (exactly one) + optional `base_seq`, `snap`, `fonts`, `force`. */\nexport type CreativeRestyleRequest = Mutable<Body<'restyleCreative'>>;\n/** Same shape as the `edit` answer (`seq`, `doc_hash`, `changed`, `warnings`, `rebased`). */\nexport type CreativeRestyleResult = Reply<'restyleCreative'>;\nexport type CaptionPresetId = Schema<'CaptionPresetId'>;\nexport type PlatformId = Schema<'PlatformId'>;\nexport type CreativeLintCode = Schema<'CreativeLintCode'>;\nexport type LintIssue = Schema<'CreativeLintIssue'>;\n/** Optional `clip_id`, `preset`, `node_id`, `script`, `language`, `retranscribe`, `base_seq`, `force`. */\nexport type CreativeCaptionsRequest = Mutable<Schema<'CreativeCaptionsRequest'>>;\n/** The `edit` answer plus `node_id`, `words`, `cached`, `corrected`, `cost_micro_usd`. */\nexport type CreativeCaptionsResult = Schema<'CreativeCaptionsResult'>;\nexport type CreativeCaptionsQuery = { node_id?: string; seq?: number; locale?: string };\n/** `platforms` (1..6) + optional `focal` (`none` | `vision`), `base_seq`, `force`. */\nexport type CreativeAdaptRequest = Mutable<Schema<'CreativeAdaptRequest'>>;\n/** The `edit` answer plus `formats` and `focal`. */\nexport type CreativeAdaptResult = Schema<'CreativeAdaptResult'>;\n/** Optional `codes`, `agent`, `base_seq`, `force`. */\nexport type CreativeLintFixRequest = Mutable<Schema<'CreativeLintFixRequest'>>;\nexport type CreativeLintFixResult = Schema<'CreativeLintFixResult'>;\n/** A tweak panel control (`doc.meta.controls[varKey]`), set with a `setControl` op. */\nexport type CreativeControl = Mutable<Schema<'Control'>>;\nexport type PanelControl = Schema<'PanelControl'>;\nexport type CreativeControls = Reply<'getCreativeControls'>;\nexport type CreativeLocaleStatus = Schema<'CreativeLocaleStatus'>;\nexport type CreativeLocaleUnit = Schema<'CreativeLocaleUnit'>;\nexport type CreativeLocalesQuery = QueryOf<'getCreativeLocales'>;\n/** `locales` (1..10) + optional `base_seq`, `tone`, `glossary`, `only_missing`, `voice`, `force`. */\nexport type CreativeLocalizeRequest = Mutable<Schema<'CreativeLocalizeRequest'>>;\n/** The `edit` answer plus `locales` (per-locale summary) and `cost_micro_usd`. */\nexport type CreativeLocalizeResult = Schema<'CreativeLocalizeResult'>;\n/** Optional `title` and `seq`. */\nexport type CreativeLocaleForkRequest = Mutable<Schema<'CreativeLocaleForkRequest'>>;\n/** The new creative plus `locale` and `fork_of`. */\nexport type CreativeLocaleForkResult = Schema<'CreativeLocaleForkResult'>;\n/** `kind` (`view` | `review`) + optional `label`, `expires_in_days`, `seq` / `allow_remix` (view), `can_approve` (review). */\nexport type StudioShareCreateRequest = Mutable<Schema<'StudioShareCreateRequest'>>;\n/** The new link with its `token` and public `url` — shown only once. */\nexport type StudioShareCreated = Schema<'StudioShareCreated'>;\n/** An active link (`url` is always null: the token is stored hashed). */\nexport type StudioShare = Schema<'StudioShare'>;\nexport type StudioShareList = Schema<'StudioShareList'>;\nexport type StudioReviewStatus = Schema<'StudioReviewStatus'>;\nexport type StudioReview = Schema<'StudioReview'>;\nexport type StudioReviewComment = Schema<'StudioReviewComment'>;\n/** A thread: anchor (`node_id`, `scene_id`, `t_ms`), `status`, and `comments` (root first). */\nexport type StudioReviewThread = Schema<'StudioReviewThread'>;\nexport type StudioReviewThreadList = Schema<'StudioReviewThreadList'>;\n/** `body` (1..2000) + optional anchor `node_id`, `scene_id`, `t_ms`. */\nexport type StudioReviewThreadCreateRequest = Mutable<Schema<'StudioReviewThreadCreateRequest'>>;\nexport type StudioReviewThreadsQuery = { status?: 'open' | 'resolved' | 'all' };\n/** Optional `locale`: lint the document translated into it. */\nexport type CreativeLintRequest = { locale?: string };\nexport type CreativeCompiledQuery = { format?: string; scene?: string; locale?: string };\n\n/** Body of `edit` (camelCase; sent as `base_seq` / `ops` / `intent` / `author` / `force`). */\nexport interface CreativeEditRequest {\n /** The version the ops were authored against (`head_seq` of what you read). */\n baseSeq: number;\n ops: CreativeOp[];\n /** Why — shown in the version history. */\n intent?: string;\n author?: 'user' | 'agent';\n /** Bypass locked nodes and variables. */\n force?: boolean;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst path = (id: string, tail = '') => `/v1/studio/creatives/${encodeURIComponent(id)}${tail}`;\nconst lottieQuery = (q: ExportLottieQuery) => ({\n format: q.format,\n formats: q.formats,\n seq: q.seq,\n container: q.container,\n});\n\nexport class Creatives {\n constructor(private readonly http: HttpClient) {}\n\n /** List your creatives, most recently updated first (`next_before` pages). */\n list(query: CreativeListQuery = {}, opts: CallOpts = {}): Promise<CreativeList> {\n return this.http.json<CreativeList>('/v1/studio/creatives', {\n query: { kind: query.kind, before: query.before, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Create a creative (`kind` + optional `title` / `doc`); without `doc` you get an empty document for the kind.\n * `brand_kit_id` applies one of your brand kits (`brandKits`) to version 1: `brand = { kitId, tokens }` + its logo.\n * `template` (+ `vars`, values by var key) starts from one of your templates (`templates`) instead of `doc`.\n */\n create(body: CreativeCreateRequest, opts: CallOpts = {}): Promise<Creative> {\n return this.http.json<Creative>('/v1/studio/creatives', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The document at the head (or `seq`) with signed `assets` (1 h URLs). */\n retrieve(id: string, query: { seq?: number } = {}, opts: CallOpts = {}): Promise<CreativeDetail> {\n return this.http.json<CreativeDetail>(path(id), {\n query: { seq: query.seq },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Compact text outline (+ formats and vars) — the cheapest structure for a prompt. */\n outline(id: string, opts: CallOpts = {}): Promise<CreativeOutline> {\n return this.http.json<CreativeOutline>(path(id, '/outline'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Node ids matching `query` (a string = text/name/id substring, or `{ text, type, sceneId, assetId, locked }`). */\n find(\n id: string,\n query: CreativeFindRequest['query'],\n opts: CallOpts = {},\n ): Promise<CreativeFindResult> {\n return this.http.json<CreativeFindResult>(path(id, '/find'), {\n method: 'POST',\n body: { query },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Full JSON of `ids` (scene ids return whole scenes) or of one `sceneId`. */\n subtree(id: string, body: CreativeSubtreeRequest, opts: CallOpts = {}): Promise<CreativeSubtree> {\n return this.http.json<CreativeSubtree>(path(id, '/subtree'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Apply an op batch (all or nothing) authored against `baseSeq`. A stale base is rebased when the touched\n * targets did not change meanwhile; otherwise the call throws `CodaiError` 409 `stale` (reload and retry). Rejected\n * ops throw 400 with `code` (`invalid`, `not_found`, `locked`, `duplicate_id`).\n */\n edit(id: string, body: CreativeEditRequest, opts: CallOpts = {}): Promise<CreativeOpsResult> {\n return this.http.json<CreativeOpsResult>(path(id, '/ops'), {\n method: 'POST',\n body: {\n base_seq: body.baseSeq,\n ops: body.ops,\n ...(body.intent !== undefined ? { intent: body.intent } : {}),\n ...(body.author !== undefined ? { author: body.author } : {}),\n ...(body.force !== undefined ? { force: body.force } : {}),\n },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Version history, newest first (`beforeSeq` pages). */\n versions(\n id: string,\n query: { beforeSeq?: number; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<CreativeVersionList> {\n return this.http.json<CreativeVersionList>(path(id, '/versions'), {\n query: { before_seq: query.beforeSeq, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** New head whose document is version `seq`'s (undo / redo). */\n revert(id: string, seq: number, opts: CallOpts = {}): Promise<CreativeRevertResult> {\n return this.http.json<CreativeRevertResult>(path(id, '/revert'), {\n method: 'POST',\n body: { seq },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** New creative from version `seq` (default the head). */\n fork(id: string, body: CreativeForkRequest = {}, opts: CallOpts = {}): Promise<Creative> {\n return this.http.json<Creative>(path(id, '/fork'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Soft-delete the creative. */\n delete(id: string, opts: CallOpts = {}): Promise<CreativeDeleted> {\n return this.http.json<CreativeDeleted>(path(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Contrast, safe area, empty text, missing assets, brand colours, platform safe zones and text floors, alt text,\n * missing captions, reading speed, flashing, missing / stale translations. Issues carry `format` / `fixable` /\n * `locale`; `fixable` counts them (`lintFix`). `locale` lints the translated document (adds\n * `text_overflow_locale`); 404 `Locale not found.` for an unknown locale.\n */\n lint(\n id: string,\n body: CreativeLintRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeLintResult> {\n return this.http.json<CreativeLintResult>(path(id, '/lint'), {\n method: 'POST',\n ...(body.locale !== undefined ? { body: { locale: body.locale } } : {}),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Preview HTML (signed asset URLs) for `format` / one `scene` / a translation (`locale`). */\n compiled(\n id: string,\n query: CreativeCompiledQuery = {},\n opts: CallOpts = {},\n ): Promise<CreativeCompiled> {\n return this.http.json<CreativeCompiled>(path(id, '/compiled'), {\n query: { format: query.format, scene: query.scene, locale: query.locale },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Queue an MP4 render of the head (`codai-render`, HTTP 202, `cached: false`); poll `renders.retrieve(render_id)`.\n * When the same render already exists for this version / format / quality / fps you get it back at once\n * (HTTP 200, `cached: true`, `status: 'succeeded'`, no new charge). Unchanged scenes are reused either way.\n * `locale` renders a translation (404 `Locale not found.` when the creative has no such locale).\n * `ai_label` (`none` | `corner` | `end_card`, EU AI Act art. 50(4)) burns a visible AI label into the video; omitted =\n * `corner` when the creative uses TTS narration or AI images, else `none` (`none` with narration: 400 `ai_label_required`).\n */\n render(\n id: string,\n body: CreativeRenderRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeRenderResult> {\n return this.http.json<CreativeRenderResult>(path(id, '/render'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Mixdown + mastering + exports of an `audio` creative (MU-05; same `POST …/render` route, HTTP 202). `formats`\n * (default `['wav', 'mp3']`), `stems: true` adds one WAV per audible track (+50 %), `lrc` exports the timed lyrics\n * (default on when the document has them), `loudness` is `streaming` (−14) | `podcast` (−16) | `broadcast` (−23) or\n * LUFS (−40…−5). Poll `renders.retrieve(render_id)`: the finished render's `data[]` holds one signed asset per output\n * (`output: mix | stem | lrc`). $0.001 per output second, minimum $0.01; held up front, billed on the measured length.\n * 400 `empty_audio` / `too_long` (20 min) / `no_lyrics`; video creatives use `render`.\n */\n renderAudio(\n id: string,\n body: CreativeAudioRenderRequest = {},\n opts: CallOpts & { idempotencyKey?: string } = {},\n ): Promise<CreativeAudioRenderAccepted> {\n return this.http.json<CreativeAudioRenderAccepted>(path(id, '/render'), {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: !opts.idempotencyKey,\n });\n }\n\n /**\n * PNG still frames at up to 6 times (`t_ms`). `exact: false` (default) screenshots the compiled HTML; `exact: true`\n * cuts them from a draft render of the covering scenes. Waits up to ~90 s: frames (`status: 'succeeded'`) or a\n * running job (`status: 'running'`) to poll with `frameJob(id, frame_job_id)`. Cached frames are free; 60 frame\n * jobs per UTC day are free, then billed (`billed_micro_usd`).\n */\n frame(id: string, body: CreativeFrameRequest, opts: CallOpts = {}): Promise<CreativeFrameResult> {\n return this.http.json<CreativeFrameResult>(path(id, '/frame'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Turn a comment pinned on a frame (`t_ms`, optional `node_id` / `scene_id`) into an edit: one bounded `codai`\n * model turn proposes ops, applied like `edit` against `base_seq` (rebased when possible, 409 `stale` else).\n * 422 `no_edit` when the model made no edit (its answer in `error.text`); `apply: false` only proposes the ops.\n * Token-metered like any `codai` text call.\n */\n comment(\n id: string,\n body: CreativeCommentRequest,\n opts: CallOpts = {},\n ): Promise<CreativeCommentResult> {\n return this.http.json<CreativeCommentResult>(path(id, '/comments'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Generate A/B variants: one bounded `codai` model turn proposes `count` (default 3) variants changing only\n * `focus` (default hook / title / cta); each becomes a fork of the creative at `base_seq` with the ops applied, plus\n * a queued draft render (`render: false` to skip; poll `renders.retrieve(render_id)`). The original is unchanged\n * until `pickVariant`. 422 `no_edit` when no valid variant came back, 504 `timeout` after 90 s. Token-metered.\n */\n variants(\n id: string,\n body: CreativeVariantsRequest,\n opts: CallOpts = {},\n ): Promise<CreativeVariantsResult> {\n return this.http.json<CreativeVariantsResult>(path(id, '/variants'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The latest variant group of a creative (`group_id: null` when none) with statuses and stored render state. */\n listVariants(id: string, opts: CallOpts = {}): Promise<CreativeVariantList> {\n return this.http.json<CreativeVariantList>(path(id, '/variants'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Pick the winner: its ops are applied to the original against `base_seq` (rebased when possible, 409 `stale`\n * else); the winner is marked `winner`, the rest of its group `rejected`.\n */\n pickVariant(\n id: string,\n variantId: string,\n body: CreativeVariantPickRequest,\n opts: CallOpts = {},\n ): Promise<CreativeVariantPickResult> {\n return this.http.json<CreativeVariantPickResult>(\n path(id, `/variants/${encodeURIComponent(variantId)}/pick`),\n { method: 'POST', body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /**\n * Save the creative (at `seq`, default the head) as a private template: each `vars` entry turns a text node's text\n * (`prop: 'text'`) or an image node's asset (`prop: 'image'`) into a variable whose default is the current value.\n * 400 `node_not_found` / `invalid_pick` / `duplicate_key`. Free.\n */\n saveTemplate(\n id: string,\n body: SaveTemplateRequest,\n opts: CallOpts = {},\n ): Promise<CreativeTemplate> {\n return this.http.json<CreativeTemplate>(path(id, '/template'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Queue an FCPXML export of a video creative (`seq`, default the head; `format`, default the first 1920×1080 /\n * 1080×1920 / 1080×1080 format): a zip with `project.fcpxml` + per-scene MP4 segments + audio, for Final Cut Pro,\n * DaVinci Resolve or Premiere. Resolves to the queued export; poll it with `exports.wait(e.id)`. Only newly\n * rendered seconds are billed (final render price). 400 `unsupported_kind` / `unsupported_format` / `too_long`.\n */\n exportFcpxml(\n id: string,\n query: ExportFcpxmlQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioExport> {\n return this.http.json<StudioExport>(path(id, '/export.fcpxml'), {\n query: { format: query.format, seq: query.seq },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Export a video creative as a Lottie animation (`seq`, default the head; `format`, default the document's default\n * format, or `formats: 'all'`; `container: 'json'` (default, Bodymovin JSON with embedded images) or `'dotlottie'`).\n * Free and synchronous: resolves to an export that is already `succeeded` with a signed `url` (valid 1 h) and the\n * fidelity report in `warnings` (video, chart, HTML block, table, cell grid and audio nodes are not exported).\n * 400 `unsupported_kind` / `invalid_request`, 413 `too_large` (over 20 MB).\n */\n exportLottie(\n id: string,\n query: ExportLottieQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioExport> {\n return this.http.json<StudioExport>(path(id, '/export.lottie'), {\n query: lottieQuery(query),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * The Lottie file itself (`download=1`, nothing stored): `application/json` for one Bodymovin JSON, `application/zip`\n * for a dotLottie archive or a zip of JSON files (`formats: 'all'`). Same options and errors as `exportLottie`. Free.\n */\n async downloadLottie(\n id: string,\n query: ExportLottieQuery = {},\n opts: CallOpts = {},\n ): Promise<LottieDownload> {\n const res = await this.http.request(path(id, '/export.lottie'), {\n query: { ...lottieQuery(query), download: '1' },\n ext: opts.ext,\n signal: opts.signal,\n });\n const m = /filename=\"([^\"]+)\"/i.exec(res.headers.get('content-disposition') ?? '');\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n filename: m ? m[1]! : null,\n contentType: res.headers.get('content-type'),\n };\n }\n\n /**\n * Turn one of your Studio documents (deck, doc, sheet) into an editable creative — slides become scenes with a\n * `layout` and speaker `notes`, doc pages a `flow` group, sheets a `cell_grid`; nodes carry semantic `role`s.\n * Idempotent: a document that already has a creative resolves to it (`existing: true`). Free. 404 unknown document,\n * 409 `document_spec_missing`, 400 `invalid_spec`, 413 `too_large`.\n */\n fromDocument(documentId: string, opts: CallOpts = {}): Promise<StudioCreativeFromDocument> {\n return this.http.json<StudioCreativeFromDocument>(\n `/v1/studio/documents/${encodeURIComponent(documentId)}/creative`,\n { method: 'POST', ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /**\n * Build a deck / doc / sheet creative (at `seq`, default the head) into a PPTX / DOCX / XLSX — a new version of its\n * Studio document (`document`, exactly the `POST /v1/studio/documents` body). Converter notes come back in\n * `warnings`. The file is free; `preview: true` also queues a billed preview (poll it with\n * `documents.waitForPreview`). 400 `not_supported_for_kind` (video / image) or `invalid_spec`.\n */\n build(\n id: string,\n body: CreativeBuildRequest = {},\n opts: CallOpts = {},\n ): Promise<StudioCreativeBuild> {\n return this.http.json<StudioCreativeBuild>(path(id, '/build'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Re-apply a brand kit (`brand_kit_id`) or a flat token map (`tokens`) to the creative as one new version: literal\n * colours equal to the old brand become token refs, `snap: true` maps every other colour to the nearest kit colour,\n * `fonts` (default true) sets heading / body font refs by role, locked nodes are skipped unless `force`. The kit\n * logo is registered too. `base_seq` defaults to the head (rebased like `edit`, 409 `stale` else). Free.\n */\n restyle(\n id: string,\n body: CreativeRestyleRequest,\n opts: CallOpts = {},\n ): Promise<CreativeRestyleResult> {\n return this.http.json<CreativeRestyleResult>(path(id, '/restyle'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Auto-captions: transcribe a voice clip (`clip_id`, default the first voice clip) word by word and add or update a\n * captions node (`preset`, default `bold-pill`) as one new version. Words are cached on the asset (free next time\n * unless `retranscribe`); `script` (default the narration of a codai speech asset) corrects the spelling. A fresh\n * transcription is billed at the speech-to-text rate (`cost_micro_usd`). Video creatives only (400\n * `unsupported_kind`); 403 `residency_unavailable`, 503 `transcription_unavailable`.\n */\n captions(\n id: string,\n body: CreativeCaptionsRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeCaptionsResult> {\n return this.http.json<CreativeCaptionsResult>(path(id, '/captions'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The captions as SubRip text on the document timeline (`node_id`, `seq` optional); 404 without captions. Free. */\n async captionsSrt(\n id: string,\n query: CreativeCaptionsQuery = {},\n opts: CallOpts = {},\n ): Promise<string> {\n const res = await this.http.request(path(id, '/captions.srt'), {\n query: { node_id: query.node_id, seq: query.seq, locale: query.locale },\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /** The captions as WebVTT text on the document timeline (`node_id`, `seq` optional); 404 without captions. Free. */\n async captionsVtt(\n id: string,\n query: CreativeCaptionsQuery = {},\n opts: CallOpts = {},\n ): Promise<string> {\n const res = await this.http.request(path(id, '/captions.vtt'), {\n query: { node_id: query.node_id, seq: query.seq, locale: query.locale },\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /**\n * Adapt to platforms (`tiktok`, `reels`, `shorts`, `feed-square`, `feed-portrait`, `youtube`): one format per\n * platform in one new version, text kept inside each platform's safe zone and above its legible size.\n * `focal: 'vision'` (token-metered) finds the focal point of full-bleed images; it fails open. Free otherwise.\n */\n adapt(id: string, body: CreativeAdaptRequest, opts: CallOpts = {}): Promise<CreativeAdaptResult> {\n return this.http.json<CreativeAdaptResult>(path(id, '/adapt'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Fix lint issues as one new version: deterministic fixes (free) for `off_brand_color`, `text_too_small`,\n * `outside_platform_safe_zone` and `flashing` (`codes` limits them); `agent: true` (token-metered) gives the rest\n * to one `codai` turn. Nothing to fix: the current `seq`, empty `fixed`, no new version.\n */\n lintFix(\n id: string,\n body: CreativeLintFixRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeLintFixResult> {\n return this.http.json<CreativeLintFixResult>(path(id, '/lint/fix'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * The tweak panel model: one control per variable (stored `meta.controls` entry or derived from the type). Change\n * values with a `setVar` op and controls with a `setControl` op (`edit`). Free.\n */\n controls(id: string, opts: CallOpts = {}): Promise<CreativeControls> {\n return this.http.json<CreativeControls>(path(id, '/controls'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Localisation state: source locale, glossary, unit count and per locale translated / missing / stale / voice.\n * With `locale` (+ `units`, default 1) also the units of that locale (paged with `offset` / `limit` ≤ 500). Free.\n */\n locales(\n id: string,\n query: CreativeLocalesQuery = {},\n opts: CallOpts = {},\n ): Promise<CreativeLocaleStatus> {\n return this.http.json<CreativeLocaleStatus>(path(id, '/locales'), {\n query: { locale: query.locale, units: query.units, offset: query.offset, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Translate every text into up to 10 BCP-47 `locales` as per-locale overrides (one new version, author `agent`).\n * Token-metered `codai` turns; `glossary` terms and the brand kit name stay verbatim, `tone` picks the address,\n * `only_missing` (default true) skips fresh translations, `voice: true` (video, billed) narrates voice clips again.\n * 400 `nothing_to_translate`; 503 `localize_unavailable` when every locale failed.\n */\n localize(\n id: string,\n body: CreativeLocalizeRequest,\n opts: CallOpts = {},\n ): Promise<CreativeLocalizeResult> {\n return this.http.json<CreativeLocalizeResult>(path(id, '/localize'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Save `locale` as a new standalone creative (translations applied, overrides dropped, `fork_of` recorded; default\n * title `<title> (<locale>)`). 404 `Locale not found.`. Free (HTTP 201).\n */\n forkLocale(\n id: string,\n locale: string,\n body: CreativeLocaleForkRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeLocaleForkResult> {\n return this.http.json<CreativeLocaleForkResult>(\n path(id, `/locales/${encodeURIComponent(locale)}/fork`),\n {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n }\n\n /**\n * Create a public link: `view` (read-only preview of version `seq` or the head; `allow_remix` default false) or\n * `review` (comments by name, no account; `can_approve` lets the holder approve). The `token` and `url` are shown\n * only in this answer (HTTP 201). 400 `unknown_seq`; 409 `too_many_shares` (20 active links). Free.\n */\n createShare(\n id: string,\n body: StudioShareCreateRequest,\n opts: CallOpts = {},\n ): Promise<StudioShareCreated> {\n return this.http.json<StudioShareCreated>(path(id, '/shares'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The active links (not revoked, not expired), newest first; `url` is always null. Free. */\n listShares(id: string, opts: CallOpts = {}): Promise<StudioShareList> {\n return this.http.json<StudioShareList>(path(id, '/shares'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Revoke a link: it answers 404 from now on. 404 when unknown or already revoked. Free. */\n async revokeShare(id: string, shareId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(path(id, `/shares/${encodeURIComponent(shareId)}`), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * The review state: `status` (`draft` → `in_review` → `approved` | `changes_requested`), requested / approved\n * version (`approved_is_head` false once the creative changed), decider and thread counts. Free.\n */\n review(id: string, opts: CallOpts = {}): Promise<StudioReview> {\n return this.http.json<StudioReview>(path(id, '/review'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Send the head to review (`in_review`, earlier decision cleared) so approver links can decide. Free. */\n requestReview(id: string, opts: CallOpts = {}): Promise<StudioReview> {\n return this.http.json<StudioReview>(path(id, '/review'), {\n method: 'POST',\n body: { action: 'request' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Back to `draft` (decision cleared, comments kept). Free. */\n resetReview(id: string, opts: CallOpts = {}): Promise<StudioReview> {\n return this.http.json<StudioReview>(path(id, '/review'), {\n method: 'POST',\n body: { action: 'reset' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Comment threads, newest first (≤ 200), replies oldest first; `status` `open` | `resolved` | `all`. Free. */\n reviewThreads(\n id: string,\n query: StudioReviewThreadsQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioReviewThreadList> {\n return this.http.json<StudioReviewThreadList>(path(id, '/review/threads'), {\n query: { status: query.status },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Start a thread as the owner, optionally anchored to `node_id` / `scene_id` / `t_ms` (checked against the head:\n * 400 `unknown_node` / `unknown_scene`; HTTP 201). 409 `too_many_comments`. Free.\n */\n createReviewThread(\n id: string,\n body: StudioReviewThreadCreateRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(path(id, '/review/threads'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Reply in a thread as the owner (HTTP 201) — returns the whole thread. Free. */\n replyReviewThread(\n id: string,\n threadId: string,\n body: { body: string },\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(\n path(id, `/review/threads/${encodeURIComponent(threadId)}/replies`),\n {\n method: 'POST',\n body: { body: body.body },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n }\n\n /** Resolve a thread. Free. */\n resolveReviewThread(\n id: string,\n threadId: string,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(\n path(id, `/review/threads/${encodeURIComponent(threadId)}/resolve`),\n { method: 'POST', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** Reopen a resolved thread. Free. */\n reopenReviewThread(\n id: string,\n threadId: string,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(\n path(id, `/review/threads/${encodeURIComponent(threadId)}/reopen`),\n { method: 'POST', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** Delete any comment (owner moderation; deleting a root hides the thread). 404 when unknown. Free. */\n async deleteReviewComment(id: string, commentId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(path(id, `/review/comments/${encodeURIComponent(commentId)}`), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Poll a frame job: frames when done (`status: 'succeeded'`), `status: 'running'` meanwhile; 404 unknown job. */\n frameJob(id: string, jobId: string, opts: CallOpts = {}): Promise<CreativeFrameResult> {\n return this.http.json<CreativeFrameResult>(path(id, `/frames/${encodeURIComponent(jobId)}`), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * codai Studio brand kits — reusable brand tokens (5 colour roles + extras, 2 fonts, optional radius) stored as a\n * Design Tokens (DTCG 2025.10) document, plus a logo.\n *\n * `POST /v1/studio/brand-kits` — create from flat `tokens` or a DTCG document (`create`), HTTP 201\n * `PATCH /v1/studio/brand-kits/{id}` — edit name / tokens (merged) / dtcg (replaced) / logo (`update`)\n * `GET /v1/studio/brand-kits/{id}/dtcg` — the kit as a DTCG JSON document (`exportDtcg`)\n * `POST /v1/studio/brand-kits/extract` — from a public https page (`{ url }`) or a logo image asset\n * (`{ logo_asset_id }`); one `codai` turn (`extract`, token-metered)\n * `GET /v1/studio/brand-kits` — your kits, newest first (`list`)\n * `GET /v1/studio/brand-kits/{id}` — one kit with a signed logo URL (`retrieve`)\n * `DELETE /v1/studio/brand-kits/{id}` — soft delete (`delete`)\n *\n * Apply a kit when creating a creative (`creatives.create({ kind, brand_kit_id })`), re-apply it to an existing one\n * with `creatives.restyle(id, { brand_kit_id })`, or set tokens directly with a `setBrand` op.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type BrandKit = Schema<'BrandKit'>;\nexport type BrandKitTokens = Schema<'BrandKitTokens'>;\nexport type BrandKitDtcg = Mutable<Schema<'BrandKitDtcg'>>;\nexport type BrandKitContrastPair = Schema<'BrandKitContrastPair'>;\n/** `{ url, name? }` (a web page) or `{ logo_asset_id, name? }` (one of your image assets) — exactly one source. */\nexport type BrandKitExtractRequest = Mutable<Body<'extractBrandKit'>>;\n/** `{ name, tokens }` or `{ name, dtcg }` (exactly one), optional `logo_asset_id` / `source_url`. */\nexport type BrandKitCreateRequest = Mutable<Body<'createBrandKit'>>;\n/** At least one of `name`, `tokens` (partial, merged), `dtcg` (replaces), `logo_asset_id` (`null` removes). */\nexport type BrandKitUpdateRequest = Mutable<Body<'updateBrandKit'>>;\nexport type BrandKitList = Reply<'listBrandKits'>;\nexport type BrandKitDeleted = Reply<'deleteBrandKit'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst path = (id: string, tail = '') => `/v1/studio/brand-kits/${encodeURIComponent(id)}${tail}`;\n\nexport class BrandKits {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a kit you define: flat `tokens` (the 5 colours `#rrggbb`, optional fonts) or a DTCG document in `dtcg`\n * (import) — exactly one. 400 `invalid_tokens` (with `details.issues`) for an invalid DTCG document, 404 when\n * `logo_asset_id` is not one of your ready image assets. Free.\n */\n create(body: BrandKitCreateRequest, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>('/v1/studio/brand-kits', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Edit a kit: `tokens` is merged onto the current kit, `dtcg` replaces the whole document (not both),\n * `logo_asset_id: null` removes the logo. Creatives keep their tokens until `creatives.restyle`. Free.\n */\n update(id: string, body: BrandKitUpdateRequest, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>(path(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The kit as a DTCG 2025.10 JSON document (`$extensions['ro.codai']` = kit id, name, logo asset id). Free. */\n exportDtcg(id: string, opts: CallOpts = {}): Promise<BrandKitDtcg> {\n return this.http.json<BrandKitDtcg>(path(id, '/dtcg'), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Extract a brand kit from a public `https` page (`{ url }`) or from one of your logo images\n * (`{ logo_asset_id }`, PNG / JPEG / WebP up to 5 MB; it becomes the kit logo): palette (primary, secondary, accent,\n * background, text) and heading / body fonts. One bounded `codai` model call (token-metered); 400 `url_blocked` for\n * private hosts, 400 `unsupported_media` for a bad logo, 422 `fetch_failed` / `extract_failed`, 504 `timeout`.\n */\n extract(body: BrandKitExtractRequest, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>('/v1/studio/brand-kits/extract', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Your brand kits, newest first (`limit` 1–100, default 50). Free. */\n list(query: { limit?: number } = {}, opts: CallOpts = {}): Promise<BrandKitList> {\n return this.http.json<BrandKitList>('/v1/studio/brand-kits', {\n query: { limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** One kit with a signed logo URL (1 h), its `dtcg` and the WCAG `contrast` pairs. Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** Delete a kit (creatives keep their tokens; the logo asset stays). Free. */\n delete(id: string, opts: CallOpts = {}): Promise<BrandKitDeleted> {\n return this.http.json<BrandKitDeleted>(path(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * codai Studio templates — private, reusable creative documents with variables, saved from your own creatives.\n *\n * `POST /v1/studio/creatives/{id}/template` — save a creative as a template (`creatives.saveTemplate`), HTTP 201\n * `GET /v1/studio/templates` — your templates (newest first), then the 40 built-in starters\n * (`source: \"starter\"`, ids `starter:<slug>:<en|ro>`) (`list`, without `doc`)\n * `GET /v1/studio/templates/{id}` — one template with its `doc` (`retrieve`)\n * `DELETE /v1/studio/templates/{id}` — soft delete (`delete`)\n *\n * Create a creative from a template with `creatives.create({ kind, template, vars })`. Everything here is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type CreativeTemplateVar = Schema<'CreativeTemplateVar'>;\nexport type CreativeTemplateList = Reply<'listCreativeTemplates'>;\nexport type CreativeTemplateListQuery = QueryOf<'listCreativeTemplates'>;\nexport type CreativeTemplateDeleted = Reply<'deleteCreativeTemplate'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst path = (id: string) => `/v1/studio/templates/${encodeURIComponent(id)}`;\n\nexport class Templates {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Your templates (newest first; `limit` 1–100, default 50), then the built-in starters in `locale` (`en` | `ro`,\n * default from Accept-Language) with in-season ones first (`month` 1–12). `source`: `own` | `starter` | `all`\n * (default). `kind` filters both. Without `doc`. Free. A starter id works anywhere a template id does\n * (`retrieve`, `creatives.create({ template })`, batches); starters cannot be deleted.\n */\n list(query: CreativeTemplateListQuery = {}, opts: CallOpts = {}): Promise<CreativeTemplateList> {\n return this.http.json<CreativeTemplateList>('/v1/studio/templates', {\n query: {\n kind: query.kind,\n limit: query.limit,\n source: query.source,\n locale: query.locale,\n month: query.month,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** One template with its variables and `doc`. Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<Schema<'CreativeTemplate'>> {\n return this.http.json<Schema<'CreativeTemplate'>>(path(id), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Delete a template (creatives made from it are not affected). Free. */\n delete(id: string, opts: CallOpts = {}): Promise<CreativeTemplateDeleted> {\n return this.http.json<CreativeTemplateDeleted>(path(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/studio/productions` — codai Studio brief → finished promo video (RC-20).\n *\n * `POST /v1/studio/productions` — storyboard on a built-in starter, images + voice-over, an editable creative and\n * a draft render (`create`, 202, ~1 min)\n * `GET /v1/studio/productions/{id}` — the production (`retrieve`); reading it advances render → review → repair →\n * ready like a poll\n *\n * `wait(id)` polls until `status` is `succeeded` or `failed`; `run(body)` = `create` + `wait`. The storyboard and\n * review turns are token-metered; images, voice-over and renders are billed at their usual prices; `budget_micro_usd`\n * (default $3) caps the whole production.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Schema } from './_shared';\n\nexport type StudioProductionCreate = Mutable<Body<'createStudioProduction'>>;\nexport type StudioProduction = Schema<'StudioProduction'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface ProductionCreateOptions extends CallOpts {\n /** `Idempotency-Key`: a retry with the same key replays the first production instead of starting another one. */\n idempotencyKey?: string;\n}\n\nexport interface ProductionWaitOptions extends CallOpts {\n /** Delay between polls (default 5000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 600 000 ms = 10 min). */\n timeoutMs?: number;\n}\n\nconst path = (id: string) => `/v1/studio/productions/${encodeURIComponent(id)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport const isProductionFinished = (p: Pick<StudioProduction, 'status'>): boolean =>\n p.status === 'succeeded' || p.status === 'failed';\n\nexport class Productions {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/studio/productions` — brief → storyboard → assets → creative → queued draft render (202). */\n create(\n body: StudioProductionCreate,\n opts: ProductionCreateOptions = {},\n ): Promise<StudioProduction> {\n return this.http.json<StudioProduction>('/v1/studio/productions', {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/studio/productions/{id}` — advances the production and returns it (another account's id is a 404). */\n retrieve(id: string, opts: CallOpts = {}): Promise<StudioProduction> {\n return this.http.json<StudioProduction>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Poll `retrieve` every `intervalMs` (default 5 s) until the production `succeeded` or `failed` (a failed one\n * resolves too — check `status` / `error`). Throws after `timeoutMs` (default 10 min) or when `signal` aborts.\n */\n async wait(id: string, opts: ProductionWaitOptions = {}): Promise<StudioProduction> {\n const interval = opts.intervalMs ?? 5_000;\n const deadline = Date.now() + (opts.timeoutMs ?? 600_000);\n for (;;) {\n const p = await this.retrieve(id, opts);\n if (isProductionFinished(p)) return p;\n if (Date.now() + interval > deadline)\n throw new Error(`codai: production ${id} did not finish in time (phase ${p.phase})`);\n await abortableSleep(interval, opts.signal);\n }\n }\n\n /** `create` + `wait`. */\n async run(\n body: StudioProductionCreate,\n opts: ProductionCreateOptions & ProductionWaitOptions = {},\n ): Promise<StudioProduction> {\n const p = await this.create(body, opts);\n return isProductionFinished(p) ? p : this.wait(p.id, opts);\n }\n}\n","/**\n * `/v1/studio/media-ops` — codai Studio media operations on your assets (AR-02).\n *\n * `GET /v1/studio/media-ops` — the op catalogue with list quotes and availability (`list`, free)\n * `POST /v1/studio/media-ops/{op}/quote` — exact price of a request, same validation as the run (`quote`, free)\n * `POST /v1/studio/media-ops/{op}` — run: 200 with the outputs (sync ops) or 202 with a job (async ops)\n * (`run`; `Idempotency-Key` honoured)\n * `GET /v1/studio/media-ops/jobs/{id}` — an async job; a finished one is settled on read (`job`)\n *\n * Ops: `image.remove_background` / `upscale` / `inpaint` / `outpaint` / `erase`, `audio.separate_stems` / `denoise` /\n * `to_midi` / `master` / `analyze`, `music.generate_ace` / `repaint` / `extend` / `cover`, `sfx.generate`. The quote is\n * held on the wallet (402 `insufficient_funds`), the measured cost billed once. Every output is AI-marked and carries\n * lineage (`parent_asset_id`, `op`, `op_inputs`). A lane that is not configured answers 503 `media_ops_unavailable`.\n * `wait(id)` polls a job until it is `ready` or `failed`; `runAndWait` = `run` + `wait` for async ops.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Reply, type Schema } from './_shared';\n\nexport type MediaOpId = Schema<'MediaOpId'>;\nexport type MediaOp = Schema<'MediaOp'>;\nexport type MediaOpList = Reply<'listStudioMediaOps'>;\nexport type MediaOpRequest = Mutable<Schema<'MediaOpRequest'>>;\nexport type MediaOpQuote = Schema<'MediaOpQuote'>;\nexport type MediaOpResult = Schema<'MediaOpResult'>;\nexport type MediaOpJob = Schema<'MediaOpJob'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface MediaOpInput {\n /** Owned, ready Studio asset ids in the order the op expects (mask second for inpaint / erase). */\n assetIds?: string[];\n /** Per-op parameters (validated strictly by the gateway; see the docs table). */\n params?: Record<string, unknown>;\n}\n\nexport interface MediaOpRunOptions extends CallOpts {\n /** `Idempotency-Key`: a retry with the same key replays the first answer instead of running (and billing) again. */\n idempotencyKey?: string;\n}\n\nexport interface MediaOpWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 1 200 000 ms = 20 min, the server-side job timeout). */\n timeoutMs?: number;\n}\n\nconst BASE = '/v1/studio/media-ops';\nconst opPath = (op: string) => `${BASE}/${encodeURIComponent(op)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nconst toBody = (input: MediaOpInput): MediaOpRequest => ({\n asset_ids: input.assetIds ?? [],\n params: input.params ?? {},\n});\n\n/** A run answer is a job (async op, HTTP 202) when `object` is `media_op.job`. */\nexport const isMediaOpJob = (r: MediaOpResult | MediaOpJob): r is MediaOpJob =>\n r.object === 'media_op.job';\n\nexport const isMediaOpJobFinished = (j: Pick<MediaOpJob, 'status'>): boolean =>\n j.status === 'ready' || j.status === 'failed';\n\nexport class MediaOps {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/studio/media-ops` — every op with engine, mode, inputs, `available` and a list quote (free). */\n list(opts: CallOpts = {}): Promise<MediaOpList> {\n return this.http.json<MediaOpList>(BASE, { ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/studio/media-ops/{op}/quote` — exact price of this request; nothing is held or billed. */\n quote(\n op: MediaOpId | string,\n input: MediaOpInput = {},\n opts: CallOpts = {},\n ): Promise<MediaOpQuote> {\n return this.http.json<MediaOpQuote>(`${opPath(op)}/quote`, {\n method: 'POST',\n body: toBody(input),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/studio/media-ops/{op}` — sync ops resolve to a `media_op.result` with the outputs, async ops to a\n * `media_op.job` (`status: pending`; poll with `job` / `wait`). Use `isMediaOpJob` to tell them apart.\n */\n run(\n op: MediaOpId | string,\n input: MediaOpInput = {},\n opts: MediaOpRunOptions = {},\n ): Promise<MediaOpResult | MediaOpJob> {\n return this.http.json<MediaOpResult | MediaOpJob>(opPath(op), {\n method: 'POST',\n body: toBody(input),\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/studio/media-ops/jobs/{id}` — the job; reading a finished one stores its outputs and bills it once. */\n job(id: string, opts: CallOpts = {}): Promise<MediaOpJob> {\n return this.http.json<MediaOpJob>(`${BASE}/jobs/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Poll `job` every `intervalMs` (default 3 s) until it is `ready` or `failed` (a failed job resolves too — check\n * `status` / `error`). Throws after `timeoutMs` (default 20 min) or when `signal` aborts.\n */\n async wait(id: string, opts: MediaOpWaitOptions = {}): Promise<MediaOpJob> {\n const interval = opts.intervalMs ?? 3_000;\n const deadline = Date.now() + (opts.timeoutMs ?? 1_200_000);\n for (;;) {\n const j = await this.job(id, opts);\n if (isMediaOpJobFinished(j)) return j;\n if (Date.now() + interval > deadline)\n throw new Error(`codai: media job ${id} did not finish in time (status ${j.status})`);\n await abortableSleep(interval, opts.signal);\n }\n }\n\n /** `run`, then `wait` when the op is async. */\n async runAndWait(\n op: MediaOpId | string,\n input: MediaOpInput = {},\n opts: MediaOpRunOptions & MediaOpWaitOptions = {},\n ): Promise<MediaOpResult | MediaOpJob> {\n const r = await this.run(op, input, opts);\n return isMediaOpJob(r) && !isMediaOpJobFinished(r) ? this.wait(r.id, opts) : r;\n }\n}\n","/**\n * `/v1/studio/lyrics` — codai Studio lyrics writer and karaoke alignment (MU-06).\n *\n * `POST /v1/studio/lyrics` — write original lyrics for a brief (`write`), checked for syllables per line and\n * the rhyme scheme; one repair turn when more than 30 % of the lines miss.\n * Token-metered (`codai::lyrics`) under a small wallet hold.\n * `POST /v1/studio/lyrics/align` — align written lyrics to one clip of an audio / video creative (`align`): timed\n * lines applied with one `setLyrics` edit (unless `apply: false`) + an LRC file.\n * Cached clip words are free; a fresh transcription bills `codai::lyrics-align`.\n *\n * Both honour `Idempotency-Key`. 402 `insufficient_funds` when the hold does not fit; alignment is 403\n * `residency_unavailable` for EU data-residency accounts.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema } from './_shared';\n\nexport type LyricsRequest = Mutable<Schema<'StudioLyricsRequest'>>;\nexport type LyricsSectionKind = Schema<'StudioLyricsSectionKind'>;\nexport type LyricsLine = Schema<'StudioLyricsLine'>;\nexport type Lyrics = Schema<'StudioLyrics'>;\nexport type LyricsAlignRequest = Mutable<Schema<'StudioLyricsAlignRequest'>>;\nexport type LyricsAlignment = Schema<'StudioLyricsAlignment'>;\n\nexport interface LyricsCallOptions {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n /** `Idempotency-Key`: a retry with the same key replays the first answer instead of running (and billing) again. */\n idempotencyKey?: string;\n}\n\nconst BASE = '/v1/studio/lyrics';\n\nexport class LyricsResource {\n constructor(private readonly http: HttpClient) {}\n\n private post<T>(path: string, body: unknown, opts: LyricsCallOptions): Promise<T> {\n return this.http.json<T>(path, {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/studio/lyrics` — `{ brief, language: 'ro' | 'en', genre?, mood?, structure?, syllables_per_line?,\n * rhyme_scheme?, lines_per_section?, title? }` → `studio.lyrics` with every line's syllables and rhyme letter, the\n * whole song as `text` (`[kind]` headers) and a `report`. `repaired: true` when the repair turn won.\n */\n write(body: LyricsRequest, opts: LyricsCallOptions = {}): Promise<Lyrics> {\n return this.post<Lyrics>(BASE, body, opts);\n }\n\n /**\n * `POST /v1/studio/lyrics/align` — `{ creative_id, clip_id, lyrics_text, language?, apply?, base_seq?,\n * retranscribe? }` → `studio.lyrics_alignment`: timed `lines`, `lrc`, `match_ratio`, `cached`, and `seq` /\n * `doc_hash` of the new version when applied.\n */\n align(body: LyricsAlignRequest, opts: LyricsCallOptions = {}): Promise<LyricsAlignment> {\n return this.post<LyricsAlignment>(`${BASE}/align`, body, opts);\n }\n}\n","/**\n * `wss://…/v1/studio/jam` — codai Studio live jam (MU-09): live generated music (Lyria RealTime) steered with weighted\n * prompts. Not an OpenAPI operation (OpenAPI cannot describe WebSockets), so it is outside `OPERATION_METHODS`.\n *\n * const jam = codai.jam.connect({ token }); // browser: ephemeral token (scope realtime | live)\n * jam.on('audio', (pcm) => player.push(pcm)); // PCM16 LE interleaved stereo at 48 kHz\n * jam.prompts([{ text: 'warm lo-fi piano', weight: 1 }]);\n * jam.config({ bpm: 90, density: 0.4 });\n * jam.play();\n *\n * Auth: server runtimes send `Authorization: Bearer <key>` (needs a WebSocket constructor that accepts headers, e.g.\n * `ws`); browsers send the subprotocols `codai-jam` + `bearer.<token>` (the server answers `codai-jam` and never echoes\n * the credential). Raw long-lived keys are never put in the URL.\n *\n * Close codes: 4400 invalid message, 4401 credentials, 4402 insufficient funds, 4403 EU residency / not allowed / spend\n * cap, 4408 10-minute limit, 4409 another jam already open, 4502 upstream error, 4503 not configured. Billed $0.03 per\n * started minute of the open upstream session (`codai::jam`); the 10-minute price is held when the session opens.\n */\nimport type { RealtimeSocket, RealtimeSocketCtor } from './realtime';\n\nexport const JAM_SUBPROTOCOL = 'codai-jam';\n\n/** WebSocket close codes of `/v1/studio/jam`. */\nexport const JAM_CLOSE_CODES = {\n invalidMessage: 4400,\n unauthorized: 4401,\n insufficientFunds: 4402,\n forbidden: 4403,\n maxDuration: 4408,\n busy: 4409,\n upstream: 4502,\n unavailable: 4503,\n} as const;\n\nexport const JAM_SCALES = [\n 'SCALE_UNSPECIFIED',\n 'C_MAJOR_A_MINOR',\n 'D_FLAT_MAJOR_B_FLAT_MINOR',\n 'D_MAJOR_B_MINOR',\n 'E_FLAT_MAJOR_C_MINOR',\n 'E_MAJOR_D_FLAT_MINOR',\n 'F_MAJOR_D_MINOR',\n 'G_FLAT_MAJOR_E_FLAT_MINOR',\n 'G_MAJOR_E_MINOR',\n 'A_FLAT_MAJOR_F_MINOR',\n 'A_MAJOR_G_FLAT_MINOR',\n 'B_FLAT_MAJOR_G_MINOR',\n 'B_MAJOR_A_FLAT_MINOR',\n] as const;\nexport type JamScale = (typeof JAM_SCALES)[number];\n\n/** A weighted prompt: 1..8 per message, `weight` in [-10, 10] and not 0. */\nexport interface JamPrompt {\n text: string;\n weight: number;\n}\n\n/** Partial config; the server merges it into the last full config. bpm / scale changes reset the context. */\nexport interface JamConfig {\n bpm?: number;\n density?: number;\n brightness?: number;\n scale?: JamScale;\n}\n\nexport type JamClientMessage =\n | { type: 'prompts'; prompts: JamPrompt[] }\n | ({ type: 'config' } & JamConfig)\n | { type: 'play' | 'pause' | 'stop' | 'reset' };\n\nexport type JamState =\n 'connecting' | 'ready' | 'playing' | 'paused' | 'stopped' | (string & Record<never, never>);\n\nexport type JamEvent =\n | {\n type: 'status';\n state: JamState;\n remaining_ms: number;\n sample_rate?: number;\n channels?: number;\n }\n | { type: 'filtered'; text: string; reason: string }\n | { type: 'error'; code: string; message: string }\n /** Emitted by the client for every binary frame. */\n | { type: 'audio'; data: ArrayBuffer }\n /** Emitted by the client itself when the socket closes (always the last event). */\n | { type: 'close'; code: number; reason: string };\n\nexport interface JamConnectOptions {\n /** Ephemeral token (scope `realtime` or `live`) — sent as the `bearer.<token>` subprotocol. Required in browsers. */\n token?: string;\n /** API key — sent as `Authorization: Bearer` (needs a ctor that supports headers). */\n apiKey?: string;\n /** Conversation id recorded on the usage row (`?session_id=`). */\n sessionId?: string;\n /** Injectable WebSocket constructor (tests, `ws` on older Node). Defaults to `globalThis.WebSocket`. */\n WebSocket?: RealtimeSocketCtor;\n /** Override the gateway base URL (default: the client's `baseUrl`). */\n baseUrl?: string;\n}\n\ntype Listener<T extends JamEvent['type']> = (ev: Extract<JamEvent, { type: T }>) => void;\ntype AnyListener = (ev: JamEvent) => void;\n\nconst OPEN = 1;\n\nfunction toArrayBuffer(data: unknown): ArrayBuffer | null {\n if (data instanceof ArrayBuffer) return data;\n if (ArrayBuffer.isView(data)) {\n const v = data as ArrayBufferView;\n return v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) as ArrayBuffer;\n }\n return null;\n}\n\n/** A live jam session: `on()` listeners for status / audio / errors and typed senders. */\nexport class JamSession {\n private readonly listeners = new Map<string, Set<AnyListener>>();\n private readonly outbox: string[] = [];\n private closed = false;\n /** Resolves when the socket is open (rejects if it closes first). */\n readonly ready: Promise<void>;\n\n constructor(readonly socket: RealtimeSocket) {\n let resolveReady!: () => void;\n let rejectReady!: (e: Error) => void;\n this.ready = new Promise<void>((res, rej) => {\n resolveReady = res;\n rejectReady = rej;\n });\n this.ready.catch(() => undefined);\n socket.onopen = () => {\n for (const f of this.outbox.splice(0)) socket.send(f);\n resolveReady();\n };\n socket.onmessage = (ev) => {\n if (typeof ev.data !== 'string') {\n const buf = toArrayBuffer(ev.data);\n if (buf) this.emit({ type: 'audio', data: buf });\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(ev.data);\n } catch {\n return;\n }\n if (\n parsed &&\n typeof parsed === 'object' &&\n typeof (parsed as { type?: unknown }).type === 'string'\n )\n this.emit(parsed as JamEvent);\n };\n socket.onerror = () => {\n /* the close event carries the code */\n };\n socket.onclose = (ev) => {\n rejectReady(new Error(`jam socket closed before open (${String(ev.code)} ${ev.reason})`));\n this.closed = true;\n this.emit({ type: 'close', code: ev.code, reason: ev.reason });\n };\n }\n\n /** Listen for one event type (`'*'` = every event). Returns an unsubscribe function. */\n on<T extends JamEvent['type']>(type: T, fn: Listener<T>): () => void;\n on(type: '*', fn: AnyListener): () => void;\n on(type: string, fn: AnyListener): () => void {\n let set = this.listeners.get(type);\n if (!set) this.listeners.set(type, (set = new Set()));\n set.add(fn);\n return () => set.delete(fn);\n }\n\n /** Send one client message (JSON). Queued until the socket opens. */\n send(msg: JamClientMessage): void {\n if (this.closed) throw new Error('jam session is closed');\n const frame = JSON.stringify(msg);\n if (this.socket.readyState === OPEN) this.socket.send(frame);\n else this.outbox.push(frame);\n }\n\n prompts(prompts: JamPrompt[]): void {\n this.send({ type: 'prompts', prompts });\n }\n\n config(config: JamConfig): void {\n this.send({ type: 'config', ...config });\n }\n\n play(): void {\n this.send({ type: 'play' });\n }\n\n pause(): void {\n this.send({ type: 'pause' });\n }\n\n stop(): void {\n this.send({ type: 'stop' });\n }\n\n reset(): void {\n this.send({ type: 'reset' });\n }\n\n close(code = 1000, reason = 'client closed'): void {\n if (this.closed) return;\n this.socket.close(code, reason);\n }\n\n private emit(ev: JamEvent): void {\n for (const fn of this.listeners.get(ev.type) ?? []) fn(ev);\n for (const fn of this.listeners.get('*') ?? []) fn(ev);\n }\n}\n\n/** Build the `wss://…/v1/studio/jam` URL (exported for tests and custom transports). */\nexport function jamUrl(baseUrl: string, opts: Pick<JamConnectOptions, 'sessionId'> = {}): string {\n const url = new URL(`${baseUrl.replace(/\\/$/, '').replace(/^http/, 'ws')}/v1/studio/jam`);\n if (opts.sessionId) url.searchParams.set('session_id', opts.sessionId);\n return url.toString();\n}\n\nexport class Jam {\n constructor(private readonly defaults: { baseUrl: string; apiKey?: string }) {}\n\n /** Open a live jam. Returns immediately; `await session.ready` to wait for the socket. */\n connect(opts: JamConnectOptions = {}): JamSession {\n const Ctor = opts.WebSocket ?? (globalThis as { WebSocket?: RealtimeSocketCtor }).WebSocket;\n if (!Ctor) throw new Error('codai.jam: no WebSocket available — pass options.WebSocket');\n let token = opts.token;\n let apiKey = token ? undefined : (opts.apiKey ?? this.defaults.apiKey);\n if (apiKey?.startsWith('codai_eph_v1.')) {\n token = apiKey;\n apiKey = undefined;\n }\n if (!token && !apiKey) throw new Error('codai.jam: pass `token` (browser) or `apiKey`');\n const url = jamUrl(opts.baseUrl ?? this.defaults.baseUrl, opts);\n const socket = apiKey\n ? new Ctor(url, [JAM_SUBPROTOCOL], { headers: { Authorization: `Bearer ${apiKey}` } })\n : new Ctor(url, [JAM_SUBPROTOCOL, `bearer.${token!}`]);\n if ('binaryType' in socket) socket.binaryType = 'arraybuffer';\n return new JamSession(socket);\n }\n}\n","/**\n * codai Studio batches — one creative per CSV / sheet row, from a template or a creative with variables.\n *\n * `POST /v1/studio/batches` — create (`create`, HTTP 201) or validate only (`dryRun`, HTTP 200)\n * `GET /v1/studio/batches` — your batches, newest first (`list`)\n * `GET /v1/studio/batches/{id}` — the batch (+ rows with `rows: 1`); every poll advances it (`get`)\n * `POST /v1/studio/batches/{id}/cancel` — stop it; rows not started become `skipped` (`cancel`)\n * `POST /v1/studio/batches/{id}/retry` — queue the failed rows again (`retry`)\n * `GET /v1/studio/batches/{id}/export.csv` — the original rows + `creative_id,status,error,render_url` (`exportCsv`)\n * `POST /v1/studio/batches/{id}/zip` — build a ZIP of the finished renders (`zip`, HTTP 202)\n *\n * `wait(id)` polls `get` until the batch is `completed`, `failed` or `cancelled`. Creating a batch is free; rows with a\n * `locale` column are translated (token-metered) and `render: true` renders every row (billed like any render).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type QueryOf, type Schema, stripUndefined } from './_shared';\n\nexport type StudioBatchStatus = Schema<'StudioBatchStatus'>;\nexport type StudioBatchRowStatus = Schema<'StudioBatchRowStatus'>;\nexport type StudioBatch = Schema<'StudioBatch'>;\nexport type StudioBatchRow = Schema<'StudioBatchRow'>;\nexport type StudioBatchColumn = Schema<'StudioBatchColumn'>;\n/** `{ batch, rows? }` (rows only with `rows: 1`). */\nexport type StudioBatchDetail = Schema<'StudioBatchDetail'>;\nexport type StudioBatchList = Schema<'StudioBatchList'>;\nexport type StudioBatchDryRun = Schema<'StudioBatchDryRun'>;\n/**\n * `source` (`{ template_id }` or `{ creative_id, seq? }`) + exactly one of `csv` / `sheet`, optional `delimiter`,\n * `mapping` (column → variable, `null` ignores), `title`, `render`, `quality`, `ai_label`, `format`, `localize`, `dry_run`.\n */\nexport type StudioBatchCreateRequest = Mutable<Schema<'StudioBatchCreateRequest'>>;\nexport type StudioBatchListQuery = QueryOf<'listStudioBatches'>;\nexport type StudioBatchGetQuery = QueryOf<'getStudioBatch'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface BatchWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 600 000 ms = 10 min). */\n timeoutMs?: number;\n}\n\nconst BATCH_DONE: readonly StudioBatchStatus[] = ['completed', 'failed', 'cancelled'];\n\nconst path = (id: string, tail = '') => `/v1/studio/batches/${encodeURIComponent(id)}${tail}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Batches {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a batch: rows are validated (invalid rows are stored as `failed`) and run in the background; poll `get`\n * or `wait`. 400 `invalid_rows` when every row is invalid. Free (translations and renders are billed as usual).\n */\n async create(body: StudioBatchCreateRequest, opts: CallOpts = {}): Promise<StudioBatchDetail> {\n return this.http.json<StudioBatchDetail>('/v1/studio/batches', {\n method: 'POST',\n body: stripUndefined({ ...body, dry_run: false }),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Validate only (`dry_run: true`): the mapping, row errors, a 3-row preview and an estimate; nothing stored. Free. */\n dryRun(body: StudioBatchCreateRequest, opts: CallOpts = {}): Promise<StudioBatchDryRun> {\n return this.http.json<StudioBatchDryRun>('/v1/studio/batches', {\n method: 'POST',\n body: stripUndefined({ ...body, dry_run: true }),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Your batches, newest first (`limit` 1–50, `before` = the previous `next_before`). Free. */\n list(query: StudioBatchListQuery = {}, opts: CallOpts = {}): Promise<StudioBatchList> {\n return this.http.json<StudioBatchList>('/v1/studio/batches', {\n query: { limit: query.limit, before: query.before },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** The batch (`rows: 1` adds rows; `status`, `offset`, `limit` ≤ 100). Each poll advances it a little. Free. */\n get(\n id: string,\n query: StudioBatchGetQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioBatchDetail> {\n return this.http.json<StudioBatchDetail>(path(id), {\n query: { rows: query.rows, status: query.status, offset: query.offset, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Stop the batch; rows not started become `skipped`. 409 `not_cancellable` when already finished. Free. */\n cancel(id: string, opts: CallOpts = {}): Promise<StudioBatch> {\n return this.http.json<StudioBatch>(path(id, '/cancel'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Queue the failed rows again (≤ 3 attempts each). 409 `nothing_to_retry`. Free. */\n retry(id: string, opts: CallOpts = {}): Promise<StudioBatch> {\n return this.http.json<StudioBatch>(path(id, '/retry'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The original CSV plus `creative_id`, `status`, `error`, `render_url` per row (formula-safe). Free. */\n async exportCsv(id: string, opts: CallOpts = {}): Promise<string> {\n const res = await this.http.request(path(id, '/export.csv'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /**\n * Start building a ZIP of the finished renders (202, `zip.status: 'building'`; unchanged when already building or\n * ready). Poll `get` until `zip.status` is `ready` (signed `zip.url`). 409 `no_renders`. Free.\n */\n zip(id: string, opts: CallOpts = {}): Promise<StudioBatch> {\n return this.http.json<StudioBatch>(path(id, '/zip'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Poll `get` every `intervalMs` (default 3 s) until the batch is `completed`, `failed` or `cancelled` and resolve\n * with it. Throws when it is not done within `timeoutMs` (default 10 min) or when `signal` aborts.\n */\n async wait(id: string, opts: BatchWaitOptions = {}): Promise<StudioBatch> {\n const { intervalMs = 3000, timeoutMs = 600_000, signal, ext } = opts;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const { batch } = await this.get(id, {}, { ext, signal });\n if (BATCH_DONE.includes(batch.status)) return batch;\n if (Date.now() + intervalMs > deadline) {\n throw new Error(`codai batch ${id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(intervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio share links seen from the outside — read, remix and review a creative someone shared with you.\n *\n * `GET /v1/public/studio/shares/{token}` — the shared creative (`get`; no key needed)\n * `POST /v1/studio/shares/{token}/remix` — copy a `view` link into your account (`remix`)\n * `POST /v1/public/studio/reviews/{token}/threads` — comment through a review link (`comment`)\n * `POST /v1/public/studio/reviews/{token}/threads/{threadId}/replies` — reply (`reply`)\n * `POST /v1/public/studio/reviews/{token}/threads/{threadId}/resolve|reopen` — (`resolve`, `reopen`)\n * `POST /v1/public/studio/reviews/{token}/decision` — approve / request changes (`decide`)\n *\n * Every method takes the token or the whole link (`https://hub.codai.ro/s/<token>` or `/r/<token>`). The public\n * routes ignore the API key; reviewers are identified only by the `name` they type (visible to the owner and other\n * reviewers). Owners create and revoke links with `creatives.createShare` / `creatives.revokeShare`. Everything is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema, stripUndefined } from './_shared';\nimport { type StudioReviewThread } from './creatives';\n\nexport type StudioShareKind = Schema<'StudioShareKind'>;\nexport type StudioPublicShare = Schema<'StudioPublicShare'>;\nexport type StudioPublicReview = Schema<'StudioPublicReview'>;\n/** The new creative (same shape as `creatives.create`) plus `remixed_from` and optional `warnings`. */\nexport type StudioRemixResult = Schema<'StudioRemixResult'>;\n/** Optional `title` of the new creative. */\nexport type StudioRemixRequest = Mutable<Schema<'StudioRemixRequest'>>;\n/** `name` + `body`, optional anchor `node_id` / `scene_id` / `t_ms`. */\nexport type StudioPublicThreadCreateRequest = Mutable<Schema<'StudioPublicThreadCreateRequest'>>;\n/** `name` + `body`. */\nexport type StudioPublicReplyRequest = Mutable<Schema<'StudioPublicReplyRequest'>>;\n/** `name`. */\nexport type StudioPublicNameRequest = Mutable<Schema<'StudioPublicNameRequest'>>;\n/** `name`, `decision` (`approve` | `request_changes`), `seq` (the head you reviewed), optional `note`. */\nexport type StudioPublicDecisionRequest = Mutable<Schema<'StudioPublicDecisionRequest'>>;\nexport type StudioPublicShareQuery = { format?: string; locale?: string };\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst SHARE_TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * The share token in `input`: a raw token, or any `https://…/s/<token>` / `…/r/<token>` URL (query and fragment\n * ignored). Trims; `null` for anything else (same rule as the gateway and the apps).\n */\nexport function shareTokenFrom(input: string): string | null {\n const s = input.trim();\n if (SHARE_TOKEN_RE.test(s)) return s;\n let url: URL;\n try {\n url = new URL(s);\n } catch {\n return null;\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;\n const parts = url.pathname.split('/').filter(Boolean);\n if (parts.length < 2) return null;\n const kind = parts[parts.length - 2];\n const token = parts[parts.length - 1]!;\n return (kind === 's' || kind === 'r') && SHARE_TOKEN_RE.test(token) ? token : null;\n}\n\nfunction tokenOf(tokenOrUrl: string): string {\n const token = shareTokenFrom(tokenOrUrl);\n if (!token)\n throw new TypeError('codai: not a share link or token (expected …/s/<token> or …/r/<token>)');\n return token;\n}\n\nconst review = (tokenOrUrl: string, tail: string) =>\n `/v1/public/studio/reviews/${encodeURIComponent(tokenOf(tokenOrUrl))}${tail}`;\nconst thread = (tokenOrUrl: string, threadId: string, tail: string) =>\n review(tokenOrUrl, `/threads/${encodeURIComponent(threadId)}${tail}`);\n\nexport class Shares {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * The shared creative: title, kind, version, formats, locales and the compiled preview HTML of `format` /\n * `locale` (null for images); review links add the review state and every thread. 404 for unknown, revoked or\n * expired links. No key needed.\n */\n get(\n tokenOrUrl: string,\n query: StudioPublicShareQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioPublicShare> {\n return this.http.json<StudioPublicShare>(\n `/v1/public/studio/shares/${encodeURIComponent(tokenOf(tokenOrUrl))}`,\n { query: { format: query.format, locale: query.locale }, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /**\n * Copy the version a `view` link shows into a new creative of yours (the owner's ready assets are copied, the\n * foreign brand kit dropped; HTTP 201). 404 for review links or links without remix; 413 `remix_too_large`. Free.\n */\n remix(\n tokenOrUrl: string,\n body: StudioRemixRequest = {},\n opts: CallOpts = {},\n ): Promise<StudioRemixResult> {\n return this.http.json<StudioRemixResult>(\n `/v1/studio/shares/${encodeURIComponent(tokenOf(tokenOrUrl))}/remix`,\n {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n }\n\n /** Start a thread through a review link (`name`, `body`, optional anchor; HTTP 201). 400 `invalid_name`. */\n comment(\n tokenOrUrl: string,\n body: StudioPublicThreadCreateRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(review(tokenOrUrl, '/threads'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Reply in a thread through a review link (`name`, `body`; HTTP 201) — returns the whole thread. */\n reply(\n tokenOrUrl: string,\n threadId: string,\n body: StudioPublicReplyRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(thread(tokenOrUrl, threadId, '/replies'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Resolve a thread through a review link (`resolved_by` = `name`). */\n resolve(\n tokenOrUrl: string,\n threadId: string,\n body: StudioPublicNameRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(thread(tokenOrUrl, threadId, '/resolve'), {\n method: 'POST',\n body: { name: body.name },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Reopen a resolved thread through a review link. */\n reopen(\n tokenOrUrl: string,\n threadId: string,\n body: StudioPublicNameRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(thread(tokenOrUrl, threadId, '/reopen'), {\n method: 'POST',\n body: { name: body.name },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Approve or request changes (approver review links only). 403 `not_an_approver`, 409 `review_not_open`, 409\n * `stale` (with `head_seq`) when `seq` is not the head. Returns the new review state.\n */\n decide(\n tokenOrUrl: string,\n body: StudioPublicDecisionRequest,\n opts: CallOpts = {},\n ): Promise<StudioPublicReview> {\n return this.http.json<StudioPublicReview>(review(tokenOrUrl, '/decision'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/**\n * `POST /v1/studio/voice-revocations` — ask for a voice cloned in codai Studio to be taken down (for people without a\n * codai account). Public: the key is not required by the route; nothing in the request is echoed back. Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema, stripUndefined } from './_shared';\n\n/** `email`, `voice_owner_name`, `details`, optional `evidence_url`. */\nexport type StudioVoiceRevocationRequest = Mutable<Schema<'StudioVoiceRevocationRequest'>>;\n/** `{ id, object: 'studio.voice_revocation', status: 'open' }`. */\nexport type StudioVoiceRevocation = Schema<'StudioVoiceRevocation'>;\n\nexport class VoiceRevocations {\n constructor(private readonly http: HttpClient) {}\n\n /** Store a takedown ticket for manual review (HTTP 202). Rate-limited per IP; never retried. */\n create(\n body: StudioVoiceRevocationRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<StudioVoiceRevocation> {\n return this.http.json<StudioVoiceRevocation>('/v1/studio/voice-revocations', {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/**\n * `/v1/vault/*` — the zero-knowledge credentials vault (V-01..V-10). Everything the server stores is ciphertext built\n * client-side (bundles, envelopes, sealed keys): this resource only moves those blobs. The agent broker calls\n * (`catalog`, `use`, `http`, `resolve`) never return secret values. Device approval keys (V-27) hold public keys\n * only: `vault.devices` enrols, lists, renames and revokes them. Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport {\n type Body,\n type Mutable,\n type QueryOf,\n type Reply,\n type Schema,\n stripUndefined,\n} from './_shared';\n\nexport type VaultAccount = Schema<'VaultAccount'>;\nexport type VaultItemEnvelope = Mutable<Schema<'VaultItemEnvelope'>>;\nexport type VaultUseDecision = Schema<'VaultUseDecision'>;\nexport type VaultAccountPut = Mutable<Body<'putVaultAccount'>>;\nexport type VaultCreate = Mutable<Body<'createVault'>>;\nexport type VaultRuleCreate = Mutable<Body<'createVaultRule'>>;\nexport type VaultDecision = Mutable<Body<'decideVaultApproval'>>;\n/** v2 proof for `decide`: an enrolled device key or a passkey assertion. */\nexport type VaultApprovalProof = Mutable<Schema<'VaultApprovalProof'>>;\nexport type VaultDeviceKey = Schema<'VaultDeviceKey'>;\nexport type VaultDeviceChallenge = Schema<'VaultDeviceChallenge'>;\nexport type VaultDeviceEnroll = Mutable<Schema<'VaultDeviceEnroll'>>;\nexport type VaultDeviceAttestation = VaultDeviceKey['attestation'];\nexport type VaultUseRequest = Mutable<Body<'vaultUse'>>;\nexport type VaultHttpRequest = Mutable<Body<'vaultHttp'>>;\nexport type VaultResolveRequest = Mutable<Body<'vaultResolve'>>;\nexport type VaultTier = VaultAccount['default_tier'];\n/** Anomaly guards (V-32): new host, burst, allowed hours. An anomaly forces t4. */\nexport type VaultGuards = Schema<'VaultGuards'>;\nexport type VaultSettingsPatch = Mutable<Body<'patchVaultSettings'>>;\nexport type VaultSettings = Reply<'patchVaultSettings'>;\nexport type VaultLockResult = Schema<'VaultLockResult'>;\nexport type VaultUnlockChallenge = Schema<'VaultUnlockChallenge'>;\nexport type VaultUnlockRequest = Mutable<Body<'unlockVault'>>;\n/** Per-handle limits (V-21); an `http` use costs 2 units, other modes 1. */\nexport type VaultItemLimits = Schema<'VaultItemLimits'>;\nexport type VaultItemLimitsInput = Mutable<Body<'setVaultItemLimits'>>;\n/** Where a lock/unlock was triggered from. */\nexport type VaultVia = 'hub' | 'desktop' | 'phone' | 'wear' | 'extension';\n\n/** The UTF-8 message an unlock proof covers: `codai-vault/unlock/v1|<challenge>|<device_id or \"passkey\">`. */\nexport function vaultUnlockMessage(challenge: string, deviceIdOrPasskey: string): string {\n return `codai-vault/unlock/v1|${challenge}|${deviceIdOrPasskey}`;\n}\n/** Loose JSON object answers (lists, acks) as documented in the OpenAPI spec. */\nexport type VaultObject = Record<string, unknown>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst seg = (base: string, id: string, suffix = '') => `${base}/${encodeURIComponent(id)}${suffix}`;\n\n/** `/v1/vault/devices/*` — hardware-backed device approval keys (public keys only; revocation is instant). */\nexport class VaultDevices {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/vault/devices/challenge` — single-use enrolment nonce, valid 5 minutes. */\n challenge(opts: CallOpts = {}): Promise<VaultDeviceChallenge> {\n return this.http.json<Reply<'createVaultDeviceChallenge'>>('/v1/vault/devices/challenge', {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/vault/devices` — enrol (or re-enrol) a device key; vault-signed, possession-proven, attested (201). */\n async enroll(body: VaultDeviceEnroll, opts: CallOpts = {}): Promise<VaultDeviceKey> {\n const r = await this.http.json<Reply<'enrollVaultDevice', 201>>('/v1/vault/devices', {\n method: 'POST',\n body: stripUndefined({ ...body }),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return r.device;\n }\n\n /** `GET /v1/vault/devices` — your device keys, revoked ones included, newest first. */\n async list(opts: CallOpts = {}): Promise<VaultDeviceKey[]> {\n const r = await this.http.json<Reply<'listVaultDevices'>>('/v1/vault/devices', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.devices];\n }\n\n /** `PATCH /v1/vault/devices/{id}` — change the display name (1-80 characters). */\n async rename(id: string, name: string, opts: CallOpts = {}): Promise<VaultDeviceKey> {\n const r = await this.http.json<Reply<'renameVaultDevice'>>(seg('/v1/vault/devices', id), {\n method: 'PATCH',\n body: { name },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return r.device;\n }\n\n /** `DELETE /v1/vault/devices/{id}` — revoke at once; later proofs answer 403 `device_revoked`. */\n revoke(id: string, opts: CallOpts = {}): Promise<Reply<'revokeVaultDevice'>> {\n return this.http.json<Reply<'revokeVaultDevice'>>(seg('/v1/vault/devices', id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Vault {\n readonly devices: VaultDevices;\n\n constructor(private readonly http: HttpClient) {\n this.devices = new VaultDevices(http);\n }\n\n private get<T>(\n path: string,\n opts: CallOpts,\n query?: Record<string, string | number | undefined>,\n ): Promise<T> {\n return this.http.json<T>(path, { query, ext: opts.ext, signal: opts.signal });\n }\n\n private send<T>(\n method: 'POST' | 'PUT' | 'PATCH' | 'DELETE',\n path: string,\n opts: CallOpts,\n body?: Record<string, unknown>,\n ): Promise<T> {\n return this.http.json<T>(path, {\n method,\n ...(body ? { body: stripUndefined(body) } : {}),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: method !== 'DELETE',\n });\n }\n\n /** `GET /v1/vault/account` — bundle, fingerprint, default tier, revision (404 `vault_not_setup` before setup). */\n account(opts: CallOpts = {}): Promise<VaultAccount> {\n return this.get<Reply<'getVaultAccount'>>('/v1/vault/account', opts);\n }\n\n /** `PUT /v1/vault/account` — upload the client-built bundle; updates send the current `revision` (409 otherwise). */\n putAccount(body: VaultAccountPut, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('PUT', '/v1/vault/account', opts, body);\n }\n\n /** `PATCH /v1/vault/settings` — default approval tier for items without a matching rule. */\n setDefaultTier(defaultTier: VaultTier, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('PATCH', '/v1/vault/settings', opts, { default_tier: defaultTier });\n }\n\n /**\n * `PATCH /v1/vault/settings` — `default_tier` and/or partial anomaly `guards` (merged over the current ones).\n * Answers the effective `{ default_tier, guards }`.\n */\n updateSettings(body: VaultSettingsPatch, opts: CallOpts = {}): Promise<VaultSettings> {\n if (body.default_tier === undefined && body.guards === undefined)\n return Promise.reject(new TypeError('updateSettings needs default_tier and/or guards'));\n return this.send<VaultSettings>('PATCH', '/v1/vault/settings', opts, { ...body });\n }\n\n /**\n * `POST /v1/vault/lock` — panic: revoke every live grant, deny every pending approval, lock the vault (agent uses\n * then answer `vault_locked`). Device keys stay enrolled. Idempotent.\n */\n lock(params: { via?: VaultVia } = {}, opts: CallOpts = {}): Promise<VaultLockResult> {\n return this.send<VaultLockResult>('POST', '/v1/vault/lock', opts, { via: params.via });\n }\n\n /** `POST /v1/vault/unlock/challenge` — single-use unlock challenge, valid 5 minutes. */\n unlockChallenge(opts: CallOpts = {}): Promise<VaultUnlockChallenge> {\n return this.send<VaultUnlockChallenge>('POST', '/v1/vault/unlock/challenge', opts, {});\n }\n\n /**\n * `POST /v1/vault/unlock` — end a lock with a device-key proof over {@link vaultUnlockMessage} or a passkey whose\n * challenge is base64url(SHA-256(that message with `passkey`)). 403 `challenge_invalid`, `wear_t3_only`, …\n */\n unlock(body: VaultUnlockRequest, opts: CallOpts = {}): Promise<Reply<'unlockVault'>> {\n return this.send<Reply<'unlockVault'>>('POST', '/v1/vault/unlock', opts, { ...body });\n }\n\n /** `GET /v1/vault/limits` — per-handle usage caps on your items. */\n async limits(opts: CallOpts = {}): Promise<VaultItemLimits[]> {\n const r = await this.get<Reply<'listVaultLimits'>>('/v1/vault/limits', opts);\n return [...r.limits];\n }\n\n /**\n * `PUT /v1/vault/items/{id}/limits` — all three keys required; `null` removes a cap, all `null` removes the limits\n * (answers `null`). Over a cap the broker calls answer 429 `vault_rate_limited` with `Retry-After`.\n */\n async setLimits(\n id: string,\n limits: VaultItemLimitsInput,\n opts: CallOpts = {},\n ): Promise<VaultItemLimits | null> {\n const r = await this.http.json<Reply<'setVaultItemLimits'>>(\n seg('/v1/vault/items', id, '/limits'),\n {\n method: 'PUT',\n body: {\n per_minute: limits.per_minute,\n per_day: limits.per_day,\n units_per_day: limits.units_per_day,\n },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n return r.limits ?? null;\n }\n\n /** `GET /v1/vault/vaults` — vaults you belong to, with your role and sealed vault key. */\n vaults(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/vaults', opts);\n }\n\n /** `POST /v1/vault/vaults` — register a vault created client-side (HTTP 201). */\n createVault(body: VaultCreate, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/vaults', opts, body);\n }\n\n /** `GET /v1/vault/items` — envelopes you can read; with `since` (ISO) only changes after it, tombstones included. */\n items(params: QueryOf<'listVaultItems'> = {}, opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/items', opts, { since: params.since });\n }\n\n /** `PUT /v1/vault/items/{id}` — store an envelope (new = revision 1, update = revision + 1, 409 otherwise). */\n putItem(id: string, envelope: VaultItemEnvelope, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('PUT', seg('/v1/vault/items', id), opts, envelope);\n }\n\n /** `DELETE /v1/vault/items/{id}` — tombstone; revokes every grant on the item and drops its cloud copy. */\n deleteItem(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('DELETE', seg('/v1/vault/items', id), opts);\n }\n\n /** `PUT /v1/vault/items/{id}/cloud` — owner only: the decrypted item to seal with KMS for cloud agents, or null. */\n setItemCloud(\n id: string,\n item: Record<string, unknown> | null,\n opts: CallOpts = {},\n ): Promise<VaultObject> {\n return this.http.json<VaultObject>(seg('/v1/vault/items', id, '/cloud'), {\n method: 'PUT',\n body: { item },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/vault/rules` — policy rules (item, agent glob, mode → tier). */\n rules(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/rules', opts);\n }\n\n /** `POST /v1/vault/rules` — add a rule (HTTP 201). Host binding and honeytokens cannot be overridden. */\n createRule(body: VaultRuleCreate, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/rules', opts, body);\n }\n\n /** `DELETE /v1/vault/rules/{id}`. */\n deleteRule(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('DELETE', seg('/v1/vault/rules', id), opts);\n }\n\n /** `GET /v1/vault/grants` — standing grants created by your approvals. */\n grants(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/grants', opts);\n }\n\n /** `DELETE /v1/vault/grants/{id}` — revoke a grant immediately. */\n revokeGrant(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('DELETE', seg('/v1/vault/grants', id), opts);\n }\n\n /** `POST /v1/vault/grants/revoke-task` — revoke every live grant of a task / session; answers `{ revoked }`. */\n revokeTaskGrants(task: string, opts: CallOpts = {}): Promise<Reply<'revokeVaultTaskGrants'>> {\n return this.send<Reply<'revokeVaultTaskGrants'>>('POST', '/v1/vault/grants/revoke-task', opts, {\n task,\n });\n }\n\n /** `GET /v1/vault/events` — append-only audit log (never contains secret values). */\n events(params: QueryOf<'listVaultEvents'> = {}, opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/events', opts, { limit: params.limit });\n }\n\n /** `GET /v1/vault/approvals` — agent requests waiting for your decision. */\n approvals(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/approvals', opts);\n }\n\n /** `GET /v1/vault/approvals/{id}` — pending, approved, denied or expired. */\n approval(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.get(seg('/v1/vault/approvals', id), opts);\n }\n\n /**\n * `POST /v1/vault/approvals/{id}/decide` — send `signature` (v1 vault key) or `proof` (v2 device key / passkey),\n * never both. Deny needs no proof; a t4 approve needs a device or passkey proof (Wear: t3 only).\n */\n decide(id: string, body: VaultDecision, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', seg('/v1/vault/approvals', id, '/decide'), opts, body);\n }\n\n /** `GET /v1/vault/catalog` — items exposed to agents (handle, title, kind, hosts, env name); no values. */\n catalog(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/catalog', opts);\n }\n\n /** `POST /v1/vault/use` — a policy decision for one use; t3/t4 return a pending approval id. */\n use(body: VaultUseRequest, opts: CallOpts = {}): Promise<VaultUseDecision> {\n return this.send<Reply<'vaultUse'>>('POST', '/v1/vault/use', opts, body);\n }\n\n /** `POST /v1/vault/http` — brokered HTTPS call with `{{vault:<slug>}}` handles; 202 = approval required. */\n httpCall(body: VaultHttpRequest, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/http', opts, body);\n }\n\n /** `POST /v1/vault/resolve` — codai local brokers only (cloud fallback of `codaid vault run`); 202 = approval. */\n resolve(body: VaultResolveRequest, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/resolve', opts, body);\n }\n}\n","/**\n * `POST /v1/studio/abuse-reports` — report illegal or abusive content seen on a codai Studio share (`/s/<token>`) or\n * review (`/r/<token>`) link (DSA art. 16 notice). Public: the key is not required by the route; an unknown link still\n * answers 202 (no enumeration). Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema, stripUndefined } from './_shared';\n\n/** `share_token`, `surface`, `category`, `explanation`, `reporter_name`, `reporter_email`, `good_faith: true`. */\nexport type StudioAbuseReportRequest = Mutable<Schema<'StudioAbuseReportRequest'>>;\n/** `{ id, object: 'studio.abuse_report', status: 'open' }`. */\nexport type StudioAbuseReport = Schema<'StudioAbuseReport'>;\n\nexport class AbuseReports {\n constructor(private readonly http: HttpClient) {}\n\n /** Store an abuse report for manual review (HTTP 202). Rate-limited per IP; never retried. */\n create(\n body: StudioAbuseReportRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<StudioAbuseReport> {\n return this.http.json<StudioAbuseReport>('/v1/studio/abuse-reports', {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/**\n * `POST /v1/public/provenance/check` — check a file for the AI-provenance marks codai writes (C2PA manifest presence +\n * claimed issuer, WAV RIFF INFO, MP3 ID3 TXXX, MP4 udta/meta, image XMP). Public: the route does not require the key;\n * the file is not stored. C2PA signatures are not verified and SynthID is never checked (see the result flags). Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Schema } from './_shared';\n\n/** `{ media_type, findings, codai_generated, synthid_checked: false, signature_verified: false }`. */\nexport type ProvenanceCheckResult = Schema<'ProvenanceCheckResult'>;\n/** One mark: `{ kind, present, ai_marked, codai, details }`. */\nexport type ProvenanceFinding = Schema<'ProvenanceFinding'>;\n\n/** Largest file the checker accepts (25 MB). */\nexport const PROVENANCE_MAX_BYTES = 25 * 1024 * 1024;\n\nexport class Provenance {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Upload `file` (PNG, JPEG, WebP, WAV, MP3 or MP4, ≤ 25 MB) and return what was found. A `Blob`/`File` sends its own\n * `type`; raw bytes need `contentType` (default `application/octet-stream`). Never retried.\n */\n check(\n file: Blob | Uint8Array<ArrayBuffer> | ArrayBuffer,\n opts: { contentType?: string; ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ProvenanceCheckResult> {\n const type =\n opts.contentType ||\n (file instanceof Blob && file.type ? file.type : 'application/octet-stream');\n return this.http.json<ProvenanceCheckResult>('/v1/public/provenance/check', {\n method: 'POST',\n rawBody: file,\n headers: { 'Content-Type': type },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/** `POST /v1/messages` — Anthropic Messages wire (JSON + named-event SSE). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient, readSse } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type MessageRequest = Mutable<Body<'createMessage'>>;\nexport type MessageResponse = Reply<'createMessage'>;\n/** Request body as accepted by the SDK: `stream` is set by the method and `model` defaults to `codai`. */\nexport type MessageInput = Omit<MessageRequest, 'stream' | 'model'> & { model?: string };\n\nexport interface MessageCallOptions {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface MessageResult {\n /** Concatenated `text` blocks of the reply. */\n text: string;\n raw: MessageResponse;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers;\n}\n\n/** One Anthropic streaming event: `event.type` mirrors the SSE `event:` name. */\nexport interface MessageStreamEvent {\n type:\n | 'message_start'\n | 'content_block_start'\n | 'content_block_delta'\n | 'content_block_stop'\n | 'message_delta'\n | 'message_stop'\n | 'ping'\n | 'error'\n | (string & {});\n [key: string]: unknown;\n}\n\nexport interface MessageStreamResult {\n /** Concatenated `text_delta` payloads. */\n text: string;\n /** Final `stop_reason` from `message_delta`, when sent. */\n stopReason: string | null;\n /** Cumulative usage: `input_tokens` from `message_start`, `output_tokens` from `message_delta`. */\n usage: { inputTokens: number; outputTokens: number } | null;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers | null;\n}\n\nexport interface MessageStream extends AsyncIterable<MessageStreamEvent> {\n readonly final: Promise<MessageStreamResult>;\n /** Text deltas only. */\n text(): AsyncIterable<string>;\n}\n\nexport class Messages {\n constructor(private readonly http: HttpClient) {}\n\n async create(body: MessageInput, opts: MessageCallOptions = {}): Promise<MessageResult> {\n const res = await this.http.request('/v1/messages', {\n body: { ...body, model: body.model ?? 'codai', stream: false },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as MessageResponse;\n const text = (raw.content ?? [])\n .map((b) => (b.type === 'text' && typeof b.text === 'string' ? b.text : ''))\n .join('');\n return {\n text,\n raw,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n stream(body: MessageInput, opts: MessageCallOptions = {}): MessageStream {\n const requestPromise = this.http.request('/v1/messages', {\n body: { ...body, model: body.model ?? 'codai', stream: true },\n ext: opts.ext,\n signal: opts.signal,\n timeoutMs: 0,\n noRetry: true,\n });\n\n let resolveFinal!: (r: MessageStreamResult) => void;\n let rejectFinal!: (e: unknown) => void;\n const final = new Promise<MessageStreamResult>((resolve, reject) => {\n resolveFinal = resolve;\n rejectFinal = reject;\n });\n final.catch(() => {});\n\n let text = '';\n let stopReason: string | null = null;\n let inputTokens: number | null = null;\n let outputTokens: number | null = null;\n let res: Response | null = null;\n\n async function* events(): AsyncGenerator<MessageStreamEvent, void, undefined> {\n try {\n res = await requestPromise;\n for await (const frame of readSse(res, opts.signal)) {\n const ev = frameJson<MessageStreamEvent>(frame);\n if (!ev) continue;\n if (typeof ev.type !== 'string') ev.type = frame.event;\n if (ev.type === 'message_start') {\n const usage = (ev.message as { usage?: { input_tokens?: number } } | undefined)?.usage;\n if (usage?.input_tokens !== undefined) inputTokens = usage.input_tokens;\n } else if (ev.type === 'content_block_delta') {\n const delta = ev.delta as { type?: string; text?: string } | undefined;\n if (delta?.type === 'text_delta' && typeof delta.text === 'string') text += delta.text;\n } else if (ev.type === 'message_delta') {\n const delta = ev.delta as { stop_reason?: string | null } | undefined;\n if (delta?.stop_reason) stopReason = delta.stop_reason;\n const usage = ev.usage as { output_tokens?: number } | undefined;\n if (usage?.output_tokens !== undefined) outputTokens = usage.output_tokens;\n }\n yield ev;\n if (ev.type === 'message_stop') break;\n }\n resolveFinal({\n text,\n stopReason,\n usage:\n inputTokens !== null || outputTokens !== null\n ? { inputTokens: inputTokens ?? 0, outputTokens: outputTokens ?? 0 }\n : null,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id') ?? null,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n });\n } catch (err) {\n rejectFinal(err);\n throw err;\n }\n }\n\n async function* textOnly(): AsyncGenerator<string, void, undefined> {\n for await (const ev of events()) {\n if (ev.type !== 'content_block_delta') continue;\n const delta = ev.delta as { type?: string; text?: string } | undefined;\n if (delta?.type === 'text_delta' && delta.text) yield delta.text;\n }\n }\n\n return {\n [Symbol.asyncIterator]: () => events(),\n text: () => ({ [Symbol.asyncIterator]: () => textOnly() }),\n final,\n };\n }\n}\n","/** `GET /v1/models`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type Model = Schema<'CoreModel'>;\nexport type ModelList = Reply<'listModels'>;\n\nexport class Models {\n constructor(private readonly http: HttpClient) {}\n\n /** Every model the calling key may address (OpenAI list shape, `data[]`). */\n async list(opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {}): Promise<Model[]> {\n const raw = await this.http.json<ModelList>('/v1/models', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.data ?? [])];\n }\n}\n","/** `/v1/orgs/*` — the orgs (teams) you belong to and their members. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Org = Schema<'OrgWithRole'>;\nexport type OrgMember = Schema<'OrgMember'>;\nexport type OrgRole = Schema<'OrgRole'>;\nexport type OrgAddMemberBody = Mutable<Body<'addOrgMember'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class OrgMembers {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/orgs/{id}/members` */\n async list(orgId: string, opts: CallOpts = {}): Promise<OrgMember[]> {\n const raw = await this.http.json<Reply<'listOrgMembers'>>(\n `/v1/orgs/${encodeURIComponent(orgId)}/members`,\n { ext: opts.ext, signal: opts.signal },\n );\n return [...(raw.members ?? [])];\n }\n\n /** `POST /v1/orgs/{id}/members` — add or re-role (owner/admin). */\n add(\n orgId: string,\n body: OrgAddMemberBody,\n opts: CallOpts = {},\n ): Promise<Reply<'addOrgMember', 201>> {\n return this.http.json<Reply<'addOrgMember', 201>>(\n `/v1/orgs/${encodeURIComponent(orgId)}/members`,\n { body, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `DELETE /v1/orgs/{id}/members/{userId}` */\n remove(orgId: string, userId: string, opts: CallOpts = {}): Promise<Reply<'removeOrgMember'>> {\n return this.http.json<Reply<'removeOrgMember'>>(\n `/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(userId)}`,\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class Orgs {\n readonly members: OrgMembers;\n constructor(private readonly http: HttpClient) {\n this.members = new OrgMembers(http);\n }\n\n /** `POST /v1/orgs` */\n create(name: string, opts: CallOpts = {}): Promise<Org> {\n return this.http.json<Org>('/v1/orgs', { body: { name }, ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/orgs` */\n async list(opts: CallOpts = {}): Promise<Org[]> {\n const raw = await this.http.json<Reply<'listOrgs'>>('/v1/orgs', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.orgs ?? [])];\n }\n}\n","/** `/v1/projects/*` — projects (a repo + isolation policy) that group environments. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Project = Schema<'Project'>;\nexport type ProjectIsolation = Schema<'ProjectIsolation'>;\nexport type ProjectCreateBody = Mutable<Body<'createProject'>>;\nexport type ProjectPatchBody = Mutable<Body<'updateProject'>>;\nexport type ProjectDetail = Reply<'getProject'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Projects {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/projects` — projects you own plus those of your orgs, newest first. */\n async list(opts: CallOpts = {}): Promise<Project[]> {\n const raw = await this.http.json<Reply<'listProjects'>>('/v1/projects', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.projects ?? [])];\n }\n\n /** `POST /v1/projects` — 409 `slug_taken` when the slug is already yours. */\n async create(body: ProjectCreateBody, opts: CallOpts = {}): Promise<Project> {\n const raw = await this.http.json<Reply<'createProject', 201>>('/v1/projects', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n return raw.project;\n }\n\n /** `GET /v1/projects/{id}` — the project plus every environment in it. */\n get(projectId: string, opts: CallOpts = {}): Promise<ProjectDetail> {\n return this.http.json<ProjectDetail>(`/v1/projects/${encodeURIComponent(projectId)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/projects/{id}` — owner or org owner/admin; the slug cannot change. */\n async update(projectId: string, body: ProjectPatchBody, opts: CallOpts = {}): Promise<Project> {\n const raw = await this.http.json<Reply<'updateProject'>>(\n `/v1/projects/${encodeURIComponent(projectId)}`,\n { method: 'PATCH', body, ext: opts.ext, signal: opts.signal },\n );\n return raw.project;\n }\n\n /** `DELETE /v1/projects/{id}` — 409 `project_has_environments` until all are destroyed. */\n delete(projectId: string, opts: CallOpts = {}): Promise<Reply<'deleteProject'>> {\n return this.http.json<Reply<'deleteProject'>>(`/v1/projects/${encodeURIComponent(projectId)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `wss://…/v1/realtime` — dependency-free realtime client (live transcription and the OpenAI\n * Realtime protocol lanes). Not an OpenAPI operation (OpenAPI cannot describe WebSockets), so it is\n * outside the `OPERATION_METHODS` parity table.\n *\n * const live = codai.realtime.connect({ model: 'codai-transcribe-live', language: 'ro', token });\n * live.appendAudio(pcm16At24kHz); // Int16Array | ArrayBuffer | Uint8Array\n * for await (const ev of live) {\n * if (ev.type === 'conversation.item.input_audio_transcription.delta') draw(ev.delta);\n * }\n *\n * Uses the global `WebSocket` (browsers, Node ≥ 22, Deno, Bun) or an injected constructor.\n * - Browser path: pass an ephemeral `token` (scope `realtime` or `live`); it travels as `?key=`.\n * Raw `codai_` keys in the query string are refused by the gateway (close 4401).\n * - Server path: pass `apiKey` (or a token) with a WebSocket constructor that accepts headers\n * (e.g. `ws`); it is sent as `Authorization: Bearer` on the upgrade.\n */\n\n/** Minimal WebSocket surface (browser `WebSocket`, Node 22 global, or the `ws` package). */\nexport interface RealtimeSocket {\n readonly readyState: number;\n binaryType?: string;\n send(data: string | ArrayBuffer | ArrayBufferView): void;\n close(code?: number, reason?: string): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\n/** `new (url, protocols?, options?)` — the third argument is used for headers by `ws`. */\nexport type RealtimeSocketCtor = new (\n url: string,\n protocols?: string | string[],\n options?: { headers?: Record<string, string> },\n) => RealtimeSocket;\n\nexport type RealtimeModel =\n 'codai-transcribe-live' | 'codai-realtime' | 'codai-voice' | (string & Record<never, never>);\n\nexport interface RealtimeConnectOptions {\n /** Default `codai-transcribe-live`. */\n model?: RealtimeModel;\n /** Language hint (`ro`, `en`, …). `ro` uses the Deepgram Nova-3 lane when the gateway has it. */\n language?: string;\n /** Ephemeral token (scope `realtime` or `live`) — sent as `?key=`. Required in browsers. */\n token?: string;\n /** Raw API key — sent as `Authorization: Bearer` (needs a ctor that supports headers). */\n apiKey?: string;\n /** Conversation id recorded on the usage row (`?session_id=`). */\n sessionId?: string;\n /**\n * First frame sent on open. Default for `codai-transcribe-live`: a transcription\n * `session.update` (PCM 24 kHz, `language` when set). Pass `null` to send nothing.\n */\n sessionUpdate?: Record<string, unknown> | null;\n /** Injectable WebSocket constructor (tests, `ws` on older Node). Defaults to `globalThis.WebSocket`. */\n WebSocket?: RealtimeSocketCtor;\n /** Override the gateway base URL (default: the client's `baseUrl`). */\n baseUrl?: string;\n}\n\n/** Typed subset of server events; anything else arrives as `RealtimeUnknownEvent`. */\nexport type RealtimeEvent =\n | {\n type: 'session.created' | 'session.updated';\n session?: Record<string, unknown>;\n event_id?: string;\n }\n | {\n type: 'conversation.item.input_audio_transcription.delta';\n item_id: string;\n content_index?: number;\n delta: string;\n event_id?: string;\n }\n | {\n type: 'conversation.item.input_audio_transcription.completed';\n item_id: string;\n content_index?: number;\n transcript: string;\n event_id?: string;\n }\n | { type: 'input_audio_buffer.committed'; item_id?: string; previous_item_id?: string | null }\n | { type: 'input_audio_buffer.cleared' }\n | { type: 'error'; error: { type?: string; code?: string; message?: string } }\n /** Emitted by the client itself when the socket closes (always the last event). */\n | { type: 'close'; code: number; reason: string };\nexport type RealtimeUnknownEvent = { type: string; [k: string]: unknown };\nexport type RealtimeAnyEvent = RealtimeEvent | RealtimeUnknownEvent;\n\ntype Listener = (ev: RealtimeAnyEvent) => void;\n\nconst OPEN = 1;\n\nfunction toBytes(audio: Int16Array | ArrayBuffer | Uint8Array): Uint8Array {\n if (audio instanceof ArrayBuffer) return new Uint8Array(audio);\n return new Uint8Array(audio.buffer, audio.byteOffset, audio.byteLength);\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let bin = '';\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(bin);\n}\n\n/** A live realtime session: async-iterable of events + `on()` listeners. */\nexport class RealtimeSession implements AsyncIterable<RealtimeAnyEvent> {\n private readonly listeners = new Map<string, Set<Listener>>();\n private readonly queue: RealtimeAnyEvent[] = [];\n private readonly waiters: Array<(r: IteratorResult<RealtimeAnyEvent>) => void> = [];\n private readonly outbox: string[] = [];\n private closed = false;\n /** Resolves when the socket is open (rejects if it closes first). */\n readonly ready: Promise<void>;\n\n constructor(\n readonly socket: RealtimeSocket,\n firstFrame: Record<string, unknown> | null,\n ) {\n let resolveReady!: () => void;\n let rejectReady!: (e: Error) => void;\n this.ready = new Promise<void>((res, rej) => {\n resolveReady = res;\n rejectReady = rej;\n });\n // Unhandled-rejection safety: callers that never await `ready` still get the `close` event.\n this.ready.catch(() => undefined);\n socket.onopen = () => {\n if (firstFrame) socket.send(JSON.stringify(firstFrame));\n for (const f of this.outbox.splice(0)) socket.send(f);\n resolveReady();\n };\n socket.onmessage = (ev) => {\n if (typeof ev.data !== 'string') return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(ev.data);\n } catch {\n return;\n }\n if (\n parsed &&\n typeof parsed === 'object' &&\n typeof (parsed as { type?: unknown }).type === 'string'\n ) {\n this.emit(parsed as RealtimeAnyEvent);\n }\n };\n socket.onerror = () => {\n /* the close event carries the code */\n };\n socket.onclose = (ev) => {\n rejectReady(\n new Error(`realtime socket closed before open (${String(ev.code)} ${ev.reason})`),\n );\n this.emit({ type: 'close', code: ev.code, reason: ev.reason });\n this.closed = true;\n for (const w of this.waiters.splice(0)) w({ value: undefined, done: true });\n };\n }\n\n /** Listen for one event type (`'*'` = every event). Returns an unsubscribe function. */\n on(type: string, fn: Listener): () => void {\n let set = this.listeners.get(type);\n if (!set) this.listeners.set(type, (set = new Set()));\n set.add(fn);\n return () => set.delete(fn);\n }\n\n /** Send any client event (JSON). Queued until the socket opens. */\n send(event: Record<string, unknown>): void {\n if (this.closed) throw new Error('realtime session is closed');\n const frame = JSON.stringify(event);\n if (this.socket.readyState === OPEN) this.socket.send(frame);\n else this.outbox.push(frame);\n }\n\n /** Append PCM16 little-endian mono audio (24 kHz for `codai-transcribe-live`). */\n appendAudio(audio: Int16Array | ArrayBuffer | Uint8Array): void {\n const bytes = toBytes(audio);\n if (bytes.byteLength === 0) return;\n this.send({ type: 'input_audio_buffer.append', audio: bytesToBase64(bytes) });\n }\n\n /** Close the current utterance: the server answers with one `...transcription.completed`. */\n commit(): void {\n this.send({ type: 'input_audio_buffer.commit' });\n }\n\n /** Drop audio the server holds for the current utterance. */\n clear(): void {\n this.send({ type: 'input_audio_buffer.clear' });\n }\n\n close(code = 1000, reason = 'client closed'): void {\n if (this.closed) return;\n this.socket.close(code, reason);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<RealtimeAnyEvent> {\n return {\n next: () => {\n const ev = this.queue.shift();\n if (ev) return Promise.resolve({ value: ev, done: false });\n if (this.closed) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => this.waiters.push(resolve));\n },\n return: () => {\n this.close();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n }\n\n private emit(ev: RealtimeAnyEvent): void {\n for (const fn of this.listeners.get(ev.type) ?? []) fn(ev);\n for (const fn of this.listeners.get('*') ?? []) fn(ev);\n const w = this.waiters.shift();\n if (w) w({ value: ev, done: false });\n else this.queue.push(ev);\n }\n}\n\n/** Build the `wss://…/v1/realtime?…` URL (exported for tests and custom transports). */\nexport function realtimeUrl(baseUrl: string, opts: RealtimeConnectOptions): string {\n const url = new URL(`${baseUrl.replace(/\\/$/, '').replace(/^http/, 'ws')}/v1/realtime`);\n url.searchParams.set('model', opts.model ?? 'codai-transcribe-live');\n if (opts.language) url.searchParams.set('language', opts.language);\n if (opts.sessionId) url.searchParams.set('session_id', opts.sessionId);\n if (opts.token) url.searchParams.set('key', opts.token);\n return url.toString();\n}\n\nexport class Realtime {\n constructor(private readonly defaults: { baseUrl: string; apiKey?: string }) {}\n\n /** Open a realtime session. Returns immediately; `await session.ready` to wait for the socket. */\n connect(opts: RealtimeConnectOptions = {}): RealtimeSession {\n const Ctor = opts.WebSocket ?? (globalThis as { WebSocket?: RealtimeSocketCtor }).WebSocket;\n if (!Ctor) throw new Error('codai.realtime: no WebSocket available — pass options.WebSocket');\n const model = opts.model ?? 'codai-transcribe-live';\n let token = opts.token;\n let apiKey = token ? undefined : (opts.apiKey ?? this.defaults.apiKey);\n // A client constructed with an ephemeral token uses it the browser way (`?key=`).\n if (apiKey?.startsWith('codai_eph_v1.')) {\n token = apiKey;\n apiKey = undefined;\n }\n if (!token && !apiKey) throw new Error('codai.realtime: pass `token` (browser) or `apiKey`');\n const url = realtimeUrl(opts.baseUrl ?? this.defaults.baseUrl, { ...opts, model, token });\n const socket = apiKey\n ? new Ctor(url, undefined, { headers: { Authorization: `Bearer ${apiKey}` } })\n : new Ctor(url);\n if ('binaryType' in socket) socket.binaryType = 'arraybuffer';\n const first =\n opts.sessionUpdate !== undefined\n ? opts.sessionUpdate\n : model === 'codai-transcribe-live'\n ? {\n type: 'session.update',\n session: {\n type: 'transcription',\n audio: {\n input: {\n format: { type: 'audio/pcm', rate: 24000 },\n transcription: {\n model,\n ...(opts.language ? { language: opts.language } : {}),\n },\n },\n },\n },\n }\n : null;\n return new RealtimeSession(socket, first);\n }\n}\n","/** `/v1/referrals` — referral stats and invitees; mutations go through `PATCH /v1/account`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\nimport { type AccountPatchResponse } from './account';\n\nexport type ReferralsView = Reply<'getReferrals'>;\nexport type ReferralRow = Schema<'ReferralRow'>;\nexport type ReferralStats = Schema<'AccountReferral'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Referrals {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/referrals` — stats, redeem deadline and invitees (masked, no PII). */\n get(opts: CallOpts = {}): Promise<ReferralsView> {\n return this.http.json<ReferralsView>('/v1/referrals', { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Redeem a referrer's code (their username) — `PATCH /v1/account\n * { referral_code }`. Allowed within 7 days of signup; the outcome is in\n * `referral_result` of the response.\n */\n redeem(code: string, opts: CallOpts = {}): Promise<AccountPatchResponse> {\n return this.patch({ referral_code: code }, opts);\n }\n\n /** Opt in/out of the referral programme — `PATCH /v1/account { referral_consent }`. */\n setConsent(consent: boolean, opts: CallOpts = {}): Promise<AccountPatchResponse> {\n return this.patch({ referral_consent: consent }, opts);\n }\n\n private patch(\n body: { referral_code?: string; referral_consent?: boolean },\n opts: CallOpts,\n ): Promise<AccountPatchResponse> {\n return this.http.json<AccountPatchResponse>('/v1/account', {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * codai Resolve — execution-verified bug fixes, no fix no fee\n * (`https://resolve.codai.ro`, spec `apps/docs/openapi/en/resolve.yaml`).\n *\n * Resolve is a separate service from the gateway: it has its own host and a\n * flat `{ error: string }` error shape, so it gets its own `HttpClient` and\n * maps failures to `ResolveError` / `ResolveInsufficientFundsError`.\n */\nimport type { components } from '../generated/resolve';\nimport { CodaiError, type HttpClient, type RequestOptions } from '../http';\nimport { type Mutable } from './_shared';\n\ntype ResolveSchemas = components['schemas'];\n\nexport type ResolveIntake = Mutable<ResolveSchemas['ResolveIntake']>;\nexport type ResolveQuote = ResolveSchemas['ResolveQuote'];\nexport type ResolveDeclined = ResolveSchemas['ResolveDeclined'];\n/** `submit()` result: `201` quote / free-tier auto-accept, or `200` decline. */\nexport type ResolveSubmitResult = ResolveQuote | ResolveDeclined;\nexport type ResolveAccepted = ResolveSchemas['ResolveAccepted'];\n/** How an accepted job is paid: `free` > `intro` (€1) > `credit` (t7 fix credit) > `wallet`. */\nexport type ResolvePaidWith = ResolveSchemas['ResolvePaidWith'];\n/** `GET /v1/resolve/balance` — fix credits, intro availability, wallet (EUR micros). */\nexport type ResolveBalance = ResolveSchemas['ResolveBalance'];\nexport type ResolveJob = ResolveSchemas['ResolveJob'];\n/** `GET /v1/resolve/jobs` page: `{ jobs, next_cursor }`. */\nexport type ResolveJobList = ResolveSchemas['ResolveJobList'];\nexport type ResolveJobStatus = ResolveSchemas['ResolveJobStatus'];\nexport type ResolveTier = ResolveSchemas['ResolveTier'];\nexport type ResolveAttestation = ResolveSchemas['ResolveAttestation'];\n/** DSSE v1 envelope in `ResolveAttestation.signature` (`null` = unsigned, pre-2026-09-27). */\nexport type ResolveAttestationEnvelope = ResolveSchemas['ResolveAttestationEnvelope'];\nexport type ResolveKeys = ResolveSchemas['ResolveKeys'];\nexport type ResolveKey = ResolveSchemas['ResolveKey'];\nexport type ResolveReproTest = ResolveSchemas['ResolveReproTest'];\nexport type ResolveHealth = ResolveSchemas['ResolveHealth'];\nexport type ResolveValidationDetails = ResolveSchemas['ResolveValidationDetails'];\nexport type ResolveInsufficientFunds = ResolveSchemas['ResolveInsufficientFunds'];\n/** Body POSTed to `callback_url` (verify with `verifyResolveWebhook` first). */\nexport type ResolveWebhookEvent = ResolveSchemas['ResolveWebhookEvent'];\nexport type ResolveWebhookEventName = ResolveSchemas['ResolveWebhookEventName'];\nexport type ResolveWebhookJob = ResolveSchemas['ResolveWebhookJob'];\n\nexport interface VerifyResolveWebhookOptions {\n /** Maximum age (and future skew) of `t`, in seconds. Default 300. */\n toleranceSeconds?: number;\n /** Current unix time in seconds (tests). Default `Date.now() / 1000`. */\n nowSeconds?: number;\n}\n\n/**\n * Verify a Resolve webhook delivery: `x-codai-signature: t=<unix>,v1=<hex>`\n * with `v1 = HMAC-SHA256(callback_secret, \"<t>.<rawBody>\")`. Pass the RAW\n * request body (before JSON parsing). Constant-time compare; rejects a\n * timestamp outside `toleranceSeconds`. Returns `false` for any bad input.\n *\n * Server-side only: uses `node:crypto` (Node 20.16+/22.3+, Bun, Deno), loaded\n * lazily so the rest of the SDK still bundles for browsers and edge runtimes.\n * Throws only when `node:crypto` is unavailable in the current runtime.\n */\nexport function verifyResolveWebhook(\n secret: string,\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n opts: VerifyResolveWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false;\n let t: string | undefined;\n const v1s: string[] = [];\n for (const part of signatureHeader.split(',')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n const k = part.slice(0, eq).trim();\n const v = part.slice(eq + 1).trim();\n if (k === 't') t = v;\n else if (k === 'v1') v1s.push(v.toLowerCase());\n }\n if (!t || !/^\\d+$/.test(t) || v1s.length === 0) return false;\n const tolerance = opts.toleranceSeconds ?? 300;\n const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - Number(t)) > tolerance) return false;\n const { createHmac, timingSafeEqual } = nodeCrypto();\n const enc = new TextEncoder();\n const body = typeof rawBody === 'string' ? enc.encode(rawBody) : rawBody;\n const expected = createHmac('sha256', secret)\n .update(enc.encode(`${t}.`))\n .update(body)\n .digest();\n return v1s.some((v1) => {\n if (!/^[0-9a-f]{64}$/.test(v1)) return false;\n return timingSafeEqual(hexToBytes(v1), expected);\n });\n}\n\ntype NodeCrypto = {\n createHmac(\n alg: string,\n key: string,\n ): { update(d: Uint8Array): { update(d: Uint8Array): { digest(): Uint8Array } } };\n timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;\n};\n\nfunction nodeCrypto(): NodeCrypto {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const mod = proc?.getBuiltinModule?.('node:crypto') as NodeCrypto | undefined;\n if (!mod) {\n throw new Error(\n 'verifyResolveWebhook needs node:crypto (Node 20.16+/22.3+, Bun or Deno); run it server-side',\n );\n }\n return mod;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/** `payloadType` of Resolve attestation envelopes. */\nexport const RESOLVE_ATTESTATION_PAYLOAD_TYPE =\n 'application/vnd.codai.resolve.attestation+json;v=1';\n\nexport type ResolveAttestationVerifyResult =\n | { ok: true; keyid: string }\n | { ok: false; reason: 'UNSIGNED' | 'BAD_SIGNATURE' | 'STATEMENT_MISMATCH' | 'BAD_PAYLOAD_TYPE' };\n\ntype VerifyCrypto = {\n createHash(alg: string): { update(d: Uint8Array): { digest(enc: 'hex'): string } };\n createVerify(alg: string): {\n update(d: Uint8Array): void;\n verify(key: { key: string; dsaEncoding: 'der' }, sig: Uint8Array): boolean;\n };\n};\n\nfunction verifyCrypto(): VerifyCrypto {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const mod = proc?.getBuiltinModule?.('node:crypto') as VerifyCrypto | undefined;\n if (!mod) {\n throw new Error(\n 'verifyAttestation needs node:crypto (Node 20.16+/22.3+, Bun or Deno); run it server-side',\n );\n }\n return mod;\n}\n\n/** RFC 8785 (JCS) for the JSON subset a statement uses: sorted keys, no whitespace. */\nfunction canonicalJson(v: unknown): string {\n if (v === null || typeof v !== 'object') return JSON.stringify(v);\n if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;\n const o = v as Record<string, unknown>;\n return `{${Object.keys(o)\n .filter((k) => o[k] !== undefined)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`)\n .join(',')}}`;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/** DSSE v1 PAE: `\"DSSEv1\" SP len(type) SP type SP len(body) SP body` (byte lengths). */\nfunction pae(payloadType: string, body: Uint8Array): Uint8Array {\n const enc = new TextEncoder();\n const typeBytes = enc.encode(payloadType);\n const head = enc.encode(`DSSEv1 ${typeBytes.length} ${payloadType} ${body.length} `);\n const out = new Uint8Array(head.length + body.length);\n out.set(head, 0);\n out.set(body, head.length);\n return out;\n}\n\n/** The statement the Resolve service signs, recomputed from the attestation JSON. */\nexport function resolveAttestationStatement(att: ResolveAttestation): Record<string, unknown> {\n const { createHash } = verifyCrypto();\n const enc = new TextEncoder();\n const sha = (s: string | null | undefined) =>\n s == null ? null : createHash('sha256').update(enc.encode(s)).digest('hex');\n return {\n kind: 'codai.resolve.attestation.v1',\n attestation_id: att.id,\n repo_url: att.repo_url,\n base_commit: att.base_commit,\n patch_sha256: sha(att.patch),\n repro_test: att.repro_test?.path\n ? { path: att.repro_test.path, sha256: sha(att.repro_test.content) }\n : null,\n test_command: att.test_command,\n regression_command: att.regression_command,\n test_output_before_sha256: sha(att.test_output_before),\n test_output_after_sha256: sha(att.test_output_after),\n regression_output_sha256: sha(att.regression_output),\n runner_image_digest: att.runner_image_digest,\n started_at: att.started_at,\n verified_at: att.verified_at,\n };\n}\n\n/**\n * Verify a Resolve attestation offline against published keys: the DSSE\n * signature (ECDSA P-256/SHA-256, DER) over `PAE(payloadType, payload)` must\n * match one key, AND the signed statement must equal the one recomputed from\n * the attestation's own fields (so a valid signature over other content fails).\n * Server-side only (`node:crypto`, loaded lazily).\n */\nexport function verifyAttestationWithKeys(\n att: ResolveAttestation,\n keys: ResolveKeys,\n): ResolveAttestationVerifyResult {\n const env = att.signature;\n if (!env || !Array.isArray(env.signatures) || env.signatures.length === 0)\n return { ok: false, reason: 'UNSIGNED' };\n if (env.payloadType !== RESOLVE_ATTESTATION_PAYLOAD_TYPE)\n return { ok: false, reason: 'BAD_PAYLOAD_TYPE' };\n const { createVerify } = verifyCrypto();\n let body: Uint8Array;\n try {\n body = base64ToBytes(env.payload);\n } catch {\n return { ok: false, reason: 'BAD_SIGNATURE' };\n }\n const msg = pae(env.payloadType, body);\n let keyid: string | null = null;\n outer: for (const s of env.signatures) {\n let sig: Uint8Array;\n try {\n sig = base64ToBytes(s.sig);\n } catch {\n continue;\n }\n for (const k of keys.keys) {\n if (k.payload_type && k.payload_type !== env.payloadType) continue;\n try {\n const v = createVerify('SHA256');\n v.update(msg);\n if (v.verify({ key: k.public_key_pem, dsaEncoding: 'der' }, sig)) {\n keyid = k.keyid;\n break outer;\n }\n } catch {\n /* malformed key/signature — try the next */\n }\n }\n }\n if (keyid === null) return { ok: false, reason: 'BAD_SIGNATURE' };\n let signed: unknown;\n try {\n signed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body));\n } catch {\n return { ok: false, reason: 'STATEMENT_MISMATCH' };\n }\n if (canonicalJson(signed) !== canonicalJson(resolveAttestationStatement(att)))\n return { ok: false, reason: 'STATEMENT_MISMATCH' };\n return { ok: true, keyid };\n}\n\n/** Statuses after which a job never changes again. */\nexport const RESOLVE_TERMINAL_STATUSES: ReadonlySet<ResolveJobStatus> = new Set<ResolveJobStatus>([\n 'resolved',\n 'failed',\n 'declined',\n 'error',\n]);\n\n/** Any non-2xx answer from the Resolve service (flat `{ error }` body). */\nexport class ResolveError extends CodaiError {\n /** The `error` field of the body: a message, or Zod `flatten()` details on a 400. */\n readonly detail: string | ResolveValidationDetails | null;\n\n constructor(\n message: string,\n status: number,\n body: unknown,\n meta: { requestId?: string | null; retryAfter?: number | null } = {},\n ) {\n super(message, status, body, meta);\n this.name = 'ResolveError';\n this.detail = extractDetail(body);\n }\n}\n\n/** `402` on `accept()` — the wallet cannot hold the quote; the job stays `quoted`. */\nexport class ResolveInsufficientFundsError extends ResolveError {\n /** Wallet balance, in `currency` units (EUR micros). */\n readonly balance: number;\n /** Amount the hold needs, in `currency` units (EUR micros). */\n readonly required: number;\n readonly currency: 'micro_eur';\n /** pay.codai.ro checkout link for the shortfall — open it, then retry `accept()`. */\n readonly topupUrl: string;\n /** Present only for a `t7` job: fix-bundle checkout (10 t7 fix credits for €49). */\n readonly bundleUrl?: string;\n\n constructor(\n message: string,\n body: ResolveInsufficientFunds,\n meta: { requestId?: string | null } = {},\n ) {\n super(message, 402, body, meta);\n this.name = 'ResolveInsufficientFundsError';\n this.balance = body.balance;\n this.required = body.required;\n this.currency = body.currency;\n this.topupUrl = body.topup_url;\n if (typeof body.bundle_url === 'string') this.bundleUrl = body.bundle_url;\n }\n}\n\nexport interface ResolveWaitOptions {\n /** Poll interval (ms). Default 5_000. */\n intervalMs?: number;\n /** Give up after this long (ms); throws `ResolveError` (status 0, body = last job). Default 1_800_000. */\n timeoutMs?: number;\n /** Stop when the job reaches one of these. Default `RESOLVE_TERMINAL_STATUSES`. */\n until?: Iterable<ResolveJobStatus>;\n signal?: AbortSignal;\n /** Called with every polled job (progress UIs). */\n onPoll?: (job: ResolveJob) => void;\n}\n\ntype CallOpts = { signal?: AbortSignal };\n\n/** Query of `resolve.list()` / `resolve.iterate()`. */\nexport interface ResolveListQuery {\n /** One status or several (sent as a comma list). Omitted = every status. */\n status?: ResolveJobStatus | ResolveJobStatus[];\n /** Page size 1–100 (server default 20). */\n limit?: number;\n /** `next_cursor` of the previous page. */\n cursor?: string;\n}\n\nexport class Resolve {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/resolve/jobs` — submit a public GitHub repo + issue for triage.\n * Returns a quote (`status: 'quoted'`), a free-tier auto-accept\n * (`status: 'accepted'`) or a decline (`status: 'declined'`). Never retried:\n * a retry could create a second job.\n */\n submit(body: ResolveIntake, opts: CallOpts = {}): Promise<ResolveSubmitResult> {\n if (!body.issue_url && !body.issue_text)\n throw new TypeError('resolve.submit: one of issue_url or issue_text is required');\n return this.call<ResolveSubmitResult>('/v1/resolve/jobs', {\n method: 'POST',\n body,\n noRetry: true,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/resolve/jobs/{id}` — status, quote, reasons, cost and attestation pointer. */\n get(id: string, opts: CallOpts = {}): Promise<ResolveJob> {\n return this.call<ResolveJob>(`/v1/resolve/jobs/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/resolve/jobs` — one page of your jobs, newest first. Pass the\n * page's `next_cursor` back as `cursor` for the next page (`null` = last).\n * `status` filters by one or more statuses.\n */\n list(query: ResolveListQuery = {}, opts: CallOpts = {}): Promise<ResolveJobList> {\n const status = Array.isArray(query.status) ? query.status.join(',') : query.status;\n return this.call<ResolveJobList>('/v1/resolve/jobs', {\n query: { status: status || undefined, limit: query.limit, cursor: query.cursor },\n signal: opts.signal,\n });\n }\n\n /**\n * Every job matching `query`, newest first, following `next_cursor` page by\n * page (`limit` = page size). Stop early with `break`.\n */\n async *iterate(\n query: Omit<ResolveListQuery, 'cursor'> = {},\n opts: CallOpts = {},\n ): AsyncGenerator<ResolveJob, void, undefined> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.list({ ...query, cursor }, opts);\n for (const job of page.jobs) yield job;\n if (!page.next_cursor) return;\n cursor = page.next_cursor;\n }\n }\n\n /**\n * `POST /v1/resolve/jobs/{id}/accept` — accept a paid quote and start the job.\n * The result's `paid_with` says how it was paid (`intro` €1 hold, `credit`\n * t7 fix credit, or `wallet`). Throws `ResolveInsufficientFundsError` (402,\n * carries `topupUrl`, plus `bundleUrl` for t7) when the wallet is short,\n * `ResolveError` 409 when the job is not `quoted`.\n */\n accept(id: string, opts: CallOpts = {}): Promise<ResolveAccepted> {\n return this.call<ResolveAccepted>(`/v1/resolve/jobs/${encodeURIComponent(id)}/accept`, {\n method: 'POST',\n rawBody: '', // no body — sent with content-length: 0\n noRetry: true,\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/resolve/attestations/{id}` — public execution proof (no auth needed\n * server-side). Accepts the attestation id or the job's `attestation_url`.\n */\n attestation(idOrUrl: string, opts: CallOpts = {}): Promise<ResolveAttestation> {\n const id = idOrUrl.replace(/^.*\\/v1\\/resolve\\/attestations\\//, '');\n return this.call<ResolveAttestation>(`/v1/resolve/attestations/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /** `GET /health` — liveness of the Resolve service. */\n health(opts: CallOpts = {}): Promise<ResolveHealth> {\n return this.call<ResolveHealth>('/health', { signal: opts.signal });\n }\n\n /** `GET /v1/resolve/balance` — fix credits (t7 only), intro availability and wallet balance. */\n balance(opts: CallOpts = {}): Promise<ResolveBalance> {\n return this.call<ResolveBalance>('/v1/resolve/balance', { signal: opts.signal });\n }\n\n /** `GET /v1/resolve/keys` — public keys that sign attestations (no auth needed server-side). */\n keys(opts: CallOpts = {}): Promise<ResolveKeys> {\n return this.call<ResolveKeys>('/v1/resolve/keys', { signal: opts.signal });\n }\n\n /**\n * Verify an attestation's signature and that the signed statement matches\n * its fields. Fetches `keys()` unless `opts.keys` is given (pin them to\n * avoid trusting the network). `{ ok: false, reason: 'UNSIGNED' }` for\n * attestations created before signing (2026-09-27). Server-side only.\n */\n async verifyAttestation(\n att: ResolveAttestation,\n opts: { keys?: ResolveKeys; signal?: AbortSignal } = {},\n ): Promise<ResolveAttestationVerifyResult> {\n if (!att.signature) return { ok: false, reason: 'UNSIGNED' };\n const keys = opts.keys ?? (await this.keys({ signal: opts.signal }));\n return verifyAttestationWithKeys(att, keys);\n }\n\n /**\n * Poll `get(id)` until the job reaches a terminal status (`resolved`,\n * `failed`, `declined`, `error`) or one of `opts.until`. A `quoted` job\n * does not move until you `accept()` it.\n */\n async waitFor(id: string, opts: ResolveWaitOptions = {}): Promise<ResolveJob> {\n const intervalMs = opts.intervalMs ?? 5_000;\n const timeoutMs = opts.timeoutMs ?? 1_800_000;\n const until = new Set(opts.until ?? RESOLVE_TERMINAL_STATUSES);\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const job = await this.get(id, { signal: opts.signal });\n opts.onPoll?.(job);\n if (until.has(job.status)) return job;\n const left = deadline - Date.now();\n if (left <= 0)\n throw new ResolveError(\n `codai-resolve job ${id} still ${job.status} after ${timeoutMs} ms`,\n 0,\n job,\n );\n await abortableSleep(Math.min(intervalMs, left), opts.signal);\n }\n }\n\n private async call<T>(path: string, init: RequestOptions): Promise<T> {\n try {\n return await this.http.json<T>(path, init);\n } catch (err) {\n throw toResolveError(path, err);\n }\n }\n}\n\nfunction extractDetail(body: unknown): string | ResolveValidationDetails | null {\n if (body && typeof body === 'object' && 'error' in body) {\n const e = (body as { error: unknown }).error;\n if (typeof e === 'string') return e;\n if (e && typeof e === 'object') return e as ResolveValidationDetails;\n }\n return null;\n}\n\nfunction isInsufficientFunds(body: unknown): body is ResolveInsufficientFunds {\n return (\n !!body &&\n typeof body === 'object' &&\n (body as { error?: unknown }).error === 'insufficient_funds' &&\n typeof (body as { topup_url?: unknown }).topup_url === 'string'\n );\n}\n\n/** Re-type a `CodaiError` from the shared HTTP layer into the Resolve hierarchy. */\nfunction toResolveError(path: string, err: unknown): unknown {\n if (!(err instanceof CodaiError) || err instanceof ResolveError) return err;\n if (err.status === 0) return err; // network/timeout — nothing Resolve-specific\n const meta = { requestId: err.requestId, retryAfter: err.retryAfter };\n if (err.status === 402 && isInsufficientFunds(err.body)) {\n const b = err.body;\n return new ResolveInsufficientFundsError(\n `codai-resolve ${path} → 402: insufficient funds (balance ${b.balance}, required ${b.required} ${b.currency}); top up at ${b.topup_url}${b.bundle_url ? ` or buy 10 t7 fixes for €49 at ${b.bundle_url}` : ''}`,\n b,\n meta,\n );\n }\n const detail = extractDetail(err.body);\n const text =\n detail === null ? '' : `: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`;\n return new ResolveError(\n `codai-resolve ${path} → ${err.status}${text}`,\n err.status,\n err.body,\n meta,\n );\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason);\n };\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/** `POST /v1/responses` — OpenAI Responses API compatibility (JSON + named-event SSE). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient, readSse } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type ResponsesRequest = Mutable<Body<'createResponse'>>;\nexport type ResponsesResponse = Reply<'createResponse'>;\n/** Request body as accepted by the SDK: `stream` is set by the method and `model` defaults to `codai`. */\nexport type ResponsesInput = Omit<ResponsesRequest, 'stream' | 'model'> & { model?: string };\n\nexport interface ResponsesCallOptions {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface ResponsesResult {\n /** `output_text` of the response. */\n outputText: string;\n raw: ResponsesResponse;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers;\n}\n\n/** One Responses streaming event; `type` mirrors the SSE `event:` name. */\nexport interface ResponsesStreamEvent {\n type:\n | 'response.created'\n | 'response.output_text.delta'\n | 'response.output_item.done'\n | 'response.output_text.done'\n | 'response.completed'\n | (string & {});\n sequence_number?: number;\n [key: string]: unknown;\n}\n\nexport interface ResponsesStreamResult {\n outputText: string;\n /** The full `response` object from `response.completed`, when received. */\n response: ResponsesResponse | null;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers | null;\n}\n\nexport interface ResponsesStream extends AsyncIterable<ResponsesStreamEvent> {\n readonly final: Promise<ResponsesStreamResult>;\n /** Text deltas only. */\n text(): AsyncIterable<string>;\n}\n\nexport class Responses {\n constructor(private readonly http: HttpClient) {}\n\n async create(body: ResponsesInput, opts: ResponsesCallOptions = {}): Promise<ResponsesResult> {\n const res = await this.http.request('/v1/responses', {\n body: { ...body, model: body.model ?? 'codai', stream: false },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as ResponsesResponse;\n return {\n outputText: typeof raw.output_text === 'string' ? raw.output_text : '',\n raw,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n stream(body: ResponsesInput, opts: ResponsesCallOptions = {}): ResponsesStream {\n const requestPromise = this.http.request('/v1/responses', {\n body: { ...body, model: body.model ?? 'codai', stream: true },\n ext: opts.ext,\n signal: opts.signal,\n timeoutMs: 0,\n noRetry: true,\n });\n\n let resolveFinal!: (r: ResponsesStreamResult) => void;\n let rejectFinal!: (e: unknown) => void;\n const final = new Promise<ResponsesStreamResult>((resolve, reject) => {\n resolveFinal = resolve;\n rejectFinal = reject;\n });\n final.catch(() => {});\n\n let outputText = '';\n let response: ResponsesResponse | null = null;\n let res: Response | null = null;\n\n async function* events(): AsyncGenerator<ResponsesStreamEvent, void, undefined> {\n try {\n res = await requestPromise;\n for await (const frame of readSse(res, opts.signal)) {\n const ev = frameJson<ResponsesStreamEvent>(frame);\n if (!ev) continue;\n if (typeof ev.type !== 'string') ev.type = frame.event;\n if (ev.type === 'response.output_text.delta' && typeof ev.delta === 'string') {\n outputText += ev.delta;\n } else if (ev.type === 'response.completed' && ev.response) {\n response = ev.response as ResponsesResponse;\n }\n yield ev;\n if (ev.type === 'response.completed') break;\n }\n resolveFinal({\n outputText,\n response,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id') ?? null,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n });\n } catch (err) {\n rejectFinal(err);\n throw err;\n }\n }\n\n async function* textOnly(): AsyncGenerator<string, void, undefined> {\n for await (const ev of events()) {\n if (ev.type === 'response.output_text.delta' && typeof ev.delta === 'string')\n yield ev.delta;\n }\n }\n\n return {\n [Symbol.asyncIterator]: () => events(),\n text: () => ({ [Symbol.asyncIterator]: () => textOnly() }),\n final,\n };\n }\n}\n","/**\n * `/v1/sessions/*` — shared-sessions protocol v2 (events, controls, lease,\n * dispatch, SSE stream) plus the per-session shares under `/shares`.\n *\n * Every call needs the `x-codai-device` header: set it once via\n * `new Codai({ device: '<uuid>' })` or per call through `ext.device`.\n */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Session = Schema<'Session'>;\nexport type SessionListItem = Schema<'SessionListItem'>;\nexport type SessionDetail = Reply<'getSession'>;\nexport type SessionCreateRequest = Mutable<Body<'createSession'>>;\nexport type SessionPatchRequest = Mutable<Body<'updateSession'>>;\nexport type SessionEvent = Schema<'SessionEvent'>;\nexport type SessionIncomingEvent = Mutable<Schema<'SessionIncomingEvent'>>;\nexport type SessionEventsAppendRequest = Mutable<Body<'appendSessionEvents'>>;\nexport type SessionEventsAppendResponse = Reply<'appendSessionEvents'>;\nexport type SessionEventsPage = Reply<'listSessionEvents'>;\nexport type SessionControl = Schema<'SessionControl'>;\nexport type SessionControlRequest = Mutable<Body<'submitSessionControl'>>;\nexport type SessionControlAccepted = Reply<'submitSessionControl', 202>;\ntype SessionDispatchBase = Omit<Mutable<Body<'dispatchToDevice'>>, 'mode' | 'text' | 'turn_id'>;\n/**\n * `POST …/dispatch` body. `send` (the default) needs `text` and runs it as a new turn on the\n * target; `open` is a handoff — the target only opens the session, so it takes no text/turn.\n */\nexport type SessionDispatchRequest =\n | (SessionDispatchBase & { mode?: 'send'; text: string; turn_id?: string })\n | (SessionDispatchBase & { mode: 'open'; text?: never; turn_id?: never });\nexport type SessionDispatchMode = NonNullable<Body<'dispatchToDevice'>['mode']>;\nexport type SessionDispatchResponse = Reply<'dispatchToDevice', 202>;\nexport type SessionLeaseClaimRequest = Mutable<Body<'claimSessionLease'>>;\nexport type SessionLeaseResponse = Reply<'claimSessionLease'>;\nexport type SessionShare = Schema<'OrgSessionShare'>;\nexport type SessionShareCreateRequest = Mutable<Body<'createSessionShare'>>;\nexport type SessionShareCreated = Reply<'createSessionShare', 201>;\nexport type SharedSession = Schema<'OrgSharedSession'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\n/** Frames of `GET /v1/sessions/{id}/stream`; every payload carries `v: 1`. */\nexport type SessionStreamEvent =\n | { event: 'event'; data: { v: 1; seq: number } & Record<string, unknown> }\n | {\n event: 'control';\n data: { v: 1; id: string; kind: string; seq: number | null; applied: boolean } & Record<\n string,\n unknown\n >;\n }\n | { event: 'lease'; data: { v: 1; holder_device_id: string | null; expires_at: string | null } }\n | {\n event: 'presence';\n data: {\n v: 1;\n device_id: string;\n user_id: string;\n role: string;\n executor: boolean;\n last_seen: string;\n driving: boolean;\n online: boolean;\n };\n }\n | { event: string; data: Record<string, unknown> };\n\nconst enc = encodeURIComponent;\n\nexport class SessionLease {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/sessions/{id}/lease` — CAS claim; `force: true` takes over a live lease. */\n acquire(\n sessionId: string,\n body: SessionLeaseClaimRequest = {},\n opts: CallOpts = {},\n ): Promise<SessionLeaseResponse> {\n return this.http.json<SessionLeaseResponse>(`/v1/sessions/${enc(sessionId)}/lease`, {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PUT /v1/sessions/{id}/lease` — heartbeat every 10 s (TTL 30 s). */\n renew(sessionId: string, opts: CallOpts = {}): Promise<SessionLeaseResponse> {\n return this.http.json<SessionLeaseResponse>(`/v1/sessions/${enc(sessionId)}/lease`, {\n method: 'PUT',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sessions/{id}/lease` */\n release(sessionId: string, opts: CallOpts = {}): Promise<Reply<'releaseSessionLease'>> {\n return this.http.json<Reply<'releaseSessionLease'>>(`/v1/sessions/${enc(sessionId)}/lease`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class SessionEvents {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/sessions/{id}/events?after=&limit=` */\n list(\n sessionId: string,\n query: Mutable<QueryOf<'listSessionEvents'>> = {},\n opts: CallOpts = {},\n ): Promise<SessionEventsPage> {\n return this.http.json<SessionEventsPage>(`/v1/sessions/${enc(sessionId)}/events`, {\n query: { after: query.after, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sessions/{id}/events` — executor only (needs the live lease). */\n append(\n sessionId: string,\n body: SessionEventsAppendRequest,\n opts: CallOpts = {},\n ): Promise<SessionEventsAppendResponse> {\n return this.http.json<SessionEventsAppendResponse>(`/v1/sessions/${enc(sessionId)}/events`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class SessionControls {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/sessions/{id}/controls?applied=&target=` — drain the control queue. */\n async list(\n sessionId: string,\n query: { applied?: boolean; target?: 'me' | string } = {},\n opts: CallOpts = {},\n ): Promise<SessionControl[]> {\n const raw = await this.http.json<Reply<'listSessionControls'>>(\n `/v1/sessions/${enc(sessionId)}/controls`,\n {\n query: { applied: query.applied, target: query.target },\n ext: opts.ext,\n signal: opts.signal,\n },\n );\n return [...(raw.controls ?? [])];\n }\n\n /** `POST /v1/sessions/{id}/control` — send a control to the executor (editor+). */\n submit(\n sessionId: string,\n body: SessionControlRequest,\n opts: CallOpts = {},\n ): Promise<SessionControlAccepted> {\n return this.http.json<SessionControlAccepted>(`/v1/sessions/${enc(sessionId)}/control`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sessions/{id}/control/{cid}/applied` — executor only. */\n markApplied(\n sessionId: string,\n controlId: string,\n opts: CallOpts = {},\n ): Promise<Reply<'markSessionControlApplied'>> {\n return this.http.json<Reply<'markSessionControlApplied'>>(\n `/v1/sessions/${enc(sessionId)}/control/${enc(controlId)}/applied`,\n { method: 'POST', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class SessionShares {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/sessions/{id}/shares` — owner only. */\n async list(sessionId: string, opts: CallOpts = {}): Promise<SessionShare[]> {\n const raw = await this.http.json<Reply<'listSessionShares'>>(\n `/v1/sessions/${enc(sessionId)}/shares`,\n { ext: opts.ext, signal: opts.signal },\n );\n return [...(raw.shares ?? [])];\n }\n\n /** `POST /v1/sessions/{id}/shares` — `token` is returned once for link shares. */\n create(\n sessionId: string,\n body: SessionShareCreateRequest,\n opts: CallOpts = {},\n ): Promise<SessionShareCreated> {\n return this.http.json<SessionShareCreated>(`/v1/sessions/${enc(sessionId)}/shares`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sessions/{id}/shares/{shareId}` */\n delete(\n sessionId: string,\n shareId: string,\n opts: CallOpts = {},\n ): Promise<Reply<'deleteSessionShare'>> {\n return this.http.json<Reply<'deleteSessionShare'>>(\n `/v1/sessions/${enc(sessionId)}/shares/${enc(shareId)}`,\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `GET /v1/sessions/shared-with-me` */\n async sharedWithMe(\n query: { archived?: boolean } = {},\n opts: CallOpts = {},\n ): Promise<SharedSession[]> {\n const raw = await this.http.json<Reply<'listSessionsSharedWithMe'>>(\n '/v1/sessions/shared-with-me',\n {\n query: { archived: query.archived ? '1' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n },\n );\n return [...(raw.sessions ?? [])];\n }\n}\n\nexport class Sessions {\n readonly events: SessionEvents;\n readonly controls: SessionControls;\n readonly lease: SessionLease;\n readonly shares: SessionShares;\n\n constructor(private readonly http: HttpClient) {\n this.events = new SessionEvents(http);\n this.controls = new SessionControls(http);\n this.lease = new SessionLease(http);\n this.shares = new SessionShares(http);\n }\n\n /** `POST /v1/sessions` — idempotent on `session_key` (200 existing / 201 created). */\n async create(\n body: SessionCreateRequest = {},\n opts: CallOpts = {},\n ): Promise<Session & { created: boolean }> {\n const res = await this.http.request('/v1/sessions', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n const session = (await res.json()) as Session;\n return { ...session, created: res.status === 201 };\n }\n\n /** `GET /v1/sessions?limit=&archived=` — own sessions first, then shared. */\n async list(\n query: { limit?: number; archived?: boolean } = {},\n opts: CallOpts = {},\n ): Promise<SessionListItem[]> {\n const raw = await this.http.json<Reply<'listSessions'>>('/v1/sessions', {\n query: { limit: query.limit, archived: query.archived ? '1' : undefined, v: '2' },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.sessions ?? [])];\n }\n\n /** `GET /v1/sessions/{id}` — detail with members, lease and presence. */\n get(\n sessionId: string,\n query: { share?: string } = {},\n opts: CallOpts = {},\n ): Promise<SessionDetail> {\n return this.http.json<SessionDetail>(`/v1/sessions/${enc(sessionId)}`, {\n query: { share: query.share, v: '2' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/sessions/{id}` — rename / archive (owner). */\n update(sessionId: string, body: SessionPatchRequest, opts: CallOpts = {}): Promise<Session> {\n return this.http.json<Session>(`/v1/sessions/${enc(sessionId)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sessions/{id}` — irreversible (owner). */\n delete(sessionId: string, opts: CallOpts = {}): Promise<Reply<'deleteSession'>> {\n return this.http.json<Reply<'deleteSession'>>(`/v1/sessions/${enc(sessionId)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sessions/{id}/dispatch` — queue a `send` for one device and wake it over FCM.\n * `{ mode: 'open' }` hands the session off instead: the target just opens it (no user turn).\n */\n dispatch(\n sessionId: string,\n body: SessionDispatchRequest,\n opts: CallOpts = {},\n ): Promise<SessionDispatchResponse> {\n return this.http.json<SessionDispatchResponse>(`/v1/sessions/${enc(sessionId)}/dispatch`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/sessions/{id}/stream?after=` — live SSE of `event` / `control` /\n * `lease` / `presence` frames. `: ping` heartbeats are skipped. The server\n * closes after 30 min; reconnect with `after` = highest `seq` seen.\n */\n async *stream(\n sessionId: string,\n query: { after?: number; share?: string } = {},\n opts: CallOpts = {},\n ): AsyncGenerator<SessionStreamEvent, void, undefined> {\n const frames = this.http.sse(`/v1/sessions/${enc(sessionId)}/stream`, {\n query: { after: query.after, share: query.share },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data) continue;\n yield { event: frame.event, data } as SessionStreamEvent;\n }\n }\n}\n","/**\n * `/v1/settings` — account-level settings shared by every device of the account (per user, not per key). Reads\n * always return the full object with defaults applied; writes deep-merge a partial and are validated strictly.\n *\n * Optimistic concurrency: pass `{ version }` from the last read to `update()`. On a mismatch the gateway answers 409\n * `version_conflict` and nothing is written; the thrown `CodaiError` carries the current state in\n * `(err.body as SettingsConflict).current` (see {@link settingsConflictCurrent}).\n */\nimport { CodaiError, type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type SettingsResponse = Reply<'getSettings'>;\nexport type UserSettings = Schema<'UserSettings'>;\nexport type TranscriptsSettings = Schema<'TranscriptsSettings'>;\nexport type SettingsConflict = Schema<'SettingsConflict'>;\n\n/** A deep partial of {@link UserSettings}: only the fields to change (`language: null` = auto-detect). */\nexport type SettingsPatch = {\n transcripts?: { -readonly [K in keyof TranscriptsSettings]?: TranscriptsSettings[K] };\n};\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\ntype UpdateOpts = CallOpts & { version?: number };\n\n/** The `current` state of a 409 `version_conflict` thrown by `settings.update`, else null. */\nexport function settingsConflictCurrent(err: unknown): SettingsResponse | null {\n if (!(err instanceof CodaiError) || err.status !== 409 || err.code !== 'version_conflict')\n return null;\n const current = (err.body as Partial<SettingsConflict> | null)?.current;\n return current ?? null;\n}\n\nexport class Settings {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/settings` — full settings with defaults; `version` 0 / `updatedAt` null until the first write. */\n get(opts: CallOpts = {}): Promise<SettingsResponse> {\n return this.http.json<SettingsResponse>('/v1/settings', { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `PATCH /v1/settings` — deep-merge `partial` into the stored settings. With `opts.version` the write is\n * conditional (409 `version_conflict` on a mismatch). Unknown keys / invalid values throw a 400 `CodaiError`.\n */\n update(partial: SettingsPatch, opts: UpdateOpts = {}): Promise<SettingsResponse> {\n return this.http.json<SettingsResponse>('/v1/settings', {\n method: 'PATCH',\n body: { settings: partial, ...(opts.version !== undefined ? { version: opts.version } : {}) },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * OS protection gate (spec `packages/agent-core/spec/os-gate.json`).\n *\n * `GET /v1/policy` — effective client policy; `os_gate.allow_override` is false when ANY org of the\n * caller forbids overrides. Cache it (the gateway sends `max-age=300`) and keep the\n * last value offline; a 503 `policy_unavailable` means \"keep the cached value\".\n * `POST /v1/os-gate/events` — audit an override granted/revoked on a device (check ids + surface + app version +\n * time only; detection details never leave the device). Answers 202 `{ ok: true }`.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type PolicyResponse = Reply<'getPolicy'>;\nexport type OsGateEvent = Schema<'OsGateEvent'>;\nexport type OsGateCheckId = OsGateEvent['checks'][number];\nexport type OsGateSurface = OsGateEvent['surface'];\nexport type OsGateEventAccepted = Schema<'OsGateEventAccepted'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class OsGate {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/policy` — `{ os_gate: { allow_override } }` folded over every org of the caller (strictest wins). */\n policy(opts: CallOpts = {}): Promise<PolicyResponse> {\n return this.http.json<PolicyResponse>('/v1/policy', { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `POST /v1/os-gate/events` — record that the user granted or revoked an override of `checks` on `surface`.\n * The body is strict: unknown keys, unknown check ids or an empty `checks` list throw a 400 `CodaiError`.\n */\n recordEvent(event: OsGateEvent, opts: CallOpts = {}): Promise<OsGateEventAccepted> {\n return this.http.json<OsGateEventAccepted>('/v1/os-gate/events', {\n method: 'POST',\n body: event,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/studio/sfx` — the codai Studio sound-effects library (`codai-sfx`): curated CC0 sounds (Kenney packs) plus a\n * Freesound CC0-only fallback when the gateway has one configured. Searching and importing are free; an imported\n * sound becomes a studio asset (`kind: 'sfx'`) usable as `asset:<asset_id>` in `renders.create`.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type AssetDto } from './assets';\nimport { type QueryOf, type Reply, type Schema } from './_shared';\n\n/** One sound (always `license: 'CC0-1.0'`). */\nexport type SfxDto = Schema<'SfxDto'>;\nexport type SfxCategory = Schema<'SfxCategory'>;\nexport type SfxList = Reply<'searchSfx'>;\n/** `GET /v1/studio/sfx` query; `tags` may also be passed as an array (joined with commas). */\nexport type SfxSearchParams = Omit<QueryOf<'searchSfx'>, 'tags'> & {\n tags?: string | readonly string[];\n};\n/** Search result plus whether the Freesound fallback failed (`x-codai-sfx-fallback: unavailable`). */\nexport type SfxSearchResult = SfxList & { fallbackUnavailable: boolean };\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Sfx {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/studio/sfx` — best match first; `limit` 1–50 (default 20). */\n async search(params: SfxSearchParams = {}, opts: CallOpts = {}): Promise<SfxSearchResult> {\n const tags = Array.isArray(params.tags)\n ? params.tags.join(',')\n : (params.tags as string | undefined);\n const res = await this.http.request('/v1/studio/sfx', {\n query: {\n q: params.q,\n category: params.category,\n tags: tags || undefined,\n max_duration: params.max_duration,\n limit: params.limit,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n const body = (await res.json()) as SfxList;\n return {\n ...body,\n fallbackUnavailable: res.headers.get('x-codai-sfx-fallback') === 'unavailable',\n };\n }\n\n /**\n * `POST /v1/studio/sfx/{sfx_id}/import` — copies the sound into your assets (`kind: 'sfx'`, free). Freesound items\n * whose licence is not CC0 are refused with 400 `license_not_allowed`; an unknown id is 404.\n */\n import(sfxId: string, opts: CallOpts = {}): Promise<AssetDto> {\n return this.http.json<AssetDto>(`/v1/studio/sfx/${encodeURIComponent(sfxId)}/import`, {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `POST /v1/systemone` — typed decisions from codai-s1 (Choice / Score / Noul). */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type SystemOneRequest = Mutable<Body<'createSystemOne'>>;\nexport type SystemOneResponse = Reply<'createSystemOne'>;\ntype SystemOneState = NonNullable<SystemOneRequest['state']>;\nexport type SystemOneAnswers = NonNullable<SystemOneResponse['answers']>;\n\n/** Single-state call: `answers` is always present. */\nexport type SystemOneSingleRequest = Omit<SystemOneRequest, 'items'> & { state: SystemOneState };\nexport type SystemOneSingleResponse = SystemOneResponse & { answers: SystemOneAnswers };\n\n/** Batch call (1-16 items, same questions, run concurrently). */\nexport type SystemOneBatchRequest = Omit<SystemOneRequest, 'state' | 'items'> & {\n items: Array<{ id: string; state: SystemOneState }>;\n};\nexport type SystemOneBatchResponse = SystemOneResponse & {\n items: Array<{ id: string; answers: SystemOneAnswers }>;\n};\n\nexport class SystemOne {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Ask one or more typed questions about `state` (or about each of `items`). Throws on 503\n * `s1_unavailable` like any other error — keep a local fallback and catch it. The gateway\n * substitutes a generative model ONLY when you pass `fallback: 'codai-fast'`, and then the\n * response says `fallback_used: true`. `timeout_ms` (100-5000) bounds the s1 call.\n */\n async create(\n body: SystemOneSingleRequest,\n opts?: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<SystemOneSingleResponse>;\n async create(\n body: SystemOneBatchRequest,\n opts?: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<SystemOneBatchResponse>;\n async create(\n body: SystemOneRequest,\n opts?: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<SystemOneResponse>;\n async create(\n body: SystemOneRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SystemOneResponse> {\n const res = await this.http.request('/v1/systemone', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as SystemOneResponse;\n }\n\n /** Same questions about up to 16 states in one call; results come back in `items` order. */\n batch(\n body: SystemOneBatchRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SystemOneBatchResponse> {\n return this.create(body, opts);\n }\n}\n","/** `/v1/tasks/*` — outcome-billing task lifecycle. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Task = Schema<'Task'>;\nexport type TaskOutcome = Schema<'TaskOutcome'>;\nexport type TaskStats = Reply<'getTaskStats'>;\nexport type TaskListPage = Reply<'listTasks'>;\nexport type TaskConfirmRequest = Mutable<Body<'confirmTask'>>;\nexport type TaskConfirmResponse = Reply<'confirmTask'>;\nexport type TaskListQuery = Mutable<QueryOf<'listTasks'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Tasks {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/tasks` — newest first; page with `cursor` = previous `next_cursor`. */\n list(query: TaskListQuery = {}, opts: CallOpts = {}): Promise<TaskListPage> {\n return this.http.json<TaskListPage>('/v1/tasks', {\n query: { outcome: query.outcome, limit: query.limit, cursor: query.cursor },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/tasks/pending` — tasks awaiting your confirmation (max 100). */\n async pending(opts: CallOpts = {}): Promise<Task[]> {\n const raw = await this.http.json<Reply<'listPendingTasks'>>('/v1/tasks/pending', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.tasks ?? [])];\n }\n\n /** `GET /v1/tasks/stats?since=` */\n stats(since?: string | Date, opts: CallOpts = {}): Promise<TaskStats> {\n return this.http.json<TaskStats>('/v1/tasks/stats', {\n query: { since: since instanceof Date ? since.toISOString() : since },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/tasks/{id}` */\n get(id: string, opts: CallOpts = {}): Promise<Task> {\n return this.http.json<Task>(`/v1/tasks/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/tasks/{id}/confirm` — answer \"Did codai solve it?\". */\n confirm(id: string, body: TaskConfirmRequest, opts: CallOpts = {}): Promise<TaskConfirmResponse> {\n return this.http.json<TaskConfirmResponse>(`/v1/tasks/${encodeURIComponent(id)}/confirm`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `/v1/triggers/*` + `/v1/notifications/*` — event triggers (webhooks → agent sessions) and the inbox. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type TriggerList = Reply<'listTriggers'>;\nexport type TriggerCreateRequest = Mutable<Body<'createTrigger'>>;\nexport type TriggerCreated = Reply<'createTrigger'>;\nexport type TriggerPatch = Mutable<Body<'updateTrigger'>>;\nexport type TriggerUpdated = Reply<'updateTrigger'>;\nexport type TriggerTestRequest = Mutable<Body<'testTrigger'>>;\nexport type TriggerTestResult = Reply<'testTrigger'>;\nexport type TriggerEvents = Reply<'listTriggerEvents'>;\nexport type NotificationList = Reply<'listNotifications'>;\nexport type NotificationsRead = Reply<'markNotificationsRead'>;\n/** Reply of `DELETE /v1/notifications/:id` and `POST /v1/notifications/delete`. */\nexport type NotificationsDeleted = { readonly deleted: number };\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Triggers {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/triggers` — never includes the signing secret. */\n list(opts: CallOpts = {}): Promise<TriggerList> {\n return this.http.json<TriggerList>('/v1/triggers', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/triggers` — the response carries the signing `secret` ONCE. */\n create(body: TriggerCreateRequest, opts: CallOpts = {}): Promise<TriggerCreated> {\n return this.http.json<TriggerCreated>('/v1/triggers', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/triggers/{id}` — name / enabled / policy. */\n update(id: string, body: TriggerPatch, opts: CallOpts = {}): Promise<TriggerUpdated> {\n return this.http.json<TriggerUpdated>(`/v1/triggers/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/triggers/{id}` — its hook URL stops working immediately. */\n delete(id: string, opts: CallOpts = {}): Promise<Reply<'deleteTrigger'>> {\n return this.http.json<Reply<'deleteTrigger'>>(`/v1/triggers/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/triggers/{id}/rotate-secret` — new secret, shown once. */\n rotateSecret(id: string, opts: CallOpts = {}): Promise<Reply<'rotateTriggerSecret'>> {\n return this.http.json<Reply<'rotateTriggerSecret'>>(\n `/v1/triggers/${encodeURIComponent(id)}/rotate-secret`,\n { method: 'POST', body: {}, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `POST /v1/triggers/{id}/test` — manual fire through the full pipeline; returns the decision + reason. */\n /** `PUT /v1/triggers/{id}/secret` — store a secret issued by the source (e.g. a Sentry integration's client secret). */\n setSecret(id: string, secret: string, opts: CallOpts = {}): Promise<Reply<'setTriggerSecret'>> {\n return this.http.json<Reply<'setTriggerSecret'>>(\n `/v1/triggers/${encodeURIComponent(id)}/secret`,\n { method: 'PUT', body: { secret }, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /** `POST /v1/triggers/{id}/test` — manual fire through the full pipeline; returns the decision + reason. */\n test(id: string, body: TriggerTestRequest = {}, opts: CallOpts = {}): Promise<TriggerTestResult> {\n return this.http.json<TriggerTestResult>(`/v1/triggers/${encodeURIComponent(id)}/test`, {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/triggers/{id}/events?limit=` — recent deliveries with decisions. */\n events(id: string, limit?: number, opts: CallOpts = {}): Promise<TriggerEvents> {\n return this.http.json<TriggerEvents>(`/v1/triggers/${encodeURIComponent(id)}/events`, {\n query: { limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/hooks/{id}` — send an event to a `generic` / `form` trigger from your own code. Signs the body\n * (`X-Codai-Signature: t=<unix>,v1=HMAC_SHA256(secret, \"<t>.<body>\")`, WebCrypto — Node 20+, browsers, Deno,\n * Workers). `deliveryId` makes retries idempotent. The hook needs no API key (the signature is the auth).\n */\n async fireHook(\n id: string,\n secret: string,\n event: {\n title: string;\n message?: string;\n severity?: 'info' | 'low' | 'medium' | 'high' | 'critical';\n url?: string;\n subject?: string;\n labels?: string[];\n dedupe_key?: string;\n resolved?: boolean;\n },\n opts: CallOpts & { deliveryId?: string } = {},\n ): Promise<Reply<'receiveTriggerHook'>> {\n const raw = JSON.stringify(event);\n const t = Math.floor(Date.now() / 1000);\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const mac = new Uint8Array(\n await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${t}.${raw}`)),\n );\n const v1 = Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n return this.http.json<Reply<'receiveTriggerHook'>>(`/v1/hooks/${encodeURIComponent(id)}`, {\n method: 'POST',\n rawBody: raw,\n ext: {\n ...opts.ext,\n headers: {\n ...opts.ext?.headers,\n 'Content-Type': 'application/json',\n 'x-codai-signature': `t=${t},v1=${v1}`,\n ...(opts.deliveryId ? { 'x-codai-delivery': opts.deliveryId } : {}),\n },\n },\n signal: opts.signal,\n });\n }\n}\n\nexport class Notifications {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/notifications?unread=1&limit=` — newest first. */\n list(\n query: { unread?: boolean; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<NotificationList> {\n return this.http.json<NotificationList>('/v1/notifications', {\n query: { unread: query.unread ? '1' : undefined, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/notifications/read` — `ids` omitted = every unread one. */\n markRead(ids?: number[], opts: CallOpts = {}): Promise<NotificationsRead> {\n return this.http.json<NotificationsRead>('/v1/notifications/read', {\n method: 'POST',\n body: ids ? { ids } : {},\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/notifications/:id` — `{ deleted: 0 }` when the id is missing or not yours. */\n delete(id: number, opts: CallOpts = {}): Promise<NotificationsDeleted> {\n return this.http.json<NotificationsDeleted>(\n `/v1/notifications/${encodeURIComponent(String(id))}`,\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `POST /v1/notifications/delete` — 1..200 ids; ids of other users are skipped. */\n deleteMany(ids: number[], opts: CallOpts = {}): Promise<NotificationsDeleted> {\n return this.http.json<NotificationsDeleted>('/v1/notifications/delete', {\n method: 'POST',\n body: { ids },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `/v1/prompts/*` — pending prompts: ready-to-paste prompts left for a future chat (handoffs, follow-ups). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\n/** PR-07 recurrence: repeat every day/week/month (at HH:MM UTC), or reopen when the run session ends. */\nexport type PromptRecurrence = Mutable<Schema<'PromptRecurrence'>>;\n/** PR-07 launch preset applied when the prompt is started. */\nexport type PromptLaunchConfig = Mutable<Schema<'PromptLaunchConfig'>>;\n\nexport type Prompt = Schema<'Prompt'>;\n/** PR-04 / PR-07 organise fields (present on every prompt row). */\nexport type PromptOrganizeFields = Pick<\n Prompt,\n 'tags' | 'priority' | 'recurrence' | 'next_prompt_id' | 'launch' | 'is_template'\n>;\nexport type PromptStatus = Schema<'PromptStatus'>;\nexport type PromptSource = Schema<'PromptSource'>;\nexport type PromptList = Reply<'listPrompts'>;\n/** PR-04 list / export filters; `tag` also accepts one string (a single tag or a comma list). AND semantics. */\nexport type PromptListFilters = Omit<\n Mutable<QueryOf<'listPrompts'>>,\n 'tag' | 'status' | 'limit'\n> & { tag?: string | string[] };\nexport type PromptListQuery = Omit<Mutable<QueryOf<'listPrompts'>>, 'tag'> & PromptListFilters;\nexport type PromptCreateRequest = Mutable<Body<'createPrompt'>>;\nexport type PromptCreated = Reply<'createPrompt'>;\nexport type PromptPatch = Mutable<Body<'updatePrompt'>>;\nexport type PromptLaunched = Reply<'launchPrompt'>;\nexport type PromptDeleted = Reply<'deletePrompt'>;\nexport type PromptReport = Schema<'PromptReport'>;\nexport type PromptMatchRequest = Mutable<Body<'matchPrompt'>>;\nexport type PromptMatched = Reply<'matchPrompt'>;\nexport type PromptVerifyRequest = Mutable<Body<'verifyPrompt'>>;\nexport type PromptVerified = Reply<'verifyPrompt'>;\nexport type PromptVerifyManyRequest = Mutable<Body<'verifyPrompts'>>;\nexport type PromptVerifyManyResult = Reply<'verifyPrompts'>;\n\n/** PR-05 `POST /v1/prompts/bulk`. */\nexport type PromptBulkRequest = Mutable<Body<'bulkPrompts'>>;\nexport type PromptBulkResult = Reply<'bulkPrompts'>;\nexport type PromptHistoryEvent = Schema<'PromptEvent'>;\nexport type PromptEventKind = PromptHistoryEvent['kind'];\nexport type PromptEventList = Reply<'listPromptEvents'>;\nexport type PromptExportQuery = Omit<Mutable<QueryOf<'exportPrompts'>>, 'tag'> & PromptListFilters;\n\n/** One `event: prompt` frame of `GET /v1/prompts/stream`. */\nexport interface PromptStreamEvent {\n op: 'upsert' | 'delete';\n id: string;\n status: PromptStatus | 'deleted';\n /** Full prompt on `upsert`. */\n prompt?: Prompt;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/prompts/${encodeURIComponent(id)}${suffix}`;\n\nfunction filterQuery(q: PromptListFilters & { status?: string; limit?: number }) {\n const tag = Array.isArray(q.tag) ? q.tag.join(',') : q.tag;\n return {\n status: q.status,\n limit: q.limit,\n tag: tag || undefined,\n priority_min: q.priority_min,\n q: q.q,\n templates: q.templates,\n sort: q.sort,\n order: q.order,\n };\n}\n\nexport class Prompts {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `GET /v1/prompts?status=&limit=&tag=&priority_min=&q=&templates=&sort=&order=` — default `open`, templates\n * excluded; `due` = open and `not_before` empty or passed; several tags = AND.\n */\n list(query: PromptListQuery = {}, opts: CallOpts = {}): Promise<PromptList> {\n return this.http.json<PromptList>('/v1/prompts', {\n query: filterQuery(query),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/prompts` — idempotent on the text (`created: false` for a duplicate); `goal_key` supersedes older open ones. */\n create(body: PromptCreateRequest, opts: CallOpts = {}): Promise<PromptCreated> {\n return this.http.json<PromptCreated>('/v1/prompts', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/prompts/{id}`. */\n get(id: string, opts: CallOpts = {}): Promise<Prompt> {\n return this.http.json<Prompt>(one(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/prompts/{id}` — edit, snooze (`not_before`), close (`status: 'done' | 'dismissed'`). */\n update(id: string, body: PromptPatch, opts: CallOpts = {}): Promise<Prompt> {\n return this.http.json<Prompt>(one(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/prompts/{id}` — `{ deleted: 0 }` when the id is missing or not yours. */\n delete(id: string, opts: CallOpts = {}): Promise<PromptDeleted> {\n return this.http.json<PromptDeleted>(one(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/prompts/{id}/launch` — new shared session + `send` control on a device; the prompt becomes `launched`. */\n launch(id: string, deviceId?: string, opts: CallOpts = {}): Promise<PromptLaunched> {\n return this.http.json<PromptLaunched>(one(id, '/launch'), {\n method: 'POST',\n body: deviceId ? { device_id: deviceId } : {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/prompts/{id}/match` — the prompt was sent in a chat → `sent` (or `answered`); never downgrades. */\n match(id: string, body: PromptMatchRequest, opts: CallOpts = {}): Promise<PromptMatched> {\n return this.http.json<PromptMatched>(one(id, '/match'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/prompts/{id}/verify` — LLM report over the transcript (sent, or the matched session's stored\n * events) and an optional diff; verdict `done` → `verified`. 502 when the model call fails.\n */\n verify(id: string, body: PromptVerifyRequest = {}, opts: CallOpts = {}): Promise<PromptVerified> {\n return this.http.json<PromptVerified>(one(id, '/verify'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/prompts/verify` — transcript-only verification of up to 20 prompts, sequentially. */\n verifyMany(body: PromptVerifyManyRequest, opts: CallOpts = {}): Promise<PromptVerifyManyResult> {\n return this.http.json<PromptVerifyManyResult>('/v1/prompts/verify', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/prompts/bulk` — one action over up to 200 of your prompts → `{ updated }`. */\n bulk(body: PromptBulkRequest, opts: CallOpts = {}): Promise<PromptBulkResult> {\n return this.http.json<PromptBulkResult>('/v1/prompts/bulk', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/prompts/{id}/events` — history, newest first (max 200). */\n events(id: string, opts: CallOpts = {}): Promise<PromptEventList> {\n return this.http.json<PromptEventList>(one(id, '/events'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/prompts/{id}/instantiate` — open copy of a template (201). */\n instantiate(id: string, opts: CallOpts = {}): Promise<Prompt> {\n return this.http.json<Prompt>(one(id, '/instantiate'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/prompts/export?format=csv|md` — list filters apply (status defaults to `all`); returns the document text. */\n async exportPrompts(query: PromptExportQuery = {}, opts: CallOpts = {}): Promise<string> {\n const res = await this.http.request('/v1/prompts/export', {\n query: { ...filterQuery(query), format: query.format ?? 'csv' },\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /** `GET /v1/prompts/stream` — live `prompt` events (keepalive comments are skipped). Closed by the server after 6 h. */\n async *stream(opts: CallOpts = {}): AsyncGenerator<PromptStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/prompts/stream', { ext: opts.ext, signal: opts.signal });\n for await (const frame of frames) {\n if (frame.event !== 'prompt') continue;\n const data = frameJson<PromptStreamEvent>(frame);\n if (data) yield data;\n }\n }\n}\n","/** `/v1/schedules/*`, `/v1/schedule-runs/*`, `/v1/scheduler/*` — the codai Scheduler (ADR 0006). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Schedule = Schema<'Schedule'>;\nexport type ScheduleInput = Mutable<Schema<'ScheduleInput'>>;\nexport type ScheduleRun = Schema<'ScheduleRun'>;\nexport type SchedulerHost = Schema<'SchedulerHost'>;\nexport type SchedulePreviewRequest = Mutable<Body<'previewSchedule'>>;\nexport type SchedulePreview = Reply<'previewSchedule'>;\nexport type SchedulerHostPatch = Mutable<Body<'updateSchedulerHost'>>;\nexport type ScheduleRunResult = Mutable<Body<'reportScheduleRunResult'>>;\nexport type ScheduleClaim = Reply<'claimScheduleRun'>;\nexport type HeartbeatMonitor = Schema<'HeartbeatMonitor'>;\nexport type HeartbeatCreateRequest = Mutable<Body<'createHeartbeat'>>;\nexport type HeartbeatPatch = Mutable<Body<'updateHeartbeat'>>;\nexport type ScheduleAuditEntry = Schema<'ScheduleAuditEntry'>;\n\n/** One `event: schedule` frame of `GET /v1/schedules/stream`. */\nexport interface ScheduleStreamEvent {\n op: 'schedule' | 'run';\n id: string;\n schedule_id?: string;\n state?: string;\n device_id?: string | null;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/schedules/${encodeURIComponent(id)}${suffix}`;\nconst run = (id: string, suffix: string) => `/v1/schedule-runs/${encodeURIComponent(id)}${suffix}`;\n\n/** Host-side executor protocol: claim → heartbeat → result. Needs a device header (`device` client option). */\nexport class ScheduleExecutor {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/scheduler/claim` — the next run this device may execute, or `null` (204). Lease 60 s. */\n async claim(opts: CallOpts = {}): Promise<ScheduleClaim | null> {\n const res = await this.http.request('/v1/scheduler/claim', {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n if (res.status === 204) return null;\n return (await res.json()) as ScheduleClaim;\n }\n\n /** `POST /v1/schedule-runs/{id}/heartbeat` — extend the lease, append log. Throws 409 when the lease was lost. */\n async heartbeat(\n runId: string,\n body: { attempt: number; log?: string },\n opts: CallOpts = {},\n ): Promise<void> {\n await this.http.request(run(runId, '/heartbeat'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/schedule-runs/{id}/result` — finish the run (retries / chains are decided server-side). */\n result(runId: string, body: ScheduleRunResult, opts: CallOpts = {}): Promise<ScheduleRun> {\n return this.http.json<ScheduleRun>(run(runId, '/result'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/schedules/{id}/approve-command` — this host approves the exact shell command hash it showed the user. */\n approveCommand(\n scheduleId: string,\n commandHash: string,\n opts: CallOpts = {},\n ): Promise<Reply<'approveScheduleCommand'>> {\n return this.http.json(one(scheduleId, '/approve-command'), {\n method: 'POST',\n body: { command_hash: commandHash },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** Scheduler hosts (your devices as executors). */\nexport class SchedulerHosts {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/scheduler/hosts`. */\n async list(opts: CallOpts = {}): Promise<SchedulerHost[]> {\n const r = await this.http.json<Reply<'listSchedulerHosts'>>('/v1/scheduler/hosts', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.hosts];\n }\n\n /** `PATCH /v1/scheduler/hosts/{id}` — name, tags, kind, os, arch. */\n update(\n id: string,\n body: SchedulerHostPatch,\n opts: CallOpts = {},\n ): Promise<Reply<'updateSchedulerHost'>> {\n return this.http.json(`/v1/scheduler/hosts/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** Heartbeat monitors: dead-man switches for jobs codai does not run (`/ping/<token>`). */\nexport class Heartbeats {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/heartbeats`. */\n async list(opts: CallOpts = {}): Promise<HeartbeatMonitor[]> {\n const r = await this.http.json<Reply<'listHeartbeats'>>('/v1/heartbeats', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.heartbeats];\n }\n\n /** `POST /v1/heartbeats` — the response carries `ping_url` once. */\n create(body: HeartbeatCreateRequest, opts: CallOpts = {}): Promise<HeartbeatMonitor> {\n return this.http.json<HeartbeatMonitor>('/v1/heartbeats', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [201],\n });\n }\n\n /** `PATCH /v1/heartbeats/{id}` — name, period_s, grace_s, paused. */\n update(id: string, body: HeartbeatPatch, opts: CallOpts = {}): Promise<HeartbeatMonitor> {\n return this.http.json<HeartbeatMonitor>(`/v1/heartbeats/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/heartbeats/{id}`. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(`/v1/heartbeats/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Schedules {\n readonly hosts: SchedulerHosts;\n readonly executor: ScheduleExecutor;\n\n constructor(private readonly http: HttpClient) {\n this.hosts = new SchedulerHosts(http);\n this.executor = new ScheduleExecutor(http);\n }\n\n /** `GET /v1/schedules`. */\n async list(opts: CallOpts = {}): Promise<Schedule[]> {\n const r = await this.http.json<Reply<'listSchedules'>>('/v1/schedules', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.schedules];\n }\n\n /** `POST /v1/schedules`. */\n create(body: ScheduleInput, opts: CallOpts = {}): Promise<Schedule> {\n return this.http.json<Schedule>('/v1/schedules', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [201],\n });\n }\n\n /** `POST /v1/schedules/preview` — cron or plain words (RO/EN) → trigger + next runs + DST warning. */\n preview(body: SchedulePreviewRequest, opts: CallOpts = {}): Promise<SchedulePreview> {\n return this.http.json<SchedulePreview>('/v1/schedules/preview', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/schedules/{id}`. */\n get(id: string, opts: CallOpts = {}): Promise<Schedule> {\n return this.http.json<Schedule>(one(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/schedules/{id}` — partial; a changed shell command clears host approvals. */\n update(id: string, body: Partial<ScheduleInput>, opts: CallOpts = {}): Promise<Schedule> {\n return this.http.json<Schedule>(one(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/schedules/{id}`. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/schedules/{id}/run` — run now (policy still applies). */\n runNow(id: string, opts: CallOpts = {}): Promise<Reply<'runSchedule', 202>> {\n return this.http.json(one(id, '/run'), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [202],\n noRetry: true,\n });\n }\n\n /** `GET /v1/schedules/{id}/runs`. */\n async runs(id: string, opts: CallOpts = {}): Promise<ScheduleRun[]> {\n const r = await this.http.json<Reply<'listScheduleRuns'>>(one(id, '/runs'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.runs];\n }\n\n /** `GET /v1/schedule-runs?limit=` — recent runs of every schedule. */\n async recentRuns(limit = 50, opts: CallOpts = {}): Promise<ScheduleRun[]> {\n const r = await this.http.json<Reply<'listRecentScheduleRuns'>>('/v1/schedule-runs', {\n query: { limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.runs];\n }\n\n /** `POST /v1/schedule-runs/{id}/decision` — approve or skip a run waiting for you. */\n decide(runId: string, approve: boolean, opts: CallOpts = {}): Promise<ScheduleRun> {\n return this.http.json<ScheduleRun>(run(runId, '/decision'), {\n method: 'POST',\n body: { approve },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/schedules/pause` — vacation mode until `until` (or until resumed). */\n pause(\n body: { until?: string | null; resume_policy?: 'skip' | 'backfill' } = {},\n opts: CallOpts = {},\n ): Promise<Reply<'pauseSchedules'>> {\n return this.http.json('/v1/schedules/pause', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/schedules/resume` — `backfill: true` runs each missed schedule once. */\n resume(\n body: { backfill?: boolean } = {},\n opts: CallOpts = {},\n ): Promise<Reply<'resumeSchedules'>> {\n return this.http.json('/v1/schedules/resume', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/schedules/audit` — append-only scheduler history, newest first (optionally one schedule). */\n async audit(\n params: { schedule_id?: string; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<ScheduleAuditEntry[]> {\n const r = await this.http.json<Reply<'listScheduleAudit'>>('/v1/schedules/audit', {\n query: { schedule_id: params.schedule_id, limit: params.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.audit];\n }\n\n /** `GET /v1/schedules/templates`. */\n templates(opts: CallOpts = {}): Promise<Reply<'listScheduleTemplates'>> {\n return this.http.json('/v1/schedules/templates', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/schedules/templates` — canonical prompt + draft create body (no write). */\n renderTemplate(\n template: string,\n params: Record<string, unknown> = {},\n opts: CallOpts = {},\n ): Promise<Reply<'renderScheduleTemplate'>> {\n return this.http.json('/v1/schedules/templates', {\n method: 'POST',\n body: { template, params },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/schedules/stream` — live `schedule` events (keepalives skipped). */\n async *stream(opts: CallOpts = {}): AsyncGenerator<ScheduleStreamEvent, void, undefined> {\n for await (const frame of this.http.sse('/v1/schedules/stream', {\n ext: opts.ext,\n signal: opts.signal,\n })) {\n if (frame.event !== 'schedule') continue;\n const data = frameJson<ScheduleStreamEvent>(frame);\n if (data) yield data;\n }\n }\n}\n","/** `/v1/lists/*`, `/v1/share` — lists and the share-sheet entry point. */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type List = Schema<'List'>;\nexport type ListItem = Schema<'ListItem'>;\nexport type ListCreateInput = Mutable<Schema<'ListCreateInput'>>;\nexport type ListPatchInput = Mutable<Schema<'ListPatchInput'>>;\nexport type ListItemInput = Mutable<Schema<'ListItemInput'>>;\nexport type ListItemPatchInput = Mutable<Schema<'ListItemPatchInput'>>;\nexport type ListItemCreated = Schema<'ListItemCreated'>;\nexport type ListOk = Schema<'ListOk'>;\nexport type ShareRequest = Mutable<Body<'shareToList'>>;\nexport type ShareResponse = Schema<'ShareResponse'>;\n\n/** One `event: list` frame of `GET /v1/lists/stream`. */\nexport interface ListStreamEvent {\n op: 'lists' | 'item' | 'item_delete';\n listId?: string;\n itemId?: string;\n}\n\n/** An item image (`GET /v1/lists/items/{itemId}/image`). */\nexport interface ListItemImage {\n bytes: Uint8Array;\n contentType: string;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/lists/${encodeURIComponent(id)}${suffix}`;\nconst item = (id: string, suffix = '') => `/v1/lists/items/${encodeURIComponent(id)}${suffix}`;\n\nexport class Lists {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/lists` — share-sheet order; presets are created on the first call. */\n async list(params: { archived?: boolean } = {}, opts: CallOpts = {}): Promise<List[]> {\n const r = await this.http.json<Reply<'listLists'>>('/v1/lists', {\n query: { archived: params.archived ? '1' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.lists];\n }\n\n /** `POST /v1/lists` — a custom list. */\n async create(body: ListCreateInput, opts: CallOpts = {}): Promise<List> {\n const r = await this.http.json<Reply<'createList', 201>>('/v1/lists', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [201],\n });\n return r.list;\n }\n\n /** `PATCH /v1/lists/order` — the order of your lists (and of the share-sheet targets). */\n reorder(ids: string[], opts: CallOpts = {}): Promise<ListOk> {\n return this.http.json<ListOk>('/v1/lists/order', {\n method: 'PATCH',\n body: { ids },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/lists/stream` — live `list` events (keepalives skipped). */\n async *stream(opts: CallOpts = {}): AsyncGenerator<ListStreamEvent, void, undefined> {\n for await (const frame of this.http.sse('/v1/lists/stream', {\n ext: opts.ext,\n signal: opts.signal,\n })) {\n if (frame.event !== 'list') continue;\n const data = frameJson<ListStreamEvent>(frame);\n if (data) yield data;\n }\n }\n\n /** `PATCH /v1/lists/{id}` — name, icon, color, share-sheet visibility, price watch, archived. */\n async update(id: string, patch: ListPatchInput, opts: CallOpts = {}): Promise<List> {\n const r = await this.http.json<Reply<'updateList'>>(one(id), {\n method: 'PATCH',\n body: patch,\n ext: opts.ext,\n signal: opts.signal,\n });\n return r.list;\n }\n\n /** `DELETE /v1/lists/{id}` — custom lists only (presets → 409 `preset_list`). */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/lists/{id}/items` — pinned first, then newest; done items only with `done: true`. */\n async items(\n id: string,\n params: { done?: boolean; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<ListItem[]> {\n const r = await this.http.json<Reply<'listListItems'>>(one(id, '/items'), {\n query: { done: params.done ? '1' : undefined, limit: params.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.items];\n }\n\n /** `POST /v1/lists/{id}/items` — 201 created, or 200 with the existing item (`created: false`). */\n add(id: string, body: ListItemInput, opts: CallOpts = {}): Promise<ListItemCreated> {\n return this.http.json<ListItemCreated>(one(id, '/items'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [200, 201],\n });\n }\n\n /** `PATCH /v1/lists/items/{itemId}` — title, body, done, pinned, reminder; `list_id` moves it. */\n async updateItem(\n itemId: string,\n patch: ListItemPatchInput,\n opts: CallOpts = {},\n ): Promise<ListItem> {\n const r = await this.http.json<Reply<'updateListItem'>>(item(itemId), {\n method: 'PATCH',\n body: patch,\n ext: opts.ext,\n signal: opts.signal,\n });\n return r.item;\n }\n\n /** `DELETE /v1/lists/items/{itemId}` — also deletes its uploaded media. */\n async deleteItem(itemId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(item(itemId), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/lists/items/{itemId}/image` — the uploaded image or the unfurled preview image. */\n async image(itemId: string, opts: CallOpts = {}): Promise<ListItemImage> {\n const res = await this.http.request(item(itemId, '/image'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n contentType: res.headers.get('content-type') ?? 'application/octet-stream',\n };\n }\n\n /** `GET /v1/lists/{id}/export.md` — the whole list as GitHub-flavoured Markdown. */\n async exportMarkdown(id: string, opts: CallOpts = {}): Promise<string> {\n const res = await this.http.request(one(id, '/export.md'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /** `POST /v1/share` — share-sheet entry point (`list_id`, `preset`, or auto → Inbox + suggestion). */\n share(body: ShareRequest, opts: CallOpts = {}): Promise<ShareResponse> {\n return this.http.json<ShareResponse>('/v1/share', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [200, 201],\n });\n }\n}\n","/** `/v1/memory` — your persistent memory (same store as the MCP memory tools). */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type MemoryItem = Schema<'MemoryItem'>;\nexport type MemoryHit = Schema<'MemoryHit'>;\nexport type MemoryTier = MemoryItem['tier'];\nexport type MemoryList = Reply<'listMemories'>;\nexport type MemorySearchResult = Reply<'searchMemories'>;\nexport type MemoryListQuery = Mutable<QueryOf<'listMemories'>>;\nexport type MemorySearchQuery = Mutable<QueryOf<'searchMemories'>>;\nexport type MemoryCreateInput = Mutable<Body<'createMemory'>>;\nexport type MemoryCreated = Reply<'createMemory', 201>;\nexport type MemoryDeleted = Reply<'deleteMemory'>;\nexport type MemoryDeletedAll = Reply<'deleteAllMemories'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Memory {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/memory` — newest first; `limit` 1–100 (20), optional `tier`. Not metered. */\n list(query: MemoryListQuery = {}, opts: CallOpts = {}): Promise<MemoryList> {\n return this.http.json<MemoryList>('/v1/memory', {\n query: { tier: query.tier, limit: query.limit, offset: query.offset },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/memory/search` — semantic recall, most relevant first; `limit` 1–10 (5). One embedding. */\n search(query: MemorySearchQuery, opts: CallOpts = {}): Promise<MemorySearchResult> {\n return this.http.json<MemorySearchResult>('/v1/memory/search', {\n query: { q: query.q, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/memory` — store one semantic memory (`content` ≤ 4000 chars, `importance` 0–1, default 0.6). */\n create(input: MemoryCreateInput, opts: CallOpts = {}): Promise<MemoryCreated> {\n return this.http.json<MemoryCreated>('/v1/memory', {\n method: 'POST',\n body: input,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/memory/{id}` — 404 when the id is unknown or not yours. */\n delete(id: string, opts: CallOpts = {}): Promise<MemoryDeleted> {\n return this.http.json<MemoryDeleted>(`/v1/memory/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `DELETE /v1/memory?confirm=all` — erase EVERY memory of your account (all tiers). Irreversible; returns the\n * counts per tier and the total. Allowed on every plan.\n */\n deleteAll(opts: CallOpts = {}): Promise<MemoryDeletedAll> {\n return this.http.json<MemoryDeletedAll>('/v1/memory', {\n method: 'DELETE',\n query: { confirm: 'all' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/sandboxes` — agent sandboxes: isolated gVisor containers with a persistent `/workspace`, no network\n * by default, artifacts from `/workspace/out` as scanned, signed links. Backend `v2` (default) = long-lived\n * GKE pod with pause/resume, fork, a persistent kernel and preview URLs; `v1` = Cloud Run, on request.\n */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Sandbox = Schema<'Sandbox'>;\nexport type SandboxEgress = Mutable<Schema<'SandboxEgress'>>;\nexport type SandboxCreateInput = Mutable<Schema<'SandboxCreate'>>;\nexport type SandboxExecInput = Mutable<Schema<'SandboxExecRequest'>>;\nexport type SandboxRunInput = Mutable<Schema<'SandboxRunRequest'>>;\nexport type SandboxExecResult = Schema<'SandboxExecResult'>;\nexport type SandboxExecEvent = Schema<'SandboxExecEvent'>;\nexport type SandboxArtifact = Schema<'SandboxArtifact'>;\nexport type SandboxReceipt = Schema<'SandboxReceipt'>;\nexport type SandboxInput = Mutable<Schema<'SandboxInput'>>;\nexport type SandboxList = Reply<'listSandboxes'>;\nexport type SandboxArtifactList = Reply<'listSandboxArtifacts'>;\nexport type SandboxFileList = Reply<'listSandboxFiles'>;\nexport type SandboxFileWritten = Reply<'putSandboxFile'>;\nexport type SandboxSnapshot = Reply<'snapshotSandbox'>;\nexport type SandboxStatus = Sandbox['status'];\nexport type SandboxSnapshotInput = Mutable<NonNullable<Body<'snapshotSandbox'>>>;\nexport type SandboxBackend = NonNullable<SandboxCreateInput['backend']>;\nexport type SandboxTemplate = NonNullable<SandboxCreateInput['template']>;\nexport type SandboxRunCodeResult = Schema<'SandboxRunCodeResult'>;\nexport type SandboxResumed = Reply<'resumeSandbox'>;\nexport type SandboxForkResult = Reply<'forkSandbox'>;\nexport type SandboxPreview = Reply<'previewSandbox'>;\n\n/** Input of {@link Sandboxes.runCode}. */\nexport interface SandboxRunCodeInput {\n code: string;\n /** Seconds before the kernel is restarted (1–900, server default 60). */\n timeoutSeconds?: number;\n}\n\n/** Input of {@link Sandboxes.fork}. */\nexport interface SandboxForkInput {\n /** Children to start (1–5). */\n count: number;\n /** Lifetime of each child; default what is left of the parent. */\n ttlSeconds?: number;\n}\n\n/** Input of {@link Sandboxes.preview}. */\nexport interface SandboxPreviewInput {\n /** Port inside the sandbox (1024–65535, not 8080). */\n port: number;\n /** URL validity in seconds (60–3600, server default 900). */\n ttlSeconds?: number;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\ntype IdemOpts = CallOpts & { idempotencyKey?: string };\n\n/** A downloaded workspace file: raw bytes plus the server's SHA-256. */\nexport interface SandboxFile {\n bytes: Uint8Array;\n sha256: string | null;\n contentType: string | null;\n}\n\nconst base = (id: string) => `/v1/sandboxes/${encodeURIComponent(id)}`;\n/** Encode each segment of a workspace path, keeping the slashes. */\nconst filePath = (p: string) =>\n p\n .replace(/^\\/+/, '')\n .split('/')\n .map((s) => encodeURIComponent(s))\n .join('/');\nconst idem = (key?: string) => (key ? { 'Idempotency-Key': key } : undefined);\n\nexport class SandboxFiles {\n constructor(private readonly http: HttpClient) {}\n\n /** `PUT /v1/sandboxes/{id}/files/{path}` — write raw bytes (≤ 100 MB) to `/workspace/<path>`. */\n put(\n id: string,\n path: string,\n content: string | Uint8Array | ArrayBuffer | Blob,\n opts: CallOpts = {},\n ): Promise<SandboxFileWritten> {\n const body = (typeof content === 'string'\n ? new TextEncoder().encode(content)\n : content) as unknown as BodyInit;\n return this.http.json<SandboxFileWritten>(`${base(id)}/files/${filePath(path)}`, {\n method: 'PUT',\n rawBody: body,\n headers: { 'Content-Type': 'application/octet-stream' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/sandboxes/{id}/files/{path}` — raw bytes of `/workspace/<path>` (`sha256` from `x-sha256`). */\n async get(id: string, path: string, opts: CallOpts = {}): Promise<SandboxFile> {\n const res = await this.http.request(`${base(id)}/files/${filePath(path)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n sha256: res.headers.get('x-sha256'),\n contentType: res.headers.get('content-type'),\n };\n }\n\n /** `GET /v1/sandboxes/{id}/files?path=` — entries under a directory (default the workspace root). */\n list(id: string, path?: string, opts: CallOpts = {}): Promise<SandboxFileList> {\n return this.http.json<SandboxFileList>(`${base(id)}/files`, {\n query: { path },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Sandboxes {\n readonly files: SandboxFiles;\n\n constructor(private readonly http: HttpClient) {\n this.files = new SandboxFiles(http);\n }\n\n /**\n * `POST /v1/sandboxes` — start a sandbox (`ttl_seconds` default 3600, max 86400 on v1 / 604800 on v2;\n * `egress` none by default, or a `pypi`/`npm` preset / allowlist on both backends).\n * `backend` defaults to `'v2'`: a long-lived pod with memory snapshots, Node 24 + npm, `template`\n * `codai-base` | `brivio-acte` | `desktop`; its reply may carry `restored`. When `backend` is omitted and v2\n * is unavailable for the key the gateway falls back to `'v1'` (check `backend` on the reply).\n * Errors: 429 `sandbox_concurrency_limit` (3 per key, 5 running v2 per user), 503 `sandbox_capacity` (retry).\n */\n create(input: SandboxCreateInput = {}, opts: CallOpts = {}): Promise<Sandbox> {\n return this.http.json<Sandbox>('/v1/sandboxes', {\n method: 'POST',\n body: input,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/sandboxes` — your sandboxes, newest first, optionally one `status`. */\n list(query: { status?: SandboxStatus } = {}, opts: CallOpts = {}): Promise<SandboxList> {\n return this.http.json<SandboxList>('/v1/sandboxes', {\n query: { status: query.status },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/sandboxes/{id}` */\n retrieve(id: string, opts: CallOpts = {}): Promise<Sandbox> {\n return this.http.json<Sandbox>(base(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/exec` — run one command and wait for it (≤ 900 s). Use\n * {@link execStream} to receive stdout / stderr as they are produced.\n */\n exec(id: string, input: SandboxExecInput, opts: IdemOpts = {}): Promise<SandboxExecResult> {\n return this.http.json<SandboxExecResult>(`${base(id)}/exec`, {\n method: 'POST',\n body: input,\n headers: idem(opts.idempotencyKey),\n timeoutMs: execTimeoutMs(input.timeout_seconds),\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/exec` with `Accept: text/event-stream` — yields `start`, `stdout`,\n * `stderr`, `truncated` and finally `exit` (or `error`) events.\n */\n async *execStream(\n id: string,\n input: SandboxExecInput,\n opts: IdemOpts = {},\n ): AsyncGenerator<SandboxExecEvent, void, undefined> {\n const frames = this.http.sse(`${base(id)}/exec`, {\n method: 'POST',\n body: input,\n headers: { Accept: 'text/event-stream', ...idem(opts.idempotencyKey) },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<SandboxExecEvent>(frame);\n if (!data || typeof data !== 'object' || !('type' in data)) continue;\n yield data;\n if (data.type === 'exit' || data.type === 'error') return;\n }\n }\n\n /** `GET /v1/sandboxes/{id}/artifacts` — collect `/workspace/out` (scanned, signed 1 h links). */\n artifacts(id: string, opts: CallOpts = {}): Promise<SandboxArtifactList> {\n return this.http.json<SandboxArtifactList>(`${base(id)}/artifacts`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/snapshot` (v1 only; v2 answers 409 `not_supported_on_v2`) — store a compressed copy of the workspace. */\n snapshot(\n id: string,\n input: SandboxSnapshotInput = {},\n opts: CallOpts = {},\n ): Promise<SandboxSnapshot> {\n return this.http.json<SandboxSnapshot>(`${base(id)}/snapshot`, {\n method: 'POST',\n body: input,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/run_code` (v2) — run Python in the persistent kernel; globals survive between\n * calls, pause/resume and forks. The last expression comes back as `result`.\n */\n runCode(id: string, input: SandboxRunCodeInput, opts: CallOpts = {}): Promise<SandboxRunCodeResult> {\n return this.http.json<SandboxRunCodeResult>(`${base(id)}/run_code`, {\n method: 'POST',\n body: {\n code: input.code,\n ...(input.timeoutSeconds !== undefined ? { timeout_seconds: input.timeoutSeconds } : {}),\n },\n timeoutMs: execTimeoutMs(input.timeoutSeconds),\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/kernel/reset` (v2) — restart the kernel; globals are lost, files kept. */\n async resetKernel(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.json<{ ok: boolean }>(`${base(id)}/kernel/reset`, {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/pause` (v2) — memory snapshot, then stop the pod (status `paused`).\n * At most 10 paused v2 sandboxes per user (429 `sandbox_paused_limit`).\n */\n pause(id: string, opts: CallOpts = {}): Promise<Sandbox> {\n return this.http.json<Sandbox>(`${base(id)}/pause`, {\n method: 'POST',\n timeoutMs: LIFECYCLE_TIMEOUT_MS,\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/resume` (v2) — restore a paused sandbox; `restored: false` = cold start. */\n resume(id: string, opts: CallOpts = {}): Promise<SandboxResumed> {\n return this.http.json<SandboxResumed>(`${base(id)}/resume`, {\n method: 'POST',\n timeoutMs: LIFECYCLE_TIMEOUT_MS,\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/fork` (v2) — start 1–5 copies of a running sandbox from a memory snapshot. */\n fork(id: string, input: SandboxForkInput, opts: CallOpts = {}): Promise<SandboxForkResult> {\n return this.http.json<SandboxForkResult>(`${base(id)}/fork`, {\n method: 'POST',\n body: {\n count: input.count,\n ...(input.ttlSeconds !== undefined ? { ttl_seconds: input.ttlSeconds } : {}),\n },\n timeoutMs: LIFECYCLE_TIMEOUT_MS,\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/preview` (v2) — signed HTTPS URL on `*.sbx.codai.ro` for a port (≤ 1 h). */\n preview(id: string, input: SandboxPreviewInput, opts: CallOpts = {}): Promise<SandboxPreview> {\n return this.http.json<SandboxPreview>(`${base(id)}/preview`, {\n method: 'POST',\n body: {\n port: input.port,\n ...(input.ttlSeconds !== undefined ? { ttl_seconds: input.ttlSeconds } : {}),\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sandboxes/{id}` — destroy the sandbox and its workspace (204). */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(base(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `POST /v1/sandboxes/run` — one shot: create, write `inputs` under `/workspace/in`, run,\n * collect artifacts, destroy. Pass `idempotencyKey` to make retries safe.\n */\n run(input: SandboxRunInput, opts: IdemOpts = {}): Promise<SandboxExecResult> {\n return this.http.json<SandboxExecResult>('/v1/sandboxes/run', {\n method: 'POST',\n body: input,\n headers: idem(opts.idempotencyKey),\n timeoutMs: execTimeoutMs(input.timeout_seconds),\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** Pause / resume / fork wait for a snapshot or a pod start (server caps: 180 s snapshot, 240 s start). */\nconst LIFECYCLE_TIMEOUT_MS = 8 * 60 * 1000;\n\n/** Client timeout for a blocking exec: the server limit plus a margin for restore and upload. */\nfunction execTimeoutMs(timeoutSeconds: number | undefined): number {\n return ((timeoutSeconds ?? 120) + 60) * 1000;\n}\n","/**\n * `/v1/transcripts/*` + `/v1/transcript-folders` + `/v1/transcript-vocabulary` + tus `/v1/uploads` — voice\n * recordings → diarized RO/EN transcripts → insights (summary, key points, actions, suggested agent prompts).\n * Feature-flagged per account (404 until enabled). Bodies are snake_case.\n */\nimport { CodaiError, type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Transcript = Schema<'Transcript'>;\nexport type TranscriptDetail = Schema<'TranscriptDetail'>;\nexport type TranscriptStatus = Schema<'TranscriptStatus'>;\nexport type TranscriptFolder = Schema<'TranscriptFolder'>;\nexport type TranscriptList = Reply<'listTranscripts'>;\nexport type TranscriptListQuery = Mutable<QueryOf<'listTranscripts'>>;\nexport type TranscriptCreateRequest = Mutable<Body<'createTranscript'>>;\nexport type TranscriptPatch = Mutable<Body<'updateTranscript'>>;\nexport type TranscriptFinalizeRequest = Mutable<Body<'finalizeTranscript'>>;\nexport type TranscriptUsage = Reply<'getTranscriptUsage'>;\nexport type TranscriptSearchQuery = Mutable<QueryOf<'searchTranscripts'>>;\nexport type TranscriptSearchResult = Reply<'searchTranscripts'>;\nexport type TranscriptAskRequest = Mutable<Body<'askTranscripts'>>;\nexport type TranscriptAskResult = Reply<'askTranscripts'>;\nexport type TranscriptAudio = Reply<'getTranscriptAudio'>;\nexport type TranscriptBookmarkRequest = Mutable<Body<'addTranscriptBookmark'>>;\nexport type TranscriptSpeakerPatch = Mutable<Body<'updateTranscriptSpeaker'>>;\nexport type TranscriptExportFormat = 'md' | 'txt' | 'srt' | 'vtt' | 'json' | 'pdf' | 'docx';\nexport type TranscriptBinaryExportFormat = 'pdf' | 'docx';\nexport type TranscriptShareCreateRequest = Mutable<Schema<'TranscriptShareCreateRequest'>>;\nexport type TranscriptShareCreated = Schema<'TranscriptShareCreated'>;\nexport type TranscriptShare = Schema<'TranscriptShare'>;\nexport type PublicTranscript = Schema<'PublicTranscript'>;\n\n/** A text export (`md` / `txt` / `srt` / `vtt` / `json`). */\nexport interface TranscriptTextExport {\n text: string;\n filename: string | null;\n contentType: string | null;\n}\n\n/** A binary export (`pdf` / `docx`): raw bytes, save them as-is. */\nexport interface TranscriptBinaryExport {\n bytes: Uint8Array;\n filename: string | null;\n contentType: string | null;\n}\n\n/** One `event: transcript` frame of `GET /v1/transcripts/stream`. */\nexport interface TranscriptStreamEvent {\n op: 'upsert' | 'delete' | 'progress' | 'live';\n id: string;\n status?: TranscriptStatus;\n /** 0..1 on `progress`. */\n progress?: number;\n title?: string;\n /** `live`: rolling caption from the recording device (committed tail + partial); never persisted. */\n finals?: string;\n partial?: string;\n /** `live`: 0..1 input level. */\n level?: number;\n /** `live`: phone | wear | desktop. */\n device?: string;\n elapsed_ms?: number;\n paused?: boolean;\n}\n\n/** Body of `POST /v1/transcripts/{id}/live` (the recording device's caption, ~1/s). */\nexport interface TranscriptLiveCaption {\n finals?: string;\n partial?: string;\n level?: number;\n device: 'phone' | 'wear' | 'desktop';\n elapsed_ms: number;\n paused?: boolean;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/transcripts/${encodeURIComponent(id)}${suffix}`;\n\nconst TUS = { 'Tus-Resumable': '1.0.0' } as const;\nexport const TUS_CHUNK_BYTES = 8 * 1024 * 1024;\n\n/** base64 of a UTF-8 string, without Buffer (browser + node). */\nfunction b64(s: string): string {\n const bytes = new TextEncoder().encode(s);\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin);\n}\n\n/** Last path segment of a tus `Location` (absolute or relative). Exported for tests. */\nexport function uploadIdFromLocation(location: string): string {\n const path = location.replace(/[?#].*$/, '').replace(/\\/+$/, '');\n const id = decodeURIComponent(path.slice(path.lastIndexOf('/') + 1));\n if (!id) throw new CodaiError(`tus: no upload id in Location ${location}`, 0, null);\n return id;\n}\n\nexport interface UploadAudioOptions extends CallOpts {\n track?: 'mic' | 'system' | 'mixed';\n transcriptId?: string;\n durationMs?: number;\n chunkSize?: number;\n /** Resume a previous upload (its id) instead of creating one. */\n uploadId?: string;\n onProgress?: (sent: number, total: number) => void;\n}\n\nclass TranscriptFolders {\n constructor(private readonly http: HttpClient) {}\n /** `GET /v1/transcript-folders`. */\n list(opts: CallOpts = {}): Promise<Reply<'listTranscriptFolders'>> {\n return this.http.json('/v1/transcript-folders', { ext: opts.ext, signal: opts.signal });\n }\n /** `POST /v1/transcript-folders` — upsert on `name`. */\n create(\n body: Mutable<Body<'createTranscriptFolder'>>,\n opts: CallOpts = {},\n ): Promise<TranscriptFolder> {\n return this.http.json('/v1/transcript-folders', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n /** `PATCH /v1/transcript-folders/{id}`. */\n update(\n id: string,\n body: Mutable<Body<'updateTranscriptFolder'>>,\n opts: CallOpts = {},\n ): Promise<TranscriptFolder> {\n return this.http.json(`/v1/transcript-folders/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n /** `DELETE /v1/transcript-folders/{id}` — transcripts stay, `folder_id` cleared. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(`/v1/transcript-folders/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nclass TranscriptVocabulary {\n constructor(private readonly http: HttpClient) {}\n /** `GET /v1/transcript-vocabulary`. */\n get(opts: CallOpts = {}): Promise<Reply<'getTranscriptVocabulary'>> {\n return this.http.json('/v1/transcript-vocabulary', { ext: opts.ext, signal: opts.signal });\n }\n /** `PUT /v1/transcript-vocabulary` — replaces the whole list. */\n put(terms: string[], opts: CallOpts = {}): Promise<Reply<'putTranscriptVocabulary'>> {\n return this.http.json('/v1/transcript-vocabulary', {\n method: 'PUT',\n body: { terms },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nclass TranscriptShares {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/transcripts/{id}/shares` — read-only public link (`https://hub.codai.ro/t/<token>`). The token/url\n * are returned ONCE (only a hash is stored). Omit `expiresInDays` for a link that never expires.\n */\n create(\n id: string,\n body: TranscriptShareCreateRequest = {},\n opts: CallOpts = {},\n ): Promise<TranscriptShareCreated> {\n return this.http.json<TranscriptShareCreated>(one(id, '/shares'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/transcripts/{id}/shares` — active links; `url` is always null (token not recoverable). */\n async list(id: string, opts: CallOpts = {}): Promise<TranscriptShare[]> {\n const r = await this.http.json<{ data: TranscriptShare[] }>(one(id, '/shares'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return r.data;\n }\n\n /** `DELETE /v1/transcripts/{id}/shares/{shareId}` — the public URL answers 404 from then on. */\n async revoke(id: string, shareId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id, `/shares/${encodeURIComponent(shareId)}`), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nclass Uploads {\n constructor(private readonly http: HttpClient) {}\n\n /** `OPTIONS /v1/uploads` — tus capabilities (headers). */\n async capabilities(\n opts: CallOpts = {},\n ): Promise<{ version: string | null; extensions: string[]; maxSize: number | null }> {\n const res = await this.http.request('/v1/uploads', {\n method: 'OPTIONS',\n headers: TUS,\n ext: opts.ext,\n signal: opts.signal,\n });\n const max = res.headers.get('tus-max-size');\n return {\n version: res.headers.get('tus-version'),\n extensions: (res.headers.get('tus-extension') ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean),\n maxSize: max ? Number(max) : null,\n };\n }\n\n /** `POST /v1/uploads` — tus creation; returns the upload id. */\n async create(\n length: number | null,\n metadata: Record<string, string>,\n opts: CallOpts = {},\n ): Promise<string> {\n const md = Object.entries(metadata)\n .map(([k, v]) => `${k} ${b64(v)}`)\n .join(',');\n const res = await this.http.request('/v1/uploads', {\n method: 'POST',\n headers: {\n ...TUS,\n ...(length === null ? { 'Upload-Defer-Length': '1' } : { 'Upload-Length': String(length) }),\n ...(md ? { 'Upload-Metadata': md } : {}),\n },\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n const loc = res.headers.get('location');\n if (!loc) throw new CodaiError('tus: create response has no Location header', res.status, null);\n return uploadIdFromLocation(loc);\n }\n\n /** tus HEAD `/v1/uploads/{id}` — bytes the server holds (resume point). */\n async offset(\n id: string,\n opts: CallOpts = {},\n ): Promise<{ offset: number; length: number | null }> {\n const res = await this.http.request(`/v1/uploads/${encodeURIComponent(id)}`, {\n method: 'HEAD',\n headers: TUS,\n ext: opts.ext,\n signal: opts.signal,\n });\n const len = res.headers.get('upload-length');\n return {\n offset: Number(res.headers.get('upload-offset') ?? 0),\n length: len ? Number(len) : null,\n };\n }\n\n /** tus PATCH `/v1/uploads/{id}` — append one chunk at `offset`; returns the new offset. */\n async append(\n id: string,\n offset: number,\n chunk: Uint8Array,\n opts: CallOpts & { length?: number } = {},\n ): Promise<number> {\n const res = await this.http.request(`/v1/uploads/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: {\n ...TUS,\n 'Upload-Offset': String(offset),\n 'Content-Type': 'application/offset+octet-stream',\n ...(opts.length !== undefined ? { 'Upload-Length': String(opts.length) } : {}),\n },\n rawBody: chunk as unknown as BodyInit,\n ext: opts.ext,\n signal: opts.signal,\n });\n const next = Number(res.headers.get('upload-offset') ?? -1);\n if (!(next > offset))\n throw new CodaiError(\n `tus: server offset ${next} did not advance past ${offset}`,\n res.status,\n null,\n );\n return next;\n }\n}\n\nexport class Transcripts {\n readonly folders: TranscriptFolders;\n readonly vocabulary: TranscriptVocabulary;\n readonly uploads: Uploads;\n readonly shares: TranscriptShares;\n\n constructor(private readonly http: HttpClient) {\n this.folders = new TranscriptFolders(http);\n this.vocabulary = new TranscriptVocabulary(http);\n this.uploads = new Uploads(http);\n this.shares = new TranscriptShares(http);\n }\n\n /** `GET /v1/transcripts` — pinned first, newest next; page with `next_cursor`. */\n list(query: TranscriptListQuery = {}, opts: CallOpts = {}): Promise<TranscriptList> {\n return this.http.json<TranscriptList>('/v1/transcripts', {\n query: query as Record<string, string | number | boolean | undefined>,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/transcripts` — status `recording`; idempotent on `client_id`. */\n create(body: TranscriptCreateRequest, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>('/v1/transcripts', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/{id}` — speakers, utterances (word timings), bookmarks, latest insights. */\n get(id: string, opts: CallOpts = {}): Promise<TranscriptDetail> {\n return this.http.json<TranscriptDetail>(one(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/transcripts/{id}` — setting `title` locks it. */\n update(id: string, body: TranscriptPatch, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/transcripts/{id}` — row + audio objects. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/transcripts/{id}/finalize` — attach tus uploads + bookmarks → `queued`. */\n finalize(id: string, body: TranscriptFinalizeRequest, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id, '/finalize'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [202],\n });\n }\n\n /** `POST /v1/transcripts/{id}/retranscribe`. */\n retranscribe(id: string, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id, '/retranscribe'), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/transcripts/{id}/reanalyze` — new insights version. */\n reanalyze(id: string, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id, '/reanalyze'), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * `POST /v1/transcripts/{id}/live` — publish the recording device's live caption to every viewer of the transcript\n * (`stream()` / hub live view). Only while `recording`; frames closer than 250 ms are dropped. Returns nothing (204).\n */\n async publishLive(id: string, body: TranscriptLiveCaption, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id, '/live'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/transcripts/{id}/bookmarks`. */\n addBookmark(\n id: string,\n body: TranscriptBookmarkRequest,\n opts: CallOpts = {},\n ): Promise<Reply<'addTranscriptBookmark', 201>> {\n return this.http.json(one(id, '/bookmarks'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/transcripts/{id}/speakers/{label}` — name a speaker / mark yourself (`is_owner`). */\n renameSpeaker(\n id: string,\n label: string,\n body: TranscriptSpeakerPatch,\n opts: CallOpts = {},\n ): Promise<Reply<'updateTranscriptSpeaker'>> {\n return this.http.json(one(id, `/speakers/${encodeURIComponent(label)}`), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/transcripts/{id}/utterances/{seq}` — correct one utterance. */\n editUtterance(\n id: string,\n seq: number,\n text: string,\n opts: CallOpts = {},\n ): Promise<Reply<'updateTranscriptUtterance'>> {\n return this.http.json(one(id, `/utterances/${seq}`), {\n method: 'PATCH',\n body: { text },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/{id}/audio` — signed playback URLs per track (empty after the 30-day retention). */\n audio(id: string, opts: CallOpts = {}): Promise<TranscriptAudio> {\n return this.http.json<TranscriptAudio>(one(id, '/audio'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/{id}/export?format=` — text for md/txt/srt/vtt/json, bytes for pdf/docx. */\n export(\n id: string,\n format: TranscriptBinaryExportFormat,\n opts?: CallOpts,\n ): Promise<TranscriptBinaryExport>;\n export(\n id: string,\n format?: Exclude<TranscriptExportFormat, TranscriptBinaryExportFormat>,\n opts?: CallOpts,\n ): Promise<TranscriptTextExport>;\n async export(\n id: string,\n format: TranscriptExportFormat = 'md',\n opts: CallOpts = {},\n ): Promise<TranscriptTextExport | TranscriptBinaryExport> {\n const res = await this.http.request(one(id, '/export'), {\n query: { format },\n ext: opts.ext,\n signal: opts.signal,\n });\n const cd = res.headers.get('content-disposition') ?? '';\n const m = /filename\\*=UTF-8''([^;]+)/i.exec(cd);\n const filename = m ? decodeURIComponent(m[1]!) : null;\n const contentType = res.headers.get('content-type');\n if (format === 'pdf' || format === 'docx')\n return { bytes: new Uint8Array(await res.arrayBuffer()), filename, contentType };\n return { text: await res.text(), filename, contentType };\n }\n\n /**\n * `GET /v1/public/transcripts/{token}` — the read-only view behind a share link (no API key needed; the\n * client's key is sent but ignored). 404 for unknown / expired / revoked links.\n */\n publicView(token: string, opts: CallOpts = {}): Promise<PublicTranscript> {\n return this.http.json<PublicTranscript>(`/v1/public/transcripts/${encodeURIComponent(token)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/transcripts/{id}/prompts/{index}/accept` — suggested agent prompt → pending prompt. */\n acceptPrompt(\n id: string,\n index: number,\n opts: CallOpts = {},\n ): Promise<Reply<'acceptTranscriptPrompt', 201>> {\n return this.http.json(one(id, `/prompts/${index}/accept`), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/transcripts/usage` — this month's allowance. */\n usage(opts: CallOpts = {}): Promise<TranscriptUsage> {\n return this.http.json<TranscriptUsage>('/v1/transcripts/usage', {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/search` — full-text (+ semantic in `hybrid`). */\n search(query: TranscriptSearchQuery, opts: CallOpts = {}): Promise<TranscriptSearchResult> {\n return this.http.json<TranscriptSearchResult>('/v1/transcripts/search', {\n query: query as Record<string, string | number | undefined>,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/transcripts/ask` — answer across your recordings with `[n]` citations. */\n ask(body: TranscriptAskRequest, opts: CallOpts = {}): Promise<TranscriptAskResult> {\n return this.http.json<TranscriptAskResult>('/v1/transcripts/ask', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/transcripts/stream` — live `transcript` events (keepalives skipped). Server closes after 55 min. */\n async *stream(opts: CallOpts = {}): AsyncGenerator<TranscriptStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/transcripts/stream', { ext: opts.ext, signal: opts.signal });\n for await (const frame of frames) {\n if (frame.event !== 'transcript') continue;\n const data = frameJson<TranscriptStreamEvent>(frame);\n if (data) yield data;\n }\n }\n\n /**\n * Upload one audio track with tus 1.0 (resumable): creates the upload (or resumes `uploadId` from the server's\n * offset), PATCHes ≤ 8 MB chunks and returns the upload id to pass to `finalize`.\n */\n async uploadAudio(\n data: Uint8Array | ArrayBuffer | Blob,\n opts: UploadAudioOptions = {},\n ): Promise<string> {\n const bytes =\n data instanceof Uint8Array\n ? data\n : data instanceof ArrayBuffer\n ? new Uint8Array(data)\n : new Uint8Array(await data.arrayBuffer());\n const total = bytes.byteLength;\n const chunk = Math.max(1, Math.min(opts.chunkSize ?? TUS_CHUNK_BYTES, TUS_CHUNK_BYTES));\n let id = opts.uploadId;\n let offset = 0;\n if (id) offset = (await this.uploads.offset(id, opts)).offset;\n else {\n const md: Record<string, string> = { track: opts.track ?? 'mic' };\n if (opts.transcriptId) md.transcript = opts.transcriptId;\n if (opts.durationMs !== undefined) md.durationMs = String(opts.durationMs);\n id = await this.uploads.create(total, md, opts);\n }\n opts.onProgress?.(offset, total);\n while (offset < total) {\n offset = await this.uploads.append(\n id,\n offset,\n bytes.subarray(offset, Math.min(total, offset + chunk)),\n opts,\n );\n opts.onProgress?.(offset, total);\n }\n return id;\n }\n}\n","/** `POST /v1/tokens` — ephemeral scoped tokens for browsers / webviews. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply } from './_shared';\n\n/** `live` = realtime + audio in one token (a live co-host's speech-to-text and text-to-speech). */\nexport type EphemeralScope = 'realtime' | 'audio' | 'embeddings' | 'live';\nexport type EphemeralTokenResponse = Reply<'createEphemeralToken'>;\n\nexport interface EphemeralToken {\n token: string;\n expiresAt: string;\n scope: EphemeralScope;\n raw: EphemeralTokenResponse;\n}\n\nexport class Tokens {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Mint a short-lived token (60–3600 s, default 600) bound to one surface.\n * Only a real `codai_` key may mint.\n */\n async create(\n scope: EphemeralScope,\n ttlSeconds?: number,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<EphemeralToken> {\n const raw = await this.http.json<EphemeralTokenResponse>('/v1/tokens', {\n body: { scope, ...(ttlSeconds !== undefined ? { ttl_seconds: ttlSeconds } : {}) },\n ext: opts.ext,\n signal: opts.signal,\n });\n return { token: raw.token, expiresAt: raw.expires_at, scope: raw.scope, raw };\n }\n}\n","/**\n * `/v1/tools/*` — verified web search, server-side page fetch and GUI grounding.\n *\n * Same contract as every codai agent surface (packages/agent-core/spec/tools-web.json). Metered per call: $3 / 1k\n * fast searches, $8 / 1k deep, $0.50 / 1k fetches; first 1,000 calls per month free, free inside a codai agent turn.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type ToolSearchRequest = Mutable<Body<'toolsSearch'>>;\nexport type ToolSearchResponse = Reply<'toolsSearch'>;\nexport type ToolFetchRequest = Mutable<Body<'toolsFetch'>>;\nexport type ToolFetchResponse = Reply<'toolsFetch'>;\nexport type ToolGroundRequest = Mutable<Body<'toolsGround'>>;\nexport type ToolGroundResponse = Reply<'toolsGround'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Tools {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/tools/search` — verified web search (never falls back to an unverified provider). Filters:\n * `include_domains` / `exclude_domains`, `freshness` or `published_after` / `published_before` (undated pages are\n * dropped), `content_chars` for a verified excerpt per result. Each result carries `published_at` (null when\n * unknown, never the crawl date) and `crawled_at`.\n */\n search(body: ToolSearchRequest, opts: CallOpts = {}): Promise<ToolSearchResponse> {\n return this.http.json<ToolSearchResponse>('/v1/tools/search', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/tools/fetch` — fetch + extract a public page (SSRF-guarded; `max_chars` default 8000, max 40 000). */\n fetch(body: ToolFetchRequest, opts: CallOpts = {}): Promise<ToolFetchResponse> {\n return this.http.json<ToolFetchResponse>('/v1/tools/fetch', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/tools/ground` — find a described UI element on an inline screenshot (`data:image/...;base64`).\n * Returns `x_norm`/`y_norm` in 0..1 (plus `x`/`y` pixels when `width`/`height` are sent); `found: false` = not on it.\n */\n ground(body: ToolGroundRequest, opts: CallOpts = {}): Promise<ToolGroundResponse> {\n return this.http.json<ToolGroundResponse>('/v1/tools/ground', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/research` — asynchronous deep research.\n *\n * `POST /v1/research` — start a job (`create`); 200 when it finished within `wait_s`, else 202 `{id, status}`\n * `GET /v1/research/{id}` — the job (`retrieve`); `report` / `answer` + `sources` once `done`, `error` if `failed`\n *\n * `wait(id)` polls `retrieve` until the job is `done` or `failed`; `run(body)` = `create` + `wait`.\n * Price: $0.20 per job plus its model tokens (free inside the monthly allowance / a codai agent turn). Polling is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Schema } from './_shared';\n\nexport type ResearchRequest = Mutable<Body<'createResearch'>>;\nexport type ResearchJob = Schema<'ResearchJob'>;\nexport type ResearchSource = Schema<'ResearchSource'>;\nexport type ResearchStatus = ResearchJob['status'];\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface ResearchCreateOptions extends CallOpts {\n /** `Idempotency-Key`: the same key returns the job created earlier instead of starting another one. */\n idempotencyKey?: string;\n}\n\nexport interface ResearchWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 360 000 ms = 6 min; the longest job budget is 300 s). */\n timeoutMs?: number;\n}\n\nconst path = (id: string) => `/v1/research/${encodeURIComponent(id)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport const isResearchFinished = (job: Pick<ResearchJob, 'status'>): boolean =>\n job.status === 'done' || job.status === 'failed';\n\nexport class Research {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/research` — start a deep-research job. With `wait_s` (0..55) the call waits that long and returns the\n * finished job; otherwise (or when it is still running) the job comes back `queued` / `running`.\n */\n create(body: ResearchRequest, opts: ResearchCreateOptions = {}): Promise<ResearchJob> {\n return this.http.json<ResearchJob>('/v1/research', {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/research/{id}` — one of your jobs (another account's id is a 404). Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<ResearchJob> {\n return this.http.json<ResearchJob>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Poll `retrieve` every `intervalMs` (default 3 s) until the job is `done` or `failed` and resolve with it (a\n * `failed` job resolves too — check `status` / `error`). Throws when it is not finished within `timeoutMs`\n * (default 6 min) or when `signal` aborts.\n */\n async wait(id: string, opts: ResearchWaitOptions = {}): Promise<ResearchJob> {\n const { intervalMs = 3000, timeoutMs = 360_000, signal, ext } = opts;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const job = await this.retrieve(id, { ext, signal });\n if (isResearchFinished(job)) return job;\n if (Date.now() + intervalMs > deadline) {\n throw new Error(`codai research job ${id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(intervalMs, signal);\n }\n }\n\n /** `create` then `wait` until the job finishes. */\n async run(\n body: ResearchRequest,\n opts: ResearchCreateOptions & Omit<ResearchWaitOptions, keyof CallOpts> = {},\n ): Promise<ResearchJob> {\n const { intervalMs, timeoutMs, ...createOpts } = opts;\n const job = await this.create(body, createOpts);\n if (isResearchFinished(job)) return job;\n return this.wait(job.id, {\n ext: opts.ext,\n signal: opts.signal,\n ...(intervalMs !== undefined ? { intervalMs } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n });\n }\n}\n","/** `/v1/usage` + `/v1/keys` — the caller's own usage breakdown and API keys (device attribution, tags). */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type UsageReport = Schema<'UsageReport'>;\nexport type UsageRow = Schema<'UsageRow'>;\nexport type UsageGroupBy = UsageReport['group_by'];\n/** `from` / `to` are inclusive `YYYY-MM-DD` UTC dates; `cost_micro_usd` in the reply is USD micros as a string. */\nexport type UsageQuery = Mutable<QueryOf<'getUsage'>>;\nexport type ApiKeyInfo = Schema<'ApiKeyInfo'>;\nexport type ApiKeyList = Reply<'listKeys'>;\nexport type ApiKeyTags = Reply<'setKeyTags'>;\n\nexport interface ApiKeyListQuery {\n /** Also return revoked keys. */\n include_revoked?: boolean;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Usage {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/usage` — default: last 30 days grouped by `day`; at most 400 days per call. */\n get(query: UsageQuery = {}, opts: CallOpts = {}): Promise<UsageReport> {\n return this.http.json<UsageReport>('/v1/usage', {\n query: {\n from: query.from,\n to: query.to,\n group_by: query.group_by,\n key: query.key,\n device: query.device,\n app: query.app,\n platform: query.platform,\n model: query.model,\n tag: query.tag,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Keys {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/keys` — your keys (never the secret); `current: true` marks the calling key. */\n list(query: ApiKeyListQuery = {}, opts: CallOpts = {}): Promise<ApiKeyList> {\n return this.http.json<ApiKeyList>('/v1/keys', {\n query: { include_revoked: query.include_revoked ? 'true' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/keys/{id}` — replace the key's tags (≤ 16, each ≤ 32 chars; `[]` clears). */\n setTags(id: string, tags: string[], opts: CallOpts = {}): Promise<ApiKeyTags> {\n return this.http.json<ApiKeyTags>(`/v1/keys/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body: { tags },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/verify/agent-output*` — EXPERIMENTAL, unaudited (HIDE protocol) verification of\n * signed agent outputs. Provenance only, never authentication. Unauthenticated endpoints.\n */\nimport { type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type EnvironmentTaskOutputSignature = Schema<'EnvironmentTaskOutputSignature'>;\nexport type AgentOutputKey = Reply<'getAgentOutputKey'>;\nexport type AgentOutputVerifyBody = Mutable<Body<'verifyAgentOutput'>>;\nexport type AgentOutputVerifyResult = Reply<'verifyAgentOutput'>;\n\ntype CallOpts = { signal?: AbortSignal };\n\nexport class Verify {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/verify/agent-output/key` — `{ enabled: false }` when signing is off. */\n agentOutputKey(opts: CallOpts = {}): Promise<AgentOutputKey> {\n return this.http.json<AgentOutputKey>('/v1/verify/agent-output/key', { signal: opts.signal });\n }\n\n /** `POST /v1/verify/agent-output` — 503 `signing_disabled` when signing is off. */\n agentOutput(body: AgentOutputVerifyBody, opts: CallOpts = {}): Promise<AgentOutputVerifyResult> {\n return this.http.json<AgentOutputVerifyResult>('/v1/verify/agent-output', {\n method: 'POST',\n body,\n signal: opts.signal,\n // 503 here means `signing_disabled`, not a transient outage.\n noRetry: true,\n });\n }\n}\n","/**\n * Single source of truth for OpenAPI parity: every `operationId` in\n * `apps/docs/openapi/en/gateway.yaml` maps to exactly one dotted method path\n * on the `Codai` client. `operations.test.ts` parses the YAML and fails when\n * an operation is missing, mapped to a non-function, or when this table\n * carries a key the YAML does not have.\n */\nexport const OPERATION_METHODS: Record<string, string> = {\n // Chat & Completions\n createChatCompletion: 'chat.completions.create',\n createResponse: 'responses.create',\n createMessage: 'messages.create',\n // Embeddings & Audio\n createEmbeddings: 'embeddings.create',\n createImage: 'images.generate',\n editImage: 'images.edit',\n createMusic: 'music.generate',\n createVideo: 'videos.create',\n getVideo: 'videos.retrieve',\n createRender: 'renders.create',\n getRender: 'renders.retrieve',\n listRenders: 'renders.list',\n createTimeline: 'renders.createTimeline',\n regenerateRenderScene: 'renders.regenerateScene',\n listAssets: 'assets.list',\n getAsset: 'assets.retrieve',\n getAssetContent: 'assets.contentUrl',\n deleteAsset: 'assets.delete',\n searchSfx: 'sfx.search',\n importSfx: 'sfx.import',\n // Cards (typed card data)\n cardsWeather: 'cards.weather',\n cardsPlaces: 'cards.places',\n cardsGeocode: 'cards.geocode',\n cardsStaticMap: 'cards.staticMap',\n cardsFx: 'cards.fx',\n cardsRoute: 'cards.route',\n cardsTrack: 'cards.track',\n cardsEfactura: 'cards.efactura',\n cardsUnfurl: 'cards.unfurl',\n cardsProduct: 'cards.product',\n cardsRender: 'cards.render',\n createDocument: 'documents.create',\n retrieveDocument: 'documents.retrieve',\n createDocumentPreview: 'documents.preview',\n retrievePreview: 'documents.retrievePreview',\n createDocumentVideo: 'documents.video',\n // Studio creatives (editable creative documents)\n listCreatives: 'creatives.list',\n createCreative: 'creatives.create',\n getCreative: 'creatives.retrieve',\n deleteCreative: 'creatives.delete',\n getCreativeOutline: 'creatives.outline',\n findCreativeNodes: 'creatives.find',\n getCreativeSubtree: 'creatives.subtree',\n applyCreativeOps: 'creatives.edit',\n listCreativeVersions: 'creatives.versions',\n revertCreative: 'creatives.revert',\n forkCreative: 'creatives.fork',\n lintCreative: 'creatives.lint',\n getCreativeCompiled: 'creatives.compiled',\n renderCreative: 'creatives.render',\n createCreativeFrame: 'creatives.frame',\n getCreativeFrameJob: 'creatives.frameJob',\n commentCreative: 'creatives.comment',\n createCreativeVariants: 'creatives.variants',\n listCreativeVariants: 'creatives.listVariants',\n pickCreativeVariant: 'creatives.pickVariant',\n extractBrandKit: 'brandKits.extract',\n listBrandKits: 'brandKits.list',\n getBrandKit: 'brandKits.retrieve',\n deleteBrandKit: 'brandKits.delete',\n createBrandKit: 'brandKits.create',\n updateBrandKit: 'brandKits.update',\n exportBrandKitDtcg: 'brandKits.exportDtcg',\n restyleCreative: 'creatives.restyle',\n captionCreative: 'creatives.captions',\n getCreativeCaptionsSrt: 'creatives.captionsSrt',\n getCreativeCaptionsVtt: 'creatives.captionsVtt',\n adaptCreative: 'creatives.adapt',\n fixCreativeLint: 'creatives.lintFix',\n getCreativeControls: 'creatives.controls',\n getCreativeLocales: 'creatives.locales',\n localizeCreative: 'creatives.localize',\n forkCreativeLocale: 'creatives.forkLocale',\n createCreativeShare: 'creatives.createShare',\n listCreativeShares: 'creatives.listShares',\n revokeCreativeShare: 'creatives.revokeShare',\n getCreativeReview: 'creatives.review',\n updateCreativeReview: 'creatives.requestReview',\n listCreativeReviewThreads: 'creatives.reviewThreads',\n createCreativeReviewThread: 'creatives.createReviewThread',\n replyCreativeReviewThread: 'creatives.replyReviewThread',\n resolveCreativeReviewThread: 'creatives.resolveReviewThread',\n reopenCreativeReviewThread: 'creatives.reopenReviewThread',\n deleteCreativeReviewComment: 'creatives.deleteReviewComment',\n remixStudioShare: 'shares.remix',\n getPublicStudioShare: 'shares.get',\n createPublicReviewThread: 'shares.comment',\n replyPublicReviewThread: 'shares.reply',\n resolvePublicReviewThread: 'shares.resolve',\n reopenPublicReviewThread: 'shares.reopen',\n decidePublicReview: 'shares.decide',\n createVoiceRevocation: 'voiceRevocations.create',\n getVaultAccount: 'vault.account',\n putVaultAccount: 'vault.putAccount',\n patchVaultSettings: 'vault.updateSettings',\n lockVault: 'vault.lock',\n createVaultUnlockChallenge: 'vault.unlockChallenge',\n unlockVault: 'vault.unlock',\n listVaultLimits: 'vault.limits',\n setVaultItemLimits: 'vault.setLimits',\n revokeVaultTaskGrants: 'vault.revokeTaskGrants',\n listVaults: 'vault.vaults',\n createVault: 'vault.createVault',\n listVaultItems: 'vault.items',\n putVaultItem: 'vault.putItem',\n deleteVaultItem: 'vault.deleteItem',\n setVaultItemCloud: 'vault.setItemCloud',\n listVaultRules: 'vault.rules',\n createVaultRule: 'vault.createRule',\n deleteVaultRule: 'vault.deleteRule',\n listVaultGrants: 'vault.grants',\n revokeVaultGrant: 'vault.revokeGrant',\n listVaultEvents: 'vault.events',\n listVaultApprovals: 'vault.approvals',\n getVaultApproval: 'vault.approval',\n decideVaultApproval: 'vault.decide',\n createVaultDeviceChallenge: 'vault.devices.challenge',\n enrollVaultDevice: 'vault.devices.enroll',\n listVaultDevices: 'vault.devices.list',\n renameVaultDevice: 'vault.devices.rename',\n revokeVaultDevice: 'vault.devices.revoke',\n vaultCatalog: 'vault.catalog',\n vaultUse: 'vault.use',\n vaultHttp: 'vault.httpCall',\n vaultResolve: 'vault.resolve',\n createStudioAbuseReport: 'abuseReports.create',\n checkProvenance: 'provenance.check',\n createStudioBatch: 'batches.create',\n listStudioBatches: 'batches.list',\n getStudioBatch: 'batches.get',\n cancelStudioBatch: 'batches.cancel',\n retryStudioBatch: 'batches.retry',\n exportStudioBatchCsv: 'batches.exportCsv',\n zipStudioBatch: 'batches.zip',\n saveCreativeTemplate: 'creatives.saveTemplate',\n listCreativeTemplates: 'templates.list',\n createStudioProduction: 'productions.create',\n getStudioProduction: 'productions.retrieve',\n listStudioMediaOps: 'mediaOps.list',\n quoteStudioMediaOp: 'mediaOps.quote',\n runStudioMediaOp: 'mediaOps.run',\n getStudioMediaOpJob: 'mediaOps.job',\n writeStudioLyrics: 'lyrics.write',\n alignStudioLyrics: 'lyrics.align',\n getCreativeTemplate: 'templates.retrieve',\n deleteCreativeTemplate: 'templates.delete',\n exportCreativeFcpxml: 'creatives.exportFcpxml',\n exportCreativeLottie: 'creatives.exportLottie',\n getStudioExport: 'exports.retrieve',\n createCreativeFromDocument: 'creatives.fromDocument',\n buildCreative: 'creatives.build',\n createSystemOne: 'systemOne.create',\n createTranscription: 'audio.transcribe',\n createSpeech: 'audio.speech',\n createSpeechStream: 'audio.speechStream',\n createEphemeralToken: 'tokens.create',\n // Models\n listModels: 'models.list',\n // Health\n getHealth: 'health.get',\n getHealthReady: 'health.ready',\n getStatus: 'health.status',\n // Agents\n runAgentSync: 'agents.run',\n createAgentRun: 'agents.runs.create',\n getAgentRunStats: 'agents.runs.stats',\n getAgentRun: 'agents.runs.get',\n listAgentRunSteps: 'agents.runs.steps',\n streamAgentRun: 'agents.runs.stream',\n cancelAgentRun: 'agents.runs.cancel',\n // Tools\n toolsSearch: 'tools.search',\n toolsFetch: 'tools.fetch',\n toolsGround: 'tools.ground',\n createResearch: 'research.create',\n getResearch: 'research.retrieve',\n // Tasks\n listTasks: 'tasks.list',\n listPendingTasks: 'tasks.pending',\n getTaskStats: 'tasks.stats',\n getTask: 'tasks.get',\n confirmTask: 'tasks.confirm',\n // Event triggers + inbox\n listTriggers: 'triggers.list',\n createTrigger: 'triggers.create',\n updateTrigger: 'triggers.update',\n deleteTrigger: 'triggers.delete',\n rotateTriggerSecret: 'triggers.rotateSecret',\n setTriggerSecret: 'triggers.setSecret',\n testTrigger: 'triggers.test',\n listTriggerEvents: 'triggers.events',\n receiveTriggerHook: 'triggers.fireHook',\n listNotifications: 'notifications.list',\n markNotificationsRead: 'notifications.markRead',\n deleteNotification: 'notifications.delete',\n deleteNotifications: 'notifications.deleteMany',\n // Pending prompts\n listPrompts: 'prompts.list',\n createPrompt: 'prompts.create',\n getPrompt: 'prompts.get',\n updatePrompt: 'prompts.update',\n deletePrompt: 'prompts.delete',\n launchPrompt: 'prompts.launch',\n matchPrompt: 'prompts.match',\n verifyPrompt: 'prompts.verify',\n verifyPrompts: 'prompts.verifyMany',\n streamPrompts: 'prompts.stream',\n exportPrompts: 'prompts.exportPrompts',\n bulkPrompts: 'prompts.bulk',\n listPromptEvents: 'prompts.events',\n instantiatePrompt: 'prompts.instantiate',\n // Transcripts\n listTranscripts: 'transcripts.list',\n createTranscript: 'transcripts.create',\n getTranscriptUsage: 'transcripts.usage',\n streamTranscripts: 'transcripts.stream',\n searchTranscripts: 'transcripts.search',\n askTranscripts: 'transcripts.ask',\n getTranscript: 'transcripts.get',\n updateTranscript: 'transcripts.update',\n deleteTranscript: 'transcripts.delete',\n finalizeTranscript: 'transcripts.finalize',\n retranscribeTranscript: 'transcripts.retranscribe',\n reanalyzeTranscript: 'transcripts.reanalyze',\n addTranscriptBookmark: 'transcripts.addBookmark',\n updateTranscriptSpeaker: 'transcripts.renameSpeaker',\n updateTranscriptUtterance: 'transcripts.editUtterance',\n getTranscriptAudio: 'transcripts.audio',\n exportTranscript: 'transcripts.export',\n acceptTranscriptPrompt: 'transcripts.acceptPrompt',\n createTranscriptShare: 'transcripts.shares.create',\n listTranscriptShares: 'transcripts.shares.list',\n revokeTranscriptShare: 'transcripts.shares.revoke',\n getPublicTranscript: 'transcripts.publicView',\n listTranscriptFolders: 'transcripts.folders.list',\n createTranscriptFolder: 'transcripts.folders.create',\n updateTranscriptFolder: 'transcripts.folders.update',\n deleteTranscriptFolder: 'transcripts.folders.delete',\n getTranscriptVocabulary: 'transcripts.vocabulary.get',\n putTranscriptVocabulary: 'transcripts.vocabulary.put',\n getUploadCapabilities: 'transcripts.uploads.capabilities',\n createUpload: 'transcripts.uploads.create',\n getUploadOffset: 'transcripts.uploads.offset',\n appendUpload: 'transcripts.uploads.append',\n publishTranscriptLive: 'transcripts.publishLive',\n // Scheduler\n listSchedules: 'schedules.list',\n createSchedule: 'schedules.create',\n previewSchedule: 'schedules.preview',\n streamSchedules: 'schedules.stream',\n getSchedule: 'schedules.get',\n updateSchedule: 'schedules.update',\n deleteSchedule: 'schedules.delete',\n runSchedule: 'schedules.runNow',\n listScheduleRuns: 'schedules.runs',\n listRecentScheduleRuns: 'schedules.recentRuns',\n decideScheduleRun: 'schedules.decide',\n approveScheduleCommand: 'schedules.executor.approveCommand',\n claimScheduleRun: 'schedules.executor.claim',\n heartbeatScheduleRun: 'schedules.executor.heartbeat',\n reportScheduleRunResult: 'schedules.executor.result',\n listSchedulerHosts: 'schedules.hosts.list',\n updateSchedulerHost: 'schedules.hosts.update',\n pauseSchedules: 'schedules.pause',\n resumeSchedules: 'schedules.resume',\n listScheduleTemplates: 'schedules.templates',\n renderScheduleTemplate: 'schedules.renderTemplate',\n listScheduleAudit: 'schedules.audit',\n listHeartbeats: 'heartbeats.list',\n createHeartbeat: 'heartbeats.create',\n updateHeartbeat: 'heartbeats.update',\n deleteHeartbeat: 'heartbeats.delete',\n // Lists & share sheet\n listLists: 'lists.list',\n createList: 'lists.create',\n reorderLists: 'lists.reorder',\n streamLists: 'lists.stream',\n updateList: 'lists.update',\n deleteList: 'lists.delete',\n listListItems: 'lists.items',\n addListItem: 'lists.add',\n updateListItem: 'lists.updateItem',\n deleteListItem: 'lists.deleteItem',\n getListItemImage: 'lists.image',\n exportListMarkdown: 'lists.exportMarkdown',\n shareToList: 'lists.share',\n // Usage & keys\n getUsage: 'usage.get',\n listKeys: 'keys.list',\n setKeyTags: 'keys.setTags',\n // Memory\n listMemories: 'memory.list',\n searchMemories: 'memory.search',\n createMemory: 'memory.create',\n deleteMemory: 'memory.delete',\n deleteAllMemories: 'memory.deleteAll',\n // Sandboxes\n createSandbox: 'sandboxes.create',\n listSandboxes: 'sandboxes.list',\n getSandbox: 'sandboxes.retrieve',\n execSandbox: 'sandboxes.exec',\n putSandboxFile: 'sandboxes.files.put',\n getSandboxFile: 'sandboxes.files.get',\n listSandboxFiles: 'sandboxes.files.list',\n listSandboxArtifacts: 'sandboxes.artifacts',\n snapshotSandbox: 'sandboxes.snapshot',\n deleteSandbox: 'sandboxes.delete',\n runSandbox: 'sandboxes.run',\n runSandboxCode: 'sandboxes.runCode',\n resetSandboxKernel: 'sandboxes.resetKernel',\n pauseSandbox: 'sandboxes.pause',\n resumeSandbox: 'sandboxes.resume',\n forkSandbox: 'sandboxes.fork',\n previewSandbox: 'sandboxes.preview',\n // Sessions\n createSession: 'sessions.create',\n listSessions: 'sessions.list',\n getSession: 'sessions.get',\n updateSession: 'sessions.update',\n deleteSession: 'sessions.delete',\n listSessionEvents: 'sessions.events.list',\n appendSessionEvents: 'sessions.events.append',\n listSessionControls: 'sessions.controls.list',\n submitSessionControl: 'sessions.controls.submit',\n markSessionControlApplied: 'sessions.controls.markApplied',\n dispatchToDevice: 'sessions.dispatch',\n claimSessionLease: 'sessions.lease.acquire',\n heartbeatSessionLease: 'sessions.lease.renew',\n releaseSessionLease: 'sessions.lease.release',\n streamSession: 'sessions.stream',\n // Devices\n getMyDispatchInbox: 'devices.dispatchInbox',\n listDevices: 'devices.list',\n updateDevice: 'devices.update',\n deleteDevice: 'devices.delete',\n revokeSelfKey: 'devices.revokeSelfKey',\n // Hosts\n listHosts: 'hosts.list',\n streamHost: 'hosts.stream',\n execOnHost: 'hosts.exec',\n postHostExecResult: 'hosts.postResult',\n // Orgs & Sharing\n listSessionsSharedWithMe: 'sessions.shares.sharedWithMe',\n listSessionShares: 'sessions.shares.list',\n createSessionShare: 'sessions.shares.create',\n deleteSessionShare: 'sessions.shares.delete',\n createOrg: 'orgs.create',\n listOrgs: 'orgs.list',\n listOrgMembers: 'orgs.members.list',\n addOrgMember: 'orgs.members.add',\n removeOrgMember: 'orgs.members.remove',\n // Projects\n listProjects: 'projects.list',\n createProject: 'projects.create',\n getProject: 'projects.get',\n updateProject: 'projects.update',\n deleteProject: 'projects.delete',\n // Environments\n listEnvironments: 'environments.list',\n createEnvironment: 'environments.create',\n enrollEnvironment: 'environments.enroll',\n getEnvironment: 'environments.get',\n updateEnvironment: 'environments.update',\n startEnvironment: 'environments.start',\n stopEnvironment: 'environments.stop',\n archiveEnvironment: 'environments.archive',\n destroyEnvironment: 'environments.destroy',\n createEnvironmentEnrollToken: 'environments.enrollToken',\n listEnvironmentMembers: 'environments.members.list',\n addEnvironmentMember: 'environments.members.add',\n setMyEnvironmentSshKey: 'environments.members.setSshKey',\n setEnvironmentMemberRole: 'environments.members.setRole',\n removeEnvironmentMember: 'environments.members.remove',\n issueMyEnvironmentSshCert: 'environments.members.sshCert',\n getEnvironmentSshCa: 'environments.sshCa',\n listEnvironmentTasks: 'environments.tasks.list',\n createEnvironmentTask: 'environments.tasks.create',\n getEnvironmentTask: 'environments.tasks.get',\n execEnvironment: 'environments.exec',\n listEnvironmentFiles: 'environments.files.list',\n getEnvironmentFile: 'environments.files.get',\n putEnvironmentFile: 'environments.files.put',\n startEnvironmentJob: 'environments.jobs.start',\n getEnvironmentJob: 'environments.jobs.get',\n // Agent-output signatures (EXPERIMENTAL, HIDE)\n getAgentOutputKey: 'verify.agentOutputKey',\n verifyAgentOutput: 'verify.agentOutput',\n listEnvironmentPorts: 'environments.ports.list',\n setEnvironmentPort: 'environments.ports.set',\n removeEnvironmentPort: 'environments.ports.remove',\n listEnvironmentSecrets: 'environments.secrets.list',\n setEnvironmentSecret: 'environments.secrets.set',\n removeEnvironmentSecret: 'environments.secrets.remove',\n // Account\n getAccount: 'account.get',\n patchAccount: 'account.update',\n getBilling: 'billing.get',\n listBillingInvoices: 'billing.invoices',\n getStudioQuote: 'billing.studioQuote',\n getReferrals: 'referrals.get',\n getSettings: 'settings.get',\n patchSettings: 'settings.update',\n getPolicy: 'osGate.policy',\n recordOsGateEvent: 'osGate.recordEvent',\n getReceipt: 'receipt.get',\n submitFeedback: 'feedback.submit',\n listPhoneModels: 'phoneModels.list',\n};\n\n/** Operations whose SDK method is an async iterator (SSE-only endpoints). */\nexport const STREAMING_OPERATIONS: ReadonlySet<string> = new Set([\n 'streamAgentRun',\n 'streamSession',\n 'streamHost',\n 'createSpeechStream',\n 'streamPrompts',\n 'streamTranscripts',\n 'streamSchedules',\n 'streamLists',\n]);\n\n/**\n * Same parity contract for the separate Resolve service\n * (`apps/docs/openapi/en/resolve.yaml`, host `resolveBaseUrl`) —\n * checked by `operations.resolve.test.ts`.\n */\nexport const RESOLVE_OPERATION_METHODS: Record<string, string> = {\n resolveHealth: 'resolve.health',\n createResolveJob: 'resolve.submit',\n getResolveJob: 'resolve.get',\n listResolveJobs: 'resolve.list',\n acceptResolveJob: 'resolve.accept',\n getResolveAttestation: 'resolve.attestation',\n getResolveKeys: 'resolve.keys',\n getResolveBalance: 'resolve.balance',\n};\n","/**\n * `CodaiApps` — management client for host apps (studiai.ro, …) that resell\n * codai to their own end users. It talks to the mgmt API (`api.codai.ro`),\n * not the gateway, and authenticates with an app connection token\n * (`codai_app_…`, created at codai.ro/console/apps/<app>), never a user key.\n *\n * keys.mint / list / update / revoke / usage → `/apps/keys*`\n * users.getOverride / setOverride / clearOverride → `/apps/users/:externalId/overrides`\n * subscriptions.sync → `/apps/subscriptions/sync`\n * validateKey → `/internal/keys/validate` (separate shared secret)\n *\n * Every call unwraps the `{ ok, data }` envelope and throws `CodaiError` on\n * a non-2xx reply (`error.code` such as `missing_scope:keys.mint`,\n * `no_key_for_external_id`, `not_owned_by_app`).\n */\n\nimport { CodaiError, HttpClient, type RequestOptions } from '../http';\n\nexport interface CodaiAppsOptions {\n /** App connection token (`codai_app_…`). Required for everything except `validateKey`. */\n appToken?: string;\n /** Shared secret for `POST /internal/keys/validate` (CODAI_VALIDATE_SHARED_SECRET on codai's side). */\n validateToken?: string;\n /** Defaults to https://api.codai.ro */\n baseUrl?: string;\n /** Default request timeout (ms). Default 20_000. */\n timeoutMs?: number;\n /** Retries on 429/5xx for idempotent calls. Default 1. `keys.mint` is never retried. */\n maxRetries?: number;\n fetch?: typeof fetch;\n}\n\nexport interface AppKeyMintInput {\n /** End user email; codai upserts its user by email so subscription syncs land on the same user. */\n email: string;\n /** The app's own stable id for the end user (≤ 200 chars). */\n endUserExternalId: string;\n label?: string;\n /** Tier slug within the app (defaults to the app's `default_tier_slug`). */\n tierSlug?: string;\n /** Attach to an existing subscription of this app + user. */\n subscriptionId?: string;\n /** Accepted for back-compat and ignored (euro caps were removed product-wide). */\n budgetEurPerDay?: number;\n /** Intersected with the app's own allowlist. */\n allowedModels?: string[];\n ratePerMinute?: number;\n ratePerHour?: number;\n maxInputTokens?: number;\n maxOutputTokens?: number;\n /** ISO 8601 with offset, in the future. Omit = never expires. */\n expiresAt?: string;\n /**\n * The end user confirmed being 18 or older in your app. Stored on the codai user when it is\n * CREATED by this call (`users.adult_confirmed_at`, version `host:<app slug>`).\n */\n adultConfirmed?: boolean;\n}\n\nexport interface AppKeyMinted {\n id: string;\n /** Plaintext key — returned exactly once. */\n key: string;\n prefix: string;\n subscriptionId: string | null;\n expiresAt: string | null;\n}\n\nexport interface AppKeyListQuery {\n endUserExternalId?: string;\n /** 1..200, default 50. */\n limit?: number;\n offset?: number;\n}\n\nexport interface AppKey {\n id: string;\n label: string;\n prefix: string;\n enabled: boolean;\n subscriptionId: string | null;\n endUserExternalId: string | null;\n lastUsedAt: string | null;\n createdAt: string;\n revokedAt: string | null;\n expiresAt?: string | null;\n}\n\nexport interface AppKeyUpdate {\n label?: string;\n enabled?: boolean;\n}\n\nexport interface AppKeyUsageWindow {\n requests: number;\n tasks: number;\n costUsd: number;\n}\n\nexport interface AppKeyUsage {\n key: { id: string; prefix: string; label: string; createdAt: string };\n usage: {\n total: AppKeyUsageWindow & {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n };\n today: AppKeyUsageWindow;\n month: AppKeyUsageWindow;\n tokensPerMinute?: {\n inputUsed: number;\n outputUsed: number;\n lastActiveInput?: number;\n lastActiveOutput?: number;\n lastActiveAt?: string | null;\n inputPeak?: number;\n inputPeakAt?: string | null;\n inputLimit: number;\n isDefaultLimit: boolean;\n };\n daily: Array<\n AppKeyUsageWindow & { date: string; promptTokens: number; completionTokens: number }\n >;\n };\n limits: {\n tierSlug: string | null;\n tierLabel: string | null;\n tasksPerDay: number | null;\n tasksPerMonth: number | null;\n ratePerMinute: number | null;\n ratePerHour: number | null;\n inputTokensPerMinute?: number | null;\n budgetEurPerDay: number | null;\n budgetEurPerMonth?: number | null;\n hasActiveSubscription: boolean;\n };\n}\n\n/** Per-(app, end user) override fields; `null` clears a field back to the tier value. */\nexport interface AppOverrideInput {\n forceTierSlug?: string | null;\n allowedModels?: string[] | null;\n ratePerMinute?: number | null;\n ratePerHour?: number | null;\n budgetEurPerDay?: number | null;\n budgetEurPerMonth?: number | null;\n tasksPerDay?: number | null;\n tasksPerMonth?: number | null;\n /** ISO 8601; null = never expires. */\n expiresAt?: string | null;\n note?: string | null;\n /** Restart task counting from now (usage history is kept). */\n resetUsage?: boolean | null;\n}\n\nexport interface AppOverrideRow {\n id: string;\n forceTierSlug: string | null;\n allowedModels: string[] | null;\n ratePerMinute: number | null;\n ratePerHour: number | null;\n budgetEurPerDay: string | number | null;\n budgetEurPerMonth?: string | number | null;\n tasksPerDay: number | null;\n tasksPerMonth: number | null;\n expiresAt: string | null;\n note: string | null;\n}\n\n/** Effective limits after merging the override on top of the subscription tier. */\nexport interface AppEffectiveLimits {\n tierSlug: string | null;\n tierLabel: string | null;\n allowedModels: string[] | null;\n ratePerMinute: number | null;\n ratePerDay?: number | null;\n budgetEurPerDay: number | null;\n budgetEurPerMonth?: number | null;\n tasksPerDay: number | null;\n tasksPerMonth: number | null;\n maxRoutingTier?: 'small' | 'medium' | 'large' | null;\n hasActiveSubscription: boolean;\n [extra: string]: unknown;\n}\n\nexport interface AppOverride {\n override: AppOverrideRow | null;\n effectiveLimits: AppEffectiveLimits;\n /** Present on reads: whether overrides are enabled for the app at all. */\n allowOverride?: boolean;\n}\n\nexport interface AppSubscriptionSyncInput {\n /** Email of the subscribing end user. */\n email: string;\n /** The Stripe event verbatim; codai re-shapes it server-side. */\n event: { id: string; type: string; data?: { object?: unknown } };\n /** The end user confirmed being 18 or older (stored when the codai user is created by this sync). */\n adultConfirmed?: boolean;\n}\n\nexport interface AppKeyValidation {\n ok: boolean;\n valid: boolean;\n key?: {\n id: string;\n prefix: string;\n label: string;\n appId: string;\n subscriptionId: string | null;\n endUserExternalId: string | null;\n };\n user?: { id: string };\n entitlements?: {\n tierSlug: string | null;\n hasActiveSubscription: boolean;\n allowedModels: string[] | null;\n ratePerMinute: number | null;\n ratePerHour: number | null;\n maxInputTokens: number | null;\n maxOutputTokens: number | null;\n budgetEurPerDay: number | null;\n supportsSubagents: boolean;\n supportsByok: boolean;\n };\n /** Set when `valid` is false (`key_not_found_or_disabled`). */\n reason?: string;\n}\n\ntype CallOpts = { signal?: AbortSignal };\ntype Envelope<T> = { ok: boolean; data?: T; error?: unknown };\n\nconst enc = encodeURIComponent;\n\nclass AppKeys {\n constructor(private readonly apps: CodaiApps) {}\n\n /** `POST /apps/keys` — mint a key for one of the app's end users (scope `keys.mint`). Never retried. */\n mint(input: AppKeyMintInput, o: CallOpts = {}): Promise<AppKeyMinted> {\n return this.apps.call('/apps/keys', { method: 'POST', body: input, noRetry: true, ...o });\n }\n\n /** `GET /apps/keys` — keys minted by this app, newest first (scope `usage.read`). */\n list(query: AppKeyListQuery = {}, o: CallOpts = {}): Promise<AppKey[]> {\n return this.apps.call('/apps/keys', {\n query: {\n endUserExternalId: query.endUserExternalId,\n limit: query.limit,\n offset: query.offset,\n },\n ...o,\n });\n }\n\n /** `PATCH /apps/keys/{id}` — change label / enabled (scope `keys.mint`). */\n update(\n id: string,\n patch: AppKeyUpdate,\n o: CallOpts = {},\n ): Promise<{ id: string } & AppKeyUpdate> {\n return this.apps.call(`/apps/keys/${enc(id)}`, { method: 'PATCH', body: patch, ...o });\n }\n\n /** `DELETE /apps/keys/{id}` — revoke (scope `keys.revoke`). */\n revoke(id: string, o: CallOpts = {}): Promise<{ id: string }> {\n return this.apps.call(`/apps/keys/${enc(id)}`, { method: 'DELETE', ...o });\n }\n\n /** `GET /apps/keys/{id}/usage?days=` — codai-side usage + effective limits; `days` clamps to 1..90. */\n usage(id: string, days = 30, o: CallOpts = {}): Promise<AppKeyUsage> {\n return this.apps.call(`/apps/keys/${enc(id)}/usage`, { query: { days }, ...o });\n }\n\n /** Revoke every non-revoked key minted for `endUserExternalId`; returns how many were revoked. */\n async revokeAllFor(endUserExternalId: string, o: CallOpts = {}): Promise<number> {\n const keys = await this.list({ endUserExternalId, limit: 200 }, o);\n let revoked = 0;\n for (const k of keys) {\n if (k.revokedAt) continue;\n await this.revoke(k.id, o);\n revoked++;\n }\n return revoked;\n }\n}\n\nclass AppUsers {\n constructor(private readonly apps: CodaiApps) {}\n\n /** `GET /apps/users/{externalId}/overrides` — current override + effective limits (scope `usage.read`). */\n getOverride(externalId: string, o: CallOpts = {}): Promise<AppOverride> {\n return this.apps.call(`/apps/users/${enc(externalId)}/overrides`, o);\n }\n\n /** `PUT /apps/users/{externalId}/overrides` — set / replace (scope `overrides.write`, app must allow overrides). */\n setOverride(externalId: string, input: AppOverrideInput, o: CallOpts = {}): Promise<AppOverride> {\n return this.apps.call(`/apps/users/${enc(externalId)}/overrides`, {\n method: 'PUT',\n body: input,\n ...o,\n });\n }\n\n /** `DELETE /apps/users/{externalId}/overrides` — clear (scope `overrides.write`). */\n clearOverride(externalId: string, o: CallOpts = {}): Promise<{ removed: boolean }> {\n return this.apps.call(`/apps/users/${enc(externalId)}/overrides`, { method: 'DELETE', ...o });\n }\n}\n\nclass AppSubscriptions {\n constructor(private readonly apps: CodaiApps) {}\n\n /** `POST /apps/subscriptions/sync` — forward a Stripe subscription event (scope `subscriptions.sync`; idempotent per subscription). */\n sync(\n input: AppSubscriptionSyncInput,\n o: CallOpts = {},\n ): Promise<{ subscriptionId: string | null }> {\n return this.apps.call('/apps/subscriptions/sync', { method: 'POST', body: input, ...o });\n }\n}\n\nexport class CodaiApps {\n readonly keys: AppKeys;\n readonly users: AppUsers;\n readonly subscriptions: AppSubscriptions;\n private readonly appHttp: HttpClient | null;\n private readonly validateHttp: HttpClient | null;\n\n constructor(opts: CodaiAppsOptions) {\n if (!opts.appToken && !opts.validateToken) {\n throw new Error('CodaiApps: appToken or validateToken is required');\n }\n const common = {\n baseUrl: opts.baseUrl ?? 'https://api.codai.ro',\n timeoutMs: opts.timeoutMs ?? 20_000,\n maxRetries: opts.maxRetries ?? 1,\n fetch: opts.fetch,\n };\n this.appHttp = opts.appToken ? new HttpClient({ apiKey: opts.appToken, ...common }) : null;\n this.validateHttp = opts.validateToken\n ? new HttpClient({ apiKey: opts.validateToken, ...common })\n : null;\n this.keys = new AppKeys(this);\n this.users = new AppUsers(this);\n this.subscriptions = new AppSubscriptions(this);\n }\n\n /**\n * `POST /internal/keys/validate` — does this plaintext key resolve to an\n * enabled codai key? Returns `{ valid: false, reason }` for unknown /\n * disabled keys; throws `CodaiError` for auth or transport failures.\n */\n async validateKey(key: string, o: CallOpts = {}): Promise<AppKeyValidation> {\n if (!this.validateHttp) throw new Error('CodaiApps: validateToken is required for validateKey');\n return this.validateHttp.json<AppKeyValidation>('/internal/keys/validate', {\n method: 'POST',\n body: { key },\n ...o,\n });\n }\n\n /** @internal Perform an app-token call and unwrap `{ ok, data }`. */\n async call<T>(path: string, init: RequestOptions = {}): Promise<T> {\n if (!this.appHttp) throw new Error('CodaiApps: appToken is required for /apps/* calls');\n const env = await this.appHttp.json<Envelope<T>>(path, init);\n if (!env || env.ok !== true || env.data === undefined) {\n throw new CodaiError(`codai ${path} → ok=false`, 200, env);\n }\n return env.data;\n }\n}\n","/**\n * codai-sdk — official TypeScript client for the codai AI gateway.\n *\n * Full parity with the public gateway OpenAPI (every `operationId` has one\n * method — see `OPERATION_METHODS`). Resources hang off the `Codai` client:\n *\n * client.chat.completions.create / .stream client.messages / client.responses\n * client.embeddings / client.images / client.audio / client.tokens / client.models / client.health\n * client.music.generate / client.videos.create / .retrieve / .generate (codai Studio, US-only)\n * client.renders.create / .retrieve / .render (codai Studio HyperFrames → MP4, codai-render)\n * client.assets.list / .retrieve / .contentUrl / .delete (stored codai Studio assets)\n * client.sfx.search / .import (codai Studio CC0 sound-effects library, codai-sfx)\n * client.documents.create / .retrieve / .preview / .retrievePreview / .video / .createPreviewAndWait / .videoAndWait\n * (codai Studio decks / docs / sheets → PPTX / DOCX / XLSX, codai-docs; previews codai-docs-preview)\n * client.creatives.create / .retrieve / .outline / .find / .subtree / .edit / .versions / .revert / .fork / .lint\n * / .compiled / .render / .frame / .frameJob / .comment / .variants / .listVariants / .pickVariant\n * / .saveTemplate / .exportFcpxml / .exportLottie / .downloadLottie / .fromDocument / .build / .restyle / .captions / .captionsSrt / .captionsVtt\n * / .adapt / .lintFix / .controls / .locales / .localize / .forkLocale / .createShare / .listShares\n * / .revokeShare / .review / .requestReview / .resetReview / .reviewThreads / .createReviewThread\n * / .replyReviewThread / .resolveReviewThread / .reopenReviewThread / .deleteReviewComment / .delete\n * (codai Studio editable creative documents, ops + version history + A/B variants; free but render, comment,\n * variants and frames beyond the daily quota)\n * client.brandKits.create / .update / .exportDtcg / .extract / .list / .retrieve / .delete (codai Studio brand\n * kits as DTCG tokens, from a web page or a logo; extract is\n * token-metered, the rest free; apply with creatives.create({ kind, brand_kit_id }))\n * client.templates.list / .retrieve / .delete (codai Studio templates saved with creatives.saveTemplate plus the 40\n * built-in starters; free; use with creatives.create({ kind, template, vars }))\n * client.productions.create / .retrieve / .wait / .run (codai Studio brief → promo video: storyboard, images,\n * voice-over, editable creative, draft render, one review + repair; billed as the parts are produced)\n * client.mediaOps.list / .quote / .run / .job / .wait / .runAndWait (codai Studio media operations on your assets:\n * background removal, upscale, inpaint / outpaint / erase, stems, denoise, MIDI, mastering, analysis, ACE-Step\n * music and sound effects; quote held, measured cost billed; async ops return a job)\n * client.lyrics.write / .align (codai Studio lyrics writer with syllable + rhyme checks; karaoke alignment to a clip\n * of an audio creative with LRC; token-metered / transcription billed)\n * client.creatives.renderAudio (mixdown + mastering of an audio creative: WAV / MP3 / FLAC, stems, LRC)\n * client.jam.connect (WebSocket live jam on Lyria RealTime; not an OpenAPI operation)\n * client.exports.retrieve / .wait (codai Studio FCPXML exports queued with creatives.exportFcpxml; only newly\n * rendered seconds are billed; Lottie exports from creatives.exportLottie are free and ready at once)\n * client.batches.create / .dryRun / .list / .get / .cancel / .retry / .exportCsv / .zip / .wait (codai Studio\n * batches: one creative per CSV / sheet row; free, row translations and renders billed as usual)\n * client.shares.get / .remix / .comment / .reply / .resolve / .reopen / .decide (codai Studio share links from the\n * outside: read a shared creative, remix a view link, comment and decide through a review link; free)\n * client.voiceRevocations.create (public takedown ticket for a voice cloned in codai Studio; no key needed)\n * client.vault.account / .items / .putItem / .rules / .approvals / .decide / .catalog / .use / .httpCall / .resolve\n * client.vault.devices.challenge / .enroll / .list / .rename / .revoke (device approval keys, V-27)\n * client.vault.updateSettings / .lock / .unlockChallenge / .unlock / .limits / .setLimits / .revokeTaskGrants (guards, v4)\n * (zero-knowledge credentials vault: ciphertext only; the broker calls never return secret values)\n * client.abuseReports.create (public DSA notice about a codai Studio share / review link; no key needed)\n * client.provenance.check (public: which codai AI-provenance marks a file carries; no key needed)\n * client.systemOne.create / .batch (typed decisions, codai-s1)\n * client.realtime.connect (WebSocket live STT / voice; not an OpenAPI operation)\n * client.agents.run + client.agents.runs.* client.tools.search / .fetch (metered web tools)\n * client.research.create / .retrieve / .wait / .run (async deep research, cited report)\n * client.cards.weather / .places / .geocode / .staticMap / .fx / .unfurl (typed card data, `{ block, provenance }`)\n * client.tasks.* client.sessions.* (events, controls, lease, shares, stream)\n * client.devices.* / client.hosts.* client.orgs.* / client.account / client.receipt\n * client.settings.get / .update (account-level settings shared by every device)\n * client.osGate.policy / .recordEvent (OS protection gate: org override policy + override audit events)\n * client.billing.get / .invoices / .watchBalance (READ-ONLY billing overview; never starts a payment)\n * client.referrals.get / .redeem / .setConsent (referral stats + invitees; mutations via PATCH /v1/account)\n * client.usage.get / client.keys.list / .setTags (own usage breakdown + API keys)\n * client.projects.* client.environments.* (members, ports, secrets)\n * client.sandboxes.create / .list / .retrieve / .exec / .execStream / .files.put / .files.get / .files.list\n * / .artifacts / .snapshot / .delete / .run (agent sandboxes: isolated gVisor workspaces, no network by default)\n * / .runCode / .resetKernel / .pause / .resume / .fork / .preview (backend v2, the default; .snapshot is v1 only)\n * client.verify.agentOutputKey / .agentOutput (EXPERIMENTAL HIDE-signed agent outputs)\n * client.feedback / client.phoneModels\n * client.resolve.* (verified bug fixes on https://resolve.codai.ro — resolve.yaml; .list / .iterate page your jobs)\n *\n * Top-level `chat()`, `chatStream()`, `embeddings()`, `models()`, `feedback()`,\n * `mintToken()` from 0.2.x are kept as thin aliases.\n *\n * Zero runtime dependencies; Node 18+ (global fetch) and modern edge runtimes.\n */\n\nimport { type CodaiRequestExtensions, HttpClient } from './http';\nimport { Account, Feedback, PhoneModels, Receipts } from './resources/account';\nimport { Agents } from './resources/agents';\nimport { Audio } from './resources/audio';\nimport { Billing } from './resources/billing';\nimport { Cards } from './resources/cards';\nimport {\n Chat,\n type ChatCompletionInput,\n type ChatCompletionRequest,\n type ChatMessage,\n type ChatResult,\n type ChatStream,\n} from './resources/chat';\nimport { Devices } from './resources/devices';\nimport { Embeddings } from './resources/embeddings';\nimport { Environments } from './resources/environments';\nimport { Health } from './resources/health';\nimport { Hosts } from './resources/hosts';\nimport { Assets } from './resources/assets';\nimport { Images } from './resources/images';\nimport { Music, Renders, Videos } from './resources/media';\nimport { Documents } from './resources/documents';\nimport { Creatives } from './resources/creatives';\nimport { BrandKits } from './resources/brand-kits';\nimport { Templates } from './resources/templates';\nimport { Productions } from './resources/productions';\nimport { MediaOps } from './resources/media-ops';\nimport { LyricsResource } from './resources/lyrics';\nimport { Jam } from './resources/jam';\nimport { Exports } from './resources/exports';\nimport { Batches } from './resources/batches';\nimport { Shares } from './resources/shares';\nimport { VoiceRevocations } from './resources/voice-revocations';\nimport { Vault } from './resources/vault';\nimport { AbuseReports } from './resources/abuse-reports';\nimport { Provenance } from './resources/provenance';\nimport { Messages } from './resources/messages';\nimport { Models } from './resources/models';\nimport { Orgs } from './resources/orgs';\nimport { Projects } from './resources/projects';\nimport { Realtime } from './resources/realtime';\nimport { Referrals } from './resources/referrals';\nimport { Resolve } from './resources/resolve';\nimport { Responses } from './resources/responses';\nimport { Sessions } from './resources/sessions';\nimport { Settings } from './resources/settings';\nimport { OsGate } from './resources/os-gate';\nimport { Sfx } from './resources/sfx';\nimport { SystemOne } from './resources/system-one';\nimport { Tasks } from './resources/tasks';\nimport { Notifications, Triggers } from './resources/triggers';\nimport { Prompts } from './resources/prompts';\nimport { Heartbeats, Schedules } from './resources/schedules';\nimport { Lists } from './resources/lists';\nimport { Memory } from './resources/memory';\nimport { Sandboxes } from './resources/sandboxes';\nimport { Transcripts } from './resources/transcripts';\nimport { type EphemeralScope, type EphemeralToken, Tokens } from './resources/tokens';\nimport { Tools } from './resources/tools';\nimport { Research } from './resources/research';\nimport { Keys, Usage } from './resources/usage-keys';\nimport { Verify } from './resources/verify';\n\nexport interface CodaiClientOptions {\n apiKey: string;\n /** Defaults to https://ai.codai.ro */\n baseUrl?: string;\n /** codai Resolve service host (`client.resolve`). Defaults to https://resolve.codai.ro */\n resolveBaseUrl?: string;\n /** Stable conversation/session id — sent as `x-codai-session-id` on every request. */\n sessionId?: string;\n /** Device UUID for shared-sessions / hosts — sent as `x-codai-device` on every request. */\n device?: string;\n /** Device name / platform recorded on first registration. */\n deviceName?: string;\n devicePlatform?: CodaiRequestExtensions['devicePlatform'];\n /** Client surface tag (`x-codai-client`). */\n client?: string;\n /** Any other default `X-Codai-*` extensions (per-call bags override). */\n defaults?: CodaiRequestExtensions;\n /** Default request timeout (ms). Default 120_000. Streams are not time-capped. */\n timeoutMs?: number;\n /** Retries on 429/5xx with exponential backoff. Default 2. */\n maxRetries?: number;\n /** Injectable fetch (tests / custom agents). */\n fetch?: typeof fetch;\n}\n\n/** 0.2.x-compatible chat options (thin alias over `chat.completions`). */\nexport interface ChatOptions {\n model?: string;\n messages: ChatMessage[];\n temperature?: number;\n maxTokens?: number;\n tools?: ChatCompletionRequest['tools'];\n /** codai extension: plan-and-execute agent mode (Pro+). */\n agentMode?: boolean;\n /** codai extension: server-side context compaction ('auto'). */\n compact?: 'auto';\n /** codai extension: best-of-N override (0 disables, 3 forces). */\n bestOf?: 0 | 3;\n /** Attribution id recorded on tool calls (agent fleets). */\n agentId?: string;\n /** Per-call session override. */\n sessionId?: string;\n /** Any other `X-Codai-*` extension. */\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface EmbeddingsOptions {\n input: string | string[];\n model?: string;\n dimensions?: number;\n signal?: AbortSignal;\n}\n\nexport class Codai {\n readonly http: HttpClient;\n\n /** Resource group (`chat.completions.create/stream`) that is also callable with the 0.2.x `chat({ messages })` shape. */\n readonly chat: Chat & ((opts: ChatOptions) => Promise<ChatResult>);\n readonly messages: Messages;\n readonly responses: Responses;\n readonly embeddings: Embeddings &\n ((opts: EmbeddingsOptions) => Promise<{ embeddings: number[][]; raw: unknown }>);\n /** Image generation and editing (`images.generate({ prompt })`, `images.edit({ prompt, image })`; codai-image = gemini-3.1-flash-image, EU). */\n readonly images: Images;\n readonly audio: Audio;\n /** codai Studio music (`music.generate({ prompt, lyrics?, model? })`; Lyria 3 clip / pro with vocals, Lyria 2 legacy; US-only). */\n readonly music: Music;\n /** codai Studio video jobs (`videos.generate({ prompt })`; Veo 3.1 Fast, US-only, English prompts). */\n readonly videos: Videos;\n /** codai Studio renders (`renders.render({ html })`; HyperFrames HTML → MP4, codai-render, up to 180 s 1080p). */\n readonly renders: Renders;\n /** Stored codai Studio assets (`assets.list()`, `.retrieve(id)`, `.contentUrl(id)`, `.delete(id)`; 1 h signed URLs, kept 90 days). */\n readonly assets: Assets;\n /** codai Studio CC0 sound effects (`sfx.search({ q })`, `sfx.import(sfxId)` → asset `kind: 'sfx'`; free). */\n readonly sfx: Sfx;\n /** codai Studio documents (`documents.create({ type: 'deck', spec })` → PPTX / DOCX / XLSX, codai-docs, free; previews + deck → MP4). */\n readonly documents: Documents;\n /** codai Studio creatives (`creatives.create({ kind: 'video' })`, `.edit(id, { baseSeq, ops })`, `.render(id)`; editable documents with versions, free except renders). */\n readonly creatives: Creatives;\n /** codai Studio brand kits (`brandKits.extract({ url })` → palette + fonts + logo; apply with `creatives.create({ kind, brand_kit_id })`). */\n readonly brandKits: BrandKits;\n /** codai Studio templates (`creatives.saveTemplate(id, { vars })` saves one; `templates.list()`; create with `creatives.create({ kind, template, vars })`). */\n readonly templates: Templates;\n /** codai Studio productions (`productions.run({ brief, language: 'ro' })` → a finished promo video + editable creative). */\n readonly productions: Productions;\n /** codai Studio media operations (`mediaOps.run('audio.separate_stems', { assetIds })` → job; `mediaOps.wait(id)`). */\n readonly mediaOps: MediaOps;\n /** codai Studio lyrics (`lyrics.write({ brief, language: 'ro' })`, `lyrics.align({ creative_id, clip_id, lyrics_text })`). */\n readonly lyrics: LyricsResource;\n /** codai Studio live jam over WebSocket (`jam.connect({ token })` → PCM16 48 kHz stereo; `prompts`, `config`, `play`). */\n readonly jam: Jam;\n /** codai Studio FCPXML exports (`creatives.exportFcpxml(id)` queues one; `exports.wait(id)` polls until the zip is ready). */\n readonly exports: Exports;\n /** codai Studio batches (`batches.create({ source: { template_id }, csv })` → one creative per row; `batches.wait(id)`). */\n readonly batches: Batches;\n /** codai Studio share links from the outside (`shares.get(url)`, `shares.remix(url)`, `shares.comment(url, …)`). */\n readonly shares: Shares;\n /** Public takedown tickets for voices cloned in codai Studio (`voiceRevocations.create({ email, … })`; no key needed). */\n readonly voiceRevocations: VoiceRevocations;\n /** Zero-knowledge credentials vault (`vault.items()`, `vault.use({ handle, mode, action })`, `vault.decide(id, …)`). */\n readonly vault: Vault;\n /** Public abuse reports about codai Studio share / review links (`abuseReports.create({ share_token, … })`; no key needed). */\n readonly abuseReports: AbuseReports;\n /** Public AI-provenance checker (`provenance.check(file)` → C2PA / RIFF INFO / ID3 / MP4 / XMP marks; no key needed). */\n readonly provenance: Provenance;\n /** Typed decisions from codai-s1 (`systemOne.create({ state, questions })`). */\n readonly systemOne: SystemOne;\n readonly tokens: Tokens;\n /** WebSocket realtime sessions (`realtime.connect({ model, language, token })`) — live STT and voice. */\n readonly realtime: Realtime;\n readonly models: Models & (() => Promise<Array<{ id: string }>>);\n readonly health: Health;\n readonly agents: Agents;\n readonly tools: Tools;\n /** Async deep research (`research.run({ question })` → cited report + sources). */\n readonly research: Research;\n /** Typed card data (`cards.weather({ lat, lng })`, `.places({ q })`, `.fx()`, `.unfurl(url)` → `{ block, provenance }`). */\n readonly cards: Cards;\n readonly tasks: Tasks;\n /** Event triggers — webhooks that notify you or start agent sessions. */\n readonly triggers: Triggers;\n /** Inbox of trigger / cloud-task notifications. */\n readonly notifications: Notifications;\n /** Pending prompts — ready-to-paste prompts left for a future chat (handoffs, dated follow-ups). */\n readonly prompts: Prompts;\n /** codai Scheduler — cron / natural-language schedules run on any of your hosts or in the cloud (`schedules.create`, `.executor.claim`). */\n readonly schedules: Schedules;\n /** Lists and the share sheet — save links, text and media to Inbox / Wishlist / Notes or your own lists (`lists.share`). */\n readonly lists: Lists;\n /** Heartbeat monitors — dead-man switches for crons codai does not run (`heartbeats.create({ name, period_s })` → `ping_url`). */\n readonly heartbeats: Heartbeats;\n /** Transcripts — voice recordings → diarized transcripts + insights (feature-flagged per account). */\n readonly transcripts: Transcripts;\n /** Your own usage split by day / key / device / app / platform / model / client / tag. */\n readonly usage: Usage;\n /** Your API keys (device attribution, tags). */\n readonly keys: Keys;\n /** Your persistent memory — the same store as the MCP memory tools (`memory.list/search/create/delete`). */\n readonly memory: Memory;\n readonly sessions: Sessions;\n readonly devices: Devices;\n readonly hosts: Hosts;\n readonly orgs: Orgs;\n readonly projects: Projects;\n readonly environments: Environments;\n /** Agent sandboxes (backend v2 by default) — isolated gVisor workspaces: `sandboxes.create/exec/execStream/files/artifacts/run`. */\n readonly sandboxes: Sandboxes;\n /** EXPERIMENTAL (HIDE, unaudited): verify signed agent outputs. Provenance only. */\n readonly verify: Verify;\n readonly account: Account;\n /** Account-level settings shared by every device (`settings.get()`, `settings.update(partial, { version })`). */\n readonly settings: Settings;\n /** OS protection gate: `osGate.policy()` (org override policy) and `osGate.recordEvent(event)` (audit). */\n readonly osGate: OsGate;\n /** READ-ONLY billing: plan, wallet, invoices, `watchBalance` (pay via the returned links, never via the SDK). */\n readonly billing: Billing;\n /** Referral stats and invitees; `redeem(code)` / `setConsent(bool)` go through `PATCH /v1/account`. */\n readonly referrals: Referrals;\n readonly receipt: Receipts;\n readonly feedback: Feedback &\n ((requestId: string, rating: 1 | -1, comment?: string) => Promise<void>);\n readonly phoneModels: PhoneModels;\n /** codai Resolve — execution-verified bug fixes (separate host, `resolveBaseUrl`). */\n readonly resolve: Resolve;\n\n constructor(opts: CodaiClientOptions) {\n if (!opts.apiKey) throw new Error('Codai: apiKey is required');\n this.http = new HttpClient({\n apiKey: opts.apiKey,\n baseUrl: opts.baseUrl ?? 'https://ai.codai.ro',\n timeoutMs: opts.timeoutMs ?? 120_000,\n maxRetries: opts.maxRetries ?? 2,\n fetch: opts.fetch,\n defaults: {\n ...opts.defaults,\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.device ? { device: opts.device } : {}),\n ...(opts.deviceName ? { deviceName: opts.deviceName } : {}),\n ...(opts.devicePlatform ? { devicePlatform: opts.devicePlatform } : {}),\n ...(opts.client ? { client: opts.client } : {}),\n },\n });\n const http = this.http;\n\n this.messages = new Messages(http);\n this.responses = new Responses(http);\n this.images = new Images(http);\n this.audio = new Audio(http);\n this.music = new Music(http);\n this.videos = new Videos(http);\n this.renders = new Renders(http);\n this.assets = new Assets(http);\n this.sfx = new Sfx(http);\n this.documents = new Documents(http);\n this.creatives = new Creatives(http);\n this.brandKits = new BrandKits(http);\n this.templates = new Templates(http);\n this.productions = new Productions(http);\n this.mediaOps = new MediaOps(http);\n this.lyrics = new LyricsResource(http);\n this.jam = new Jam({ baseUrl: http.baseUrl, apiKey: opts.apiKey });\n this.exports = new Exports(http);\n this.batches = new Batches(http);\n this.shares = new Shares(http);\n this.voiceRevocations = new VoiceRevocations(http);\n this.vault = new Vault(http);\n this.abuseReports = new AbuseReports(http);\n this.provenance = new Provenance(http);\n this.systemOne = new SystemOne(http);\n this.tokens = new Tokens(http);\n this.realtime = new Realtime({ baseUrl: http.baseUrl, apiKey: opts.apiKey });\n this.health = new Health(http);\n this.agents = new Agents(http);\n this.tools = new Tools(http);\n this.research = new Research(http);\n this.cards = new Cards(http);\n this.tasks = new Tasks(http);\n this.triggers = new Triggers(http);\n this.notifications = new Notifications(http);\n this.prompts = new Prompts(http);\n this.schedules = new Schedules(http);\n this.lists = new Lists(http);\n this.heartbeats = new Heartbeats(http);\n this.transcripts = new Transcripts(http);\n this.usage = new Usage(http);\n this.keys = new Keys(http);\n this.memory = new Memory(http);\n this.sessions = new Sessions(http);\n this.devices = new Devices(http);\n this.hosts = new Hosts(http);\n this.orgs = new Orgs(http);\n this.projects = new Projects(http);\n this.environments = new Environments(http);\n this.sandboxes = new Sandboxes(http);\n this.verify = new Verify(http);\n this.account = new Account(http);\n this.settings = new Settings(http);\n this.osGate = new OsGate(http);\n this.billing = new Billing(http);\n this.referrals = new Referrals(http);\n this.receipt = new Receipts(http);\n this.phoneModels = new PhoneModels(http);\n this.resolve = new Resolve(\n new HttpClient({\n apiKey: opts.apiKey,\n baseUrl: opts.resolveBaseUrl ?? 'https://resolve.codai.ro',\n timeoutMs: opts.timeoutMs ?? 120_000,\n maxRetries: opts.maxRetries ?? 2,\n fetch: opts.fetch,\n defaults: opts.client ? { client: opts.client } : {},\n }),\n );\n\n // Callable resources keep the 0.2.x top-level signatures working\n // (`client.embeddings({...})`, `client.models()`, `client.feedback(id, 1)`)\n // while also exposing `.create()` / `.list()` / `.submit()`.\n this.chat = callable(new Chat(http), (o: ChatOptions) =>\n this.chat.completions.create(this.legacyBody(o), {\n ext: this.legacyExt(o),\n signal: o.signal,\n }),\n );\n this.embeddings = callable(new Embeddings(http), async (o: EmbeddingsOptions) => {\n const r = await this.embeddings.create(\n { input: o.input, model: o.model, dimensions: o.dimensions },\n { signal: o.signal },\n );\n return { embeddings: r.embeddings, raw: r.raw };\n });\n this.models = callable(new Models(http), async () =>\n (await this.models.list()).map((m) => ({ id: m.id })),\n );\n this.feedback = callable(\n new Feedback(http),\n async (requestId: string, rating: 1 | -1, comment?: string) => {\n await this.feedback.submit({\n event_id: requestId,\n rating,\n ...(comment ? { comment } : {}),\n });\n },\n );\n }\n\n // ------------------------------------------------- 0.2.x compatibility aliases\n\n /** Alias of `chat.completions.stream()` with the 0.2.x option names. */\n chatStream(opts: ChatOptions): ChatStream {\n return this.chat.completions.stream(this.legacyBody(opts), {\n ext: this.legacyExt(opts),\n signal: opts.signal,\n });\n }\n\n /** Alias of `tokens.create()`. */\n mintToken(scope: EphemeralScope, ttlSeconds?: number): Promise<EphemeralToken> {\n return this.tokens.create(scope, ttlSeconds);\n }\n\n private legacyBody(opts: ChatOptions): ChatCompletionInput {\n return {\n model: opts.model ?? 'codai',\n messages: opts.messages,\n ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),\n ...(opts.maxTokens !== undefined ? { max_tokens: opts.maxTokens } : {}),\n ...(opts.tools ? { tools: opts.tools } : {}),\n };\n }\n\n private legacyExt(opts: ChatOptions): CodaiRequestExtensions {\n return {\n ...opts.ext,\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.agentMode ? { mode: 'agent' as const } : {}),\n ...(opts.compact ? { compact: opts.compact } : {}),\n ...(opts.bestOf !== undefined ? { bestOf: opts.bestOf } : {}),\n ...(opts.agentId ? { agentId: opts.agentId } : {}),\n };\n }\n}\n\n/**\n * Make an object callable: returns a function that forwards calls to `fn`\n * and carries every own/prototype member of `target` (methods bound).\n */\nfunction callable<T extends object, F extends (...args: never[]) => unknown>(\n target: T,\n fn: F,\n): T & F {\n const f = ((...args: Parameters<F>) => fn(...args)) as T & F;\n for (const key of allKeys(target)) {\n const value = (target as Record<string, unknown>)[key];\n Object.defineProperty(f, key, {\n value:\n typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value,\n enumerable: true,\n writable: false,\n });\n }\n return f;\n}\n\nfunction allKeys(obj: object): string[] {\n const keys = new Set<string>();\n let cur: object | null = obj;\n while (cur && cur !== Object.prototype) {\n for (const k of Object.getOwnPropertyNames(cur)) if (k !== 'constructor') keys.add(k);\n cur = Object.getPrototypeOf(cur);\n }\n return [...keys];\n}\n\nexport default Codai;\n\n// ------------------------------------------------------------------ exports\nexport { CodaiError, HttpClient, extensionHeaders, readSse, frameJson } from './http';\nexport type { CodaiRequestExtensions, ErrorCode, SseFrame, RequestOptions } from './http';\nexport { OPERATION_METHODS, STREAMING_OPERATIONS, RESOLVE_OPERATION_METHODS } from './operations';\nexport type { paths, components, operations } from './generated/gateway';\nexport type {\n paths as ResolvePaths,\n components as ResolveComponents,\n operations as ResolveOperations,\n} from './generated/resolve';\n\nexport * from './resources/chat';\nexport * from './resources/messages';\nexport * from './resources/responses';\nexport * from './resources/embeddings';\nexport * from './resources/images';\nexport * from './resources/audio';\nexport * from './resources/media';\nexport * from './resources/assets';\nexport * from './resources/sfx';\nexport * from './resources/documents';\nexport * from './resources/creatives';\nexport * from './resources/brand-kits';\nexport * from './resources/templates';\nexport * from './resources/productions';\nexport * from './resources/media-ops';\nexport * from './resources/lyrics';\nexport * from './resources/jam';\nexport * from './resources/exports';\nexport * from './resources/batches';\nexport * from './resources/shares';\nexport * from './resources/voice-revocations';\nexport * from './resources/vault';\nexport * from './resources/abuse-reports';\nexport * from './resources/provenance';\nexport * from './resources/tokens';\nexport * from './resources/realtime';\nexport * from './resources/system-one';\nexport * from './resources/models';\nexport * from './resources/health';\nexport * from './resources/agents';\nexport * from './resources/tools';\nexport * from './resources/research';\nexport * from './resources/cards';\nexport * from './resources/tasks';\nexport * from './resources/triggers';\nexport * from './resources/prompts';\nexport * from './resources/schedules';\nexport * from './resources/lists';\nexport * from './resources/transcripts';\nexport * from './resources/usage-keys';\nexport * from './resources/memory';\nexport * from './resources/sessions';\nexport * from './resources/devices';\nexport * from './resources/hosts';\nexport * from './resources/orgs';\nexport * from './resources/projects';\nexport * from './resources/environments';\nexport * from './resources/sandboxes';\nexport * from './resources/verify';\nexport * from './resources/account';\nexport * from './resources/settings';\nexport * from './resources/os-gate';\nexport * from './resources/billing';\nexport * from './resources/referrals';\nexport * from './resources/resolve';\nexport * from './resources/apps';\n"],"mappings":";AAWA,IAAa,aAAb,cAAgC,MAAM;CAUlB;CACA;;CATlB,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YACE,SACA,AAAgB,QAChB,AAAgB,MAChB,OAA2F,CAAC,GAC5F;EACA,MAAM,OAAO;EAJG;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S,SACP,QACA,IACO;CACP,MAAM,MAAM,GAAG,SAAwB,GAAG,GAAG,IAAI;CACjD,KAAK,MAAM,OAAO,QAAQ,MAAM,GAAG;EACjC,MAAM,QAAS,OAAmC;EAClD,OAAO,eAAe,GAAG,KAAK;GAC5B,OACE,OAAO,UAAU,aAAc,MAAuC,KAAK,MAAM,IAAI;GACvF,YAAY;GACZ,UAAU;EACZ,CAAC;CACH;CACA,OAAO;AACT;AAEA,SAAS,QAAQ,KAAuB;CACtC,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI,MAAqB;CACzB,OAAO,OAAO,QAAQ,OAAO,WAAW;EACtC,KAAK,MAAM,KAAK,OAAO,oBAAoB,GAAG,GAAG,IAAI,MAAM,eAAe,KAAK,IAAI,CAAC;EACpF,MAAM,OAAO,eAAe,GAAG;CACjC;CACA,OAAO,CAAC,GAAG,IAAI;AACjB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["base64ToBytes","filePath","decodeBase64","abortableSleep","abortableSleep","path","abortableSleep","path","path","path","path","abortableSleep","BASE","abortableSleep","OPEN","path","abortableSleep","abortableSleep","enc","one","one","one"],"sources":["../src/http.ts","../src/resources/_shared.ts","../src/resources/account.ts","../src/resources/agents.ts","../src/resources/audio.ts","../src/resources/billing.ts","../src/resources/cards.ts","../src/resources/chat.ts","../src/resources/devices.ts","../src/resources/embeddings.ts","../src/resources/environments.ts","../src/resources/health.ts","../src/resources/hosts.ts","../src/resources/assets.ts","../src/resources/images.ts","../src/resources/media.ts","../src/resources/documents.ts","../src/resources/exports.ts","../src/resources/creatives.ts","../src/resources/brand-kits.ts","../src/resources/templates.ts","../src/resources/productions.ts","../src/resources/media-ops.ts","../src/resources/lyrics.ts","../src/resources/jam.ts","../src/resources/batches.ts","../src/resources/shares.ts","../src/resources/voice-revocations.ts","../src/resources/vault.ts","../src/resources/abuse-reports.ts","../src/resources/provenance.ts","../src/resources/messages.ts","../src/resources/models.ts","../src/resources/orgs.ts","../src/resources/projects.ts","../src/resources/realtime.ts","../src/resources/referrals.ts","../src/resources/resolve.ts","../src/resources/responses.ts","../src/resources/sessions.ts","../src/resources/settings.ts","../src/resources/os-gate.ts","../src/resources/sfx.ts","../src/resources/system-one.ts","../src/resources/tasks.ts","../src/resources/triggers.ts","../src/resources/prompts.ts","../src/resources/schedules.ts","../src/resources/lists.ts","../src/resources/memory.ts","../src/resources/sandboxes.ts","../src/resources/transcripts.ts","../src/resources/tokens.ts","../src/resources/tools.ts","../src/resources/research.ts","../src/resources/usage-keys.ts","../src/resources/verify.ts","../src/operations.ts","../src/resources/apps.ts","../src/index.ts"],"sourcesContent":["/**\n * Shared HTTP layer for every resource: base URL, bearer auth, `X-Codai-*`\n * extension headers, retries, timeouts, JSON + SSE helpers and the\n * `CodaiError` mapping of the gateway error envelope.\n */\n\nimport type { components } from './generated/gateway';\n\nexport type ErrorEnvelope = components['schemas']['Error'];\nexport type ErrorCode = ErrorEnvelope['error']['code'];\n\nexport class CodaiError extends Error {\n /** Stable gateway error code (`invalid_api_key`, `rate_limit_exceeded`, …) when the body was an error envelope. */\n readonly code: ErrorCode | null;\n /** `x-codai-trace-id` (or `x-request-id`) of the failed response, when present. */\n readonly requestId: string | null;\n /** Seconds to wait before retrying, from `Retry-After` on 429s. */\n readonly retryAfter: number | null;\n\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: unknown,\n meta: { code?: ErrorCode | null; requestId?: string | null; retryAfter?: number | null } = {},\n ) {\n super(message);\n this.name = 'CodaiError';\n this.code = meta.code ?? extractCode(body);\n this.requestId = meta.requestId ?? null;\n this.retryAfter = meta.retryAfter ?? null;\n }\n}\n\nfunction extractCode(body: unknown): ErrorCode | null {\n if (body && typeof body === 'object') {\n const err = (body as { error?: { code?: unknown } }).error;\n if (err && typeof err === 'object' && typeof err.code === 'string')\n return err.code as ErrorCode;\n }\n return null;\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (body && typeof body === 'object') {\n const err = (body as { error?: { message?: unknown } }).error;\n if (err && typeof err === 'object' && typeof err.message === 'string') return err.message;\n }\n return null;\n}\n\nconst RETRYABLE = new Set([429, 500, 502, 503, 504]);\n\n/**\n * Per-request `X-Codai-*` extension headers. Every field maps 1:1 to the\n * request header of the same name (`effort` → `x-codai-effort`). Values are\n * sent verbatim; booleans become `1` / `0`.\n */\nexport interface CodaiRequestExtensions {\n /** `x-codai-session-id` — groups requests of one conversation. */\n sessionId?: string;\n /** `x-request-id` — echoed as `x-codai-trace-id`. */\n requestId?: string;\n /** `x-codai-effort` */\n effort?: 'minimal' | 'low' | 'medium' | 'high' | 'max';\n /** `x-codai-thinking` */\n thinking?: boolean;\n /** `x-codai-thinking-budget` */\n thinkingBudget?: number;\n /** `x-codai-thinking-pin` */\n thinkingPin?: boolean;\n /** `x-codai-cache` (`false` disables caching on direct model ids). */\n cache?: boolean;\n /** `x-codai-no-task` */\n noTask?: boolean;\n /** `x-codai-task-id` */\n taskId?: string;\n /** `x-codai-task-outcome` */\n taskOutcome?: 'pass' | 'fail';\n /** `x-codai-task-evidence` */\n taskEvidence?: 'exec_verdict' | 'reexec';\n /** `x-codai-client` */\n client?: string;\n /** `x-codai-incognito` */\n incognito?: boolean;\n /** `x-codai-no-recall` */\n noRecall?: boolean;\n /** `x-codai-proven-only` */\n provenOnly?: boolean;\n /** `x-codai-new-session` */\n newSession?: boolean;\n /** `x-codai-repo` */\n repo?: string;\n /** `x-codai-agent-id` */\n agentId?: string;\n /** `x-codai-disable-subagents` */\n disableSubagents?: boolean;\n /** `x-codai-mode: agent` */\n mode?: 'agent';\n /** `x-codai-server-tools` */\n serverTools?: boolean;\n /** `x-codai-orchestrate` */\n orchestrate?: boolean;\n /** `x-codai-cascade` */\n cascade?: 'verify';\n /** `x-codai-best-of` (number or `off`). */\n bestOf?: number | 'off';\n /** `x-codai-best-of-depth` */\n bestOfDepth?: number;\n /** `x-codai-reflect` */\n reflect?: boolean;\n /** `x-codai-step-verify` */\n stepVerify?: boolean;\n /** `x-codai-plan` */\n plan?: boolean;\n /** `x-codai-consensus` */\n consensus?: boolean;\n /** `x-codai-compact` (`'auto'` and `true` both send `1`). */\n compact?: boolean | 'auto';\n /** `x-codai-retrieval` */\n retrieval?: boolean;\n /** `x-codai-heuristics` */\n heuristics?: boolean;\n /** `x-codai-identity` */\n identity?: 'on' | 'off' | 'shadow';\n /** `x-codai-playbook` */\n playbook?: string;\n /** `x-codai-no-playbook` */\n noPlaybook?: boolean;\n /** `x-codai-debug` */\n debug?: boolean;\n /** `x-codai-device` — shared-sessions / hosts device UUID. */\n device?: string;\n /** `x-codai-device-name` */\n deviceName?: string;\n /** `x-codai-device-platform` */\n devicePlatform?: 'android' | 'ios' | 'web' | 'desktop' | 'cli' | 'agent' | 'wear' | 'vscode';\n /** `x-codai-push-token` */\n pushToken?: string;\n /** `x-codai-share-token` */\n shareToken?: string;\n /**\n * `Idempotency-Key` — billed codai Studio POSTs (videos, music, renders, timelines, documents, creatives, batches):\n * a retry with the same key and body replays the first answer instead of charging twice (24 h).\n */\n idempotencyKey?: string;\n /** Escape hatch: any additional raw headers. */\n headers?: Record<string, string>;\n}\n\nconst EXTENSION_HEADERS: Record<Exclude<keyof CodaiRequestExtensions, 'headers'>, string> = {\n sessionId: 'x-codai-session-id',\n requestId: 'x-request-id',\n effort: 'x-codai-effort',\n thinking: 'x-codai-thinking',\n thinkingBudget: 'x-codai-thinking-budget',\n thinkingPin: 'x-codai-thinking-pin',\n cache: 'x-codai-cache',\n noTask: 'x-codai-no-task',\n taskId: 'x-codai-task-id',\n taskOutcome: 'x-codai-task-outcome',\n taskEvidence: 'x-codai-task-evidence',\n client: 'x-codai-client',\n incognito: 'x-codai-incognito',\n noRecall: 'x-codai-no-recall',\n provenOnly: 'x-codai-proven-only',\n newSession: 'x-codai-new-session',\n repo: 'x-codai-repo',\n agentId: 'x-codai-agent-id',\n disableSubagents: 'x-codai-disable-subagents',\n mode: 'x-codai-mode',\n serverTools: 'x-codai-server-tools',\n orchestrate: 'x-codai-orchestrate',\n cascade: 'x-codai-cascade',\n bestOf: 'x-codai-best-of',\n bestOfDepth: 'x-codai-best-of-depth',\n reflect: 'x-codai-reflect',\n stepVerify: 'x-codai-step-verify',\n plan: 'x-codai-plan',\n consensus: 'x-codai-consensus',\n compact: 'x-codai-compact',\n retrieval: 'x-codai-retrieval',\n heuristics: 'x-codai-heuristics',\n identity: 'x-codai-identity',\n playbook: 'x-codai-playbook',\n noPlaybook: 'x-codai-no-playbook',\n debug: 'x-codai-debug',\n device: 'x-codai-device',\n deviceName: 'x-codai-device-name',\n devicePlatform: 'x-codai-device-platform',\n pushToken: 'x-codai-push-token',\n shareToken: 'x-codai-share-token',\n idempotencyKey: 'Idempotency-Key',\n};\n\n/** Translate an extensions bag into raw `X-Codai-*` headers. Exported for tests. */\nexport function extensionHeaders(ext: CodaiRequestExtensions | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!ext) return out;\n for (const [key, header] of Object.entries(EXTENSION_HEADERS) as Array<\n [Exclude<keyof CodaiRequestExtensions, 'headers'>, string]\n >) {\n const value = ext[key];\n if (value === undefined || value === null) continue;\n if (typeof value === 'boolean') out[header] = value ? '1' : '0';\n else if (key === 'compact' && value === 'auto') out[header] = '1';\n else out[header] = String(value);\n }\n if (ext.headers) Object.assign(out, ext.headers);\n return out;\n}\n\nexport interface HttpClientOptions {\n apiKey: string;\n baseUrl: string;\n timeoutMs: number;\n maxRetries: number;\n /** Extensions applied to every request (per-call bags override per key). */\n defaults?: CodaiRequestExtensions;\n /** Injectable fetch (defaults to the global one). */\n fetch?: typeof fetch;\n}\n\nexport type Query = Record<string, string | number | boolean | undefined | null>;\n\nexport interface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\n /** Extra raw headers for this call (e.g. tus `Upload-Offset`); applied last. */\n headers?: Record<string, string>;\n /** JSON body (serialised) — pass `undefined` for no body. */\n body?: unknown;\n /** A pre-built body (FormData / Blob) sent as-is; disables retries. */\n rawBody?: BodyInit;\n query?: Query;\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n /** Override the client timeout for this call (ms). `0` disables it (streams). */\n timeoutMs?: number;\n /** Never retry this call (multipart uploads, streams). */\n noRetry?: boolean;\n /** Statuses treated as success besides 2xx (e.g. 503 on `/health/ready`). */\n acceptStatus?: number[];\n}\n\nexport class HttpClient {\n readonly apiKey: string;\n readonly baseUrl: string;\n readonly timeoutMs: number;\n readonly maxRetries: number;\n readonly defaults: CodaiRequestExtensions;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: HttpClientOptions) {\n this.apiKey = opts.apiKey;\n this.baseUrl = opts.baseUrl.replace(/\\/$/, '');\n this.timeoutMs = opts.timeoutMs;\n this.maxRetries = opts.maxRetries;\n this.defaults = opts.defaults ?? {};\n this.fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));\n }\n\n url(path: string, query?: Query): string {\n const url = new URL(`${this.baseUrl}${path}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined || v === null) continue;\n url.searchParams.set(k, typeof v === 'boolean' ? (v ? '1' : '0') : String(v));\n }\n }\n return url.toString();\n }\n\n headers(ext?: CodaiRequestExtensions, json = true): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n ...(json ? { 'Content-Type': 'application/json' } : {}),\n ...extensionHeaders(this.defaults),\n ...extensionHeaders(ext),\n };\n }\n\n /** Perform a request; throws `CodaiError` on non-2xx (after retries on 429/5xx). */\n async request(path: string, init: RequestOptions = {}): Promise<Response> {\n const url = this.url(path, init.query);\n const hasJson = init.body !== undefined;\n const headers = { ...this.headers(init.ext, hasJson), ...init.headers };\n const method = init.method ?? (hasJson || init.rawBody !== undefined ? 'POST' : 'GET');\n const retries = init.noRetry || init.rawBody !== undefined ? 0 : this.maxRetries;\n const timeout = init.timeoutMs ?? this.timeoutMs;\n const accept = new Set(init.acceptStatus ?? []);\n let lastErr: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n const signal = init.signal ?? (timeout > 0 ? AbortSignal.timeout(timeout) : undefined);\n try {\n const res = await this.fetchImpl(url, {\n method,\n headers,\n ...(hasJson ? { body: JSON.stringify(init.body) } : {}),\n ...(init.rawBody !== undefined ? { body: init.rawBody } : {}),\n ...(signal ? { signal } : {}),\n });\n if (res.ok || accept.has(res.status)) return res;\n if (RETRYABLE.has(res.status) && attempt < retries) {\n await sleep(500 * 2 ** attempt + Math.random() * 250);\n continue;\n }\n throw await this.toError(path, res);\n } catch (err) {\n if (err instanceof CodaiError) throw err;\n lastErr = err;\n // Caller aborts are never retried.\n if (init.signal?.aborted) throw err;\n if (attempt < retries) {\n await sleep(500 * 2 ** attempt);\n continue;\n }\n }\n }\n throw new CodaiError(`codai ${path} failed after retries: ${String(lastErr)}`, 0, null);\n }\n\n async json<T>(path: string, init: RequestOptions = {}): Promise<T> {\n const res = await this.request(path, init);\n return (await res.json()) as T;\n }\n\n /**\n * Open a `text/event-stream` and iterate parsed frames. Frames are\n * `\\n\\n`-separated blocks; each yields `{ event, data }` where `event`\n * defaults to `message` and `data` is the joined `data:` payload (raw\n * string — the caller decides whether it is JSON or `[DONE]`). Comment\n * lines (`: ping`) are skipped. The stream is retried like any request\n * up to the first byte; after that errors propagate.\n */\n async *sse(\n path: string,\n init: RequestOptions = {},\n ): AsyncGenerator<SseFrame, Response, undefined> {\n const res = await this.request(path, {\n ...init,\n timeoutMs: init.timeoutMs ?? 0,\n noRetry: true,\n });\n yield* readSse(res, init.signal);\n return res;\n }\n\n private async toError(path: string, res: Response): Promise<CodaiError> {\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n /* non-JSON error body */\n }\n const retryAfterRaw = res.headers.get('retry-after');\n const retryAfter = retryAfterRaw && /^\\d+$/.test(retryAfterRaw) ? Number(retryAfterRaw) : null;\n const message = extractMessage(body);\n return new CodaiError(\n message ? `codai ${path} → ${res.status}: ${message}` : `codai ${path} → ${res.status}`,\n res.status,\n body,\n {\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n retryAfter,\n },\n );\n }\n}\n\nexport interface SseFrame {\n /** `event:` name; `message` when the frame has none (OpenAI-style streams). */\n event: string;\n /** Joined `data:` lines (a multi-line data block is joined with `\\n`). */\n data: string;\n}\n\n/** Parse an SSE body into frames. Exported for the resources and for tests. */\nexport async function* readSse(res: Response, signal?: AbortSignal): AsyncGenerator<SseFrame> {\n const reader = res.body?.getReader();\n if (!reader) throw new CodaiError('no response body', res.status, null);\n const decoder = new TextDecoder();\n let buffer = '';\n const onAbort = () => void reader.cancel().catch(() => {});\n signal?.addEventListener('abort', onAbort, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n // Normalise CRLF so both `\\n\\n` and `\\r\\n\\r\\n` delimit frames.\n buffer = buffer.replace(/\\r\\n/g, '\\n');\n const blocks = buffer.split('\\n\\n');\n buffer = blocks.pop() ?? '';\n for (const block of blocks) {\n const frame = parseSseBlock(block);\n if (frame) yield frame;\n }\n }\n const tail = buffer.trim() ? parseSseBlock(buffer) : null;\n if (tail) yield tail;\n } finally {\n signal?.removeEventListener('abort', onAbort);\n reader.releaseLock?.();\n }\n}\n\nfunction parseSseBlock(block: string): SseFrame | null {\n let event = 'message';\n const data: string[] = [];\n for (const line of block.split('\\n')) {\n if (!line || line.startsWith(':')) continue;\n if (line.startsWith('event:')) event = line.slice(6).trim();\n else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));\n // `id:` / `retry:` are never emitted by the gateway; ignore anything else.\n }\n if (data.length === 0) return null;\n return { event, data: data.join('\\n') };\n}\n\n/** Parse a frame's data as JSON, returning `null` for `[DONE]` / non-JSON. */\nexport function frameJson<T = unknown>(frame: SseFrame): T | null {\n if (frame.data === '[DONE]') return null;\n try {\n return JSON.parse(frame.data) as T;\n } catch {\n return null;\n }\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n","/** Type helpers over the generated OpenAPI types shared by every resource. */\nimport type { components, operations } from '../generated/gateway';\n\nexport type Schemas = components['schemas'];\nexport type Schema<K extends keyof Schemas> = Schemas[K];\n\n/** JSON request body of an operation. */\nexport type Body<Op extends keyof operations> = operations[Op] extends {\n requestBody?: { content: { 'application/json': infer B } };\n}\n ? B\n : never;\n\n/** JSON response body of an operation for a given status (default 200). */\nexport type Reply<\n Op extends keyof operations,\n Status extends keyof operations[Op]['responses'] = 200 extends keyof operations[Op]['responses']\n ? 200\n : keyof operations[Op]['responses'],\n> = operations[Op]['responses'][Status] extends {\n content: { 'application/json': infer R };\n}\n ? R\n : never;\n\n/** Query parameters of an operation. */\nexport type QueryOf<Op extends keyof operations> = operations[Op]['parameters'] extends {\n query?: infer Q;\n}\n ? NonNullable<Q>\n : never;\n\n/**\n * Strip the `readonly` modifiers that `--immutable` adds, so callers can\n * build request bodies with plain mutable objects.\n */\nexport type Mutable<T> =\n T extends ReadonlyArray<infer U>\n ? Array<Mutable<U>>\n : T extends object\n ? { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\nexport function stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) if (v !== undefined) out[k] = v;\n return out as T;\n}\n","/** `/v1/account`, `/v1/receipt`, `/v1/feedback`, `/v1/phone/models`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type AccountView = Reply<'getAccount'>;\nexport type AccountPatchRequest = Mutable<Body<'patchAccount'>>;\nexport type AccountPatchResponse = Reply<'patchAccount'>;\nexport type Receipt = Reply<'getReceipt'>;\nexport type FeedbackRequest = Mutable<Body<'submitFeedback'>>;\nexport type FeedbackResponse = Reply<'submitFeedback'>;\nexport type PhoneModel = Schema<'AccountPhoneModel'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Account {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/account` — the full account card. */\n get(opts: CallOpts = {}): Promise<AccountView> {\n return this.http.json<AccountView>('/v1/account', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/account` — consents, username, referral (at least one field). */\n update(body: AccountPatchRequest, opts: CallOpts = {}): Promise<AccountPatchResponse> {\n return this.http.json<AccountPatchResponse>('/v1/account', {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Receipts {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `GET /v1/receipt` — spend receipt. `sessionId` wins over `since`; with\n * neither, the last 24 hours.\n */\n get(\n query: { sessionId?: string; since?: string | Date } = {},\n opts: CallOpts = {},\n ): Promise<Receipt> {\n return this.http.json<Receipt>('/v1/receipt', {\n query: {\n session_id: query.sessionId,\n since: query.since instanceof Date ? query.since.toISOString() : query.since,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Feedback {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/feedback` — rate one turn. Exactly one of `event_id`,\n * `session_id`, `client_request_id` must be present.\n */\n submit(body: FeedbackRequest, opts: CallOpts = {}): Promise<FeedbackResponse> {\n return this.http.json<FeedbackResponse>('/v1/feedback', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class PhoneModels {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/phone/models` — on-device model catalog with signed URLs. */\n async list(opts: CallOpts = {}): Promise<PhoneModel[]> {\n const raw = await this.http.json<Reply<'listPhoneModels'>>('/v1/phone/models', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.models ?? [])];\n }\n}\n","/** `/v1/agents/*` — synchronous runs and the persisted async run lifecycle. */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type AgentRunRequest = Mutable<Body<'runAgentSync'>>;\nexport type AgentRunCreateRequest = Mutable<Body<'createAgentRun'>>;\nexport type AgentSyncResult = Reply<'runAgentSync'>;\nexport type AgentRunAccepted = Reply<'createAgentRun', 202>;\nexport type AgentRun = Reply<'getAgentRun'>;\nexport type AgentRunStep = Schema<'AgentRunStep'>;\nexport type AgentRunStats = Reply<'getAgentRunStats'>;\nexport type AgentRunStatus = Schema<'AgentRunStatus'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface AgentRunResult {\n result: string;\n model: string;\n /** Usage-event id — exact target for `feedback.submit`. */\n eventId: string | null;\n usage: AgentSyncResult['usage'] | null;\n raw: AgentSyncResult;\n headers: Headers;\n}\n\n/** SSE frames of `GET /v1/agents/runs/{id}/stream`. */\nexport type AgentRunStreamEvent =\n | {\n event: 'step';\n data: {\n seq: number;\n kind: 'plan' | 'tool_call' | 'observation' | 'answer';\n summary: string | null;\n };\n }\n | {\n event: 'done';\n data: {\n status: 'completed' | 'failed' | 'cancelled';\n result: string | null;\n error: string | null;\n step_count: number;\n };\n }\n | { event: 'timeout'; data: Record<string, never> };\n\nexport class AgentRuns {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/agents/runs` — returns 202 with the run id. */\n create(body: AgentRunCreateRequest, opts: CallOpts = {}): Promise<AgentRunAccepted> {\n return this.http.json<AgentRunAccepted>('/v1/agents/runs', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/agents/runs/{id}` */\n get(id: string, opts: CallOpts = {}): Promise<AgentRun> {\n return this.http.json<AgentRun>(`/v1/agents/runs/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/agents/runs/{id}/steps` — newest first. */\n async steps(id: string, opts: CallOpts = {}): Promise<AgentRunStep[]> {\n const raw = await this.http.json<Reply<'listAgentRunSteps'>>(\n `/v1/agents/runs/${encodeURIComponent(id)}/steps`,\n { ext: opts.ext, signal: opts.signal },\n );\n return [...(raw.steps ?? [])];\n }\n\n /** `GET /v1/agents/runs/stats?days=` */\n stats(days?: number, opts: CallOpts = {}): Promise<AgentRunStats> {\n return this.http.json<AgentRunStats>('/v1/agents/runs/stats', {\n query: { days },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/agents/runs/{id}/cancel` */\n cancel(id: string, opts: CallOpts = {}): Promise<Reply<'cancelAgentRun'>> {\n return this.http.json<Reply<'cancelAgentRun'>>(\n `/v1/agents/runs/${encodeURIComponent(id)}/cancel`,\n { method: 'POST', body: {}, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /**\n * `GET /v1/agents/runs/{id}/stream` — async iterator over `step` / `done` /\n * `timeout` events. The iterator ends after `done`; on `timeout` (30 min)\n * it also ends and you may reconnect (full replay from seq 0).\n */\n async *stream(\n id: string,\n opts: CallOpts = {},\n ): AsyncGenerator<AgentRunStreamEvent, void, undefined> {\n const frames = this.http.sse(`/v1/agents/runs/${encodeURIComponent(id)}/stream`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data) continue;\n const ev = { event: frame.event, data } as AgentRunStreamEvent;\n yield ev;\n if (ev.event === 'done' || ev.event === 'timeout') return;\n }\n }\n}\n\nexport class Agents {\n readonly runs: AgentRuns;\n constructor(private readonly http: HttpClient) {\n this.runs = new AgentRuns(http);\n }\n\n /** `POST /v1/agents/run` — blocks until the agent loop finishes. */\n async run(body: AgentRunRequest, opts: CallOpts = {}): Promise<AgentRunResult> {\n const res = await this.http.request('/v1/agents/run', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as AgentSyncResult;\n return {\n result: String(raw.result ?? ''),\n model: String(raw.model ?? ''),\n eventId: raw.event_id ?? res.headers.get('x-codai-event-id'),\n usage: raw.usage ?? null,\n raw,\n headers: res.headers,\n };\n }\n}\n","/** `POST /v1/audio/transcriptions`, `POST /v1/audio/speech` and `POST /v1/audio/speech/stream`. */\nimport { type CodaiRequestExtensions, type HttpClient, frameJson } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type TranscriptionResponse = Reply<'createTranscription'>;\nexport type SpeechRequest = Mutable<Body<'createSpeech'>>;\nexport type SpeechStreamRequest = Mutable<Body<'createSpeechStream'>>;\n/** One word timing of a `speechJson()` result (seconds from the start of the audio). */\nexport type SpeechWord = Schema<'SpeechWord'>;\n/** JSON shape of `POST /v1/audio/speech` when `timestamps` or `store` is true. */\nexport type SpeechJson = Schema<'SpeechJson'>;\n\n/** One event of `audio.speechStream()` (Azure neural TTS with lip-sync timing). */\nexport type SpeechStreamEvent =\n | {\n type: 'start';\n model: string;\n voice: string;\n format: 'pcm' | 'mp3';\n content_type: string;\n sample_rate: number;\n }\n /** `delta` is base64; `audio` is the decoded bytes (PCM16 LE mono 24 kHz for `pcm`). */\n | { type: 'audio'; delta: string; audio: Uint8Array }\n /** Azure viseme id (0-21) at `offsetMs` on the audio timeline. */\n | { type: 'viseme'; id: number; offsetMs: number }\n | { type: 'word'; text: string; offsetMs: number; durationMs: number }\n | {\n type: 'done';\n audio_ms: number | null;\n audioBytes: number;\n visemes: number;\n words: number;\n }\n | { type: 'error'; error: { code: string; message: string } };\n/** Raw generated event schema (all fields optional). */\nexport type SpeechStreamEventSchema = Schema<'SpeechStreamEvent'>;\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nexport interface TranscriptionOptions {\n /** Audio file contents (max 25 MB). */\n file: Blob | Uint8Array | ArrayBuffer;\n /** Filename hint (extension drives format detection). Default `audio.webm`. */\n filename?: string;\n /** Default `codai-transcribe`. */\n model?: string;\n /** ISO-639-1 language hint. */\n language?: string;\n /** Text to guide style or spelling. */\n prompt?: string;\n /** `json` (default) or `verbose_json`. */\n responseFormat?: 'json' | 'verbose_json';\n /** Sampling temperature 0–1. */\n temperature?: number;\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface TranscriptionResult {\n text: string;\n raw: TranscriptionResponse;\n routedTo: string | null;\n headers: Headers;\n}\n\nexport interface SpeechResult {\n /** Raw audio bytes in the requested format (mp3 by default). */\n audio: ArrayBuffer;\n /** Upstream `content-type` (`audio/mpeg` when the upstream sent none). */\n contentType: string;\n routedTo: string | null;\n headers: Headers;\n}\n\nexport interface SpeechJsonResult {\n /** Decoded audio bytes (empty when `store: true` — use `asset.url`). */\n audio: Uint8Array;\n /** Word timings (`timestamps: true`); `null` when not requested or the timing pass failed. */\n words: SpeechWord[] | null;\n /** The stored studio asset (`store: true`), referenceable as `asset:<asset_id>` in renders. */\n asset: SpeechJson['asset'] | null;\n durationSeconds: number;\n /** Upstream cost of the request in micro-USD. */\n costMicroUsd: number | null;\n /** True when `timestamps` was requested but the gateway answered `x-codai-timestamps: unavailable`. */\n timestampsUnavailable: boolean;\n raw: SpeechJson;\n routedTo: string | null;\n headers: Headers;\n}\n\nexport class Audio {\n constructor(private readonly http: HttpClient) {}\n\n /** Speech-to-text (multipart upload; never retried). Returns the transcript (0.2.x shape). */\n async transcribe(opts: TranscriptionOptions): Promise<string> {\n return (await this.transcribeDetailed(opts)).text;\n }\n\n /** Speech-to-text with the raw upstream JSON and routing headers. */\n async transcribeDetailed(opts: TranscriptionOptions): Promise<TranscriptionResult> {\n const form = new FormData();\n const blob = opts.file instanceof Blob ? opts.file : new Blob([opts.file as BlobPart]);\n form.append('file', blob, opts.filename ?? 'audio.webm');\n form.append('model', opts.model ?? 'codai-transcribe');\n if (opts.language) form.append('language', opts.language);\n if (opts.prompt) form.append('prompt', opts.prompt);\n if (opts.responseFormat) form.append('response_format', opts.responseFormat);\n if (opts.temperature !== undefined) form.append('temperature', String(opts.temperature));\n const res = await this.http.request('/v1/audio/transcriptions', {\n method: 'POST',\n rawBody: form,\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as TranscriptionResponse;\n return {\n text: typeof raw.text === 'string' ? raw.text : '',\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n /** Text-to-speech. Returns the raw audio bytes (0.2.x shape); see `speechDetailed()` for headers. */\n async speech(\n body: Omit<SpeechRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ArrayBuffer> {\n return (await this.speechDetailed(body, opts)).audio;\n }\n\n /** Text-to-speech with the upstream `content-type` and routing headers. */\n async speechDetailed(\n body: Omit<SpeechRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SpeechResult> {\n const model = body.model ?? 'codai-tts';\n // codai-speech* pick their own default (Aoede / Kore); `alloy` is an Azure voice name.\n const voice = body.voice ?? (model.startsWith('codai-speech') ? undefined : 'alloy');\n const res = await this.http.request('/v1/audio/speech', {\n body: { ...body, model, ...(voice === undefined ? {} : { voice }) },\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n audio: await res.arrayBuffer(),\n contentType: res.headers.get('content-type') ?? 'audio/mpeg',\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n /**\n * Text-to-speech with JSON output: per-word timings (`timestamps`, default true here) and/or a stored studio\n * asset (`store`). Works for every speech model; `codai-speech` (Chirp 3 HD) and `codai-speech-expressive`\n * (Gemini TTS, honours `instructions`) speak Romanian natively (`language`, default `ro-RO`).\n */\n async speechJson(\n body: Omit<SpeechRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SpeechJsonResult> {\n const timestamps = body.timestamps ?? (body.store ? undefined : true);\n const res = await this.http.request('/v1/audio/speech', {\n body: {\n ...body,\n model: body.model ?? 'codai-speech',\n ...(timestamps === undefined ? {} : { timestamps }),\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as SpeechJson;\n const cost = raw.cost_micro_usd ?? res.headers.get('x-codai-cost-micro-usd');\n return {\n audio: raw.b64_json ? base64ToBytes(raw.b64_json) : new Uint8Array(0),\n words: raw.words ? [...raw.words] : null,\n asset: raw.asset ?? null,\n durationSeconds: raw.duration_seconds,\n costMicroUsd: cost === null || cost === undefined ? null : Number(cost),\n timestampsUnavailable: res.headers.get('x-codai-timestamps') === 'unavailable',\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n /**\n * Streaming neural TTS with visemes + word boundaries (`codai-tts-ro`, Azure AI Speech).\n * Yields `start`, then `audio` / `viseme` / `word` in synthesis order, then `done` (or `error`).\n * Voices: `alina` (default), `emil`, or any Azure neural voice name. Default format `pcm`\n * (PCM16 mono 24 kHz). Works with an ephemeral token of scope `audio` or `live`.\n */\n async *speechStream(\n body: SpeechStreamRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): AsyncGenerator<SpeechStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/audio/speech/stream', {\n body: { ...body, model: body.model ?? 'codai-tts-ro' },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data || typeof data.type !== 'string') continue;\n if (data.type === 'audio' && typeof data.delta === 'string') {\n yield { type: 'audio', delta: data.delta, audio: base64ToBytes(data.delta) };\n continue;\n }\n yield data as SpeechStreamEvent;\n if (data.type === 'done' || data.type === 'error') return;\n }\n }\n}\n","/**\n * `/v1/billing`, `/v1/billing/invoices`, `/v1/studio/quote` — READ-ONLY billing overview and Studio price quotes.\n *\n * Nothing here starts a payment: plan, top-up and portal actions are browser\n * links in `Billing.links` (open them; the SDK never creates checkout sessions).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type BillingOverview = Reply<'getBilling'>;\nexport type BillingPlan = Schema<'BillingPlan'>;\nexport type BillingWallet = Schema<'BillingWallet'>;\nexport type BillingAutoTopup = Schema<'BillingAutoTopup'>;\nexport type BillingPaymentMethod = Schema<'BillingPaymentMethod'>;\nexport type BillingLinks = Schema<'BillingLinks'>;\nexport type BillingInvoice = Schema<'BillingInvoice'>;\nexport type BillingInvoiceList = Reply<'listBillingInvoices'>;\nexport type StudioQuote = Reply<'getStudioQuote'>;\n\n/** `GET /v1/studio/quote` parameters: `action` picks the price function, the rest are its inputs. */\nexport interface StudioQuoteQuery {\n action: 'video' | 'music' | 'render' | 'preview' | 'frames' | 'captions' | 'speech' | 'image';\n seconds?: number;\n resolution?: '720p' | '1080p';\n audio?: boolean;\n quality?: 'draft' | 'final';\n pages?: number;\n chars?: number;\n model?: string;\n n?: number;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface WatchBalanceOptions {\n /** Call `onLow` when `wallet.balance_eur` drops below this (EUR). */\n thresholdEur: number;\n /** Poll interval (ms). Default 60_000, minimum 1_000. */\n intervalMs?: number;\n /** Stops the watcher (same as calling the returned function). */\n signal?: AbortSignal;\n /**\n * Called once per crossing below the threshold (again only after the\n * balance went back to >= threshold). Read `billing.links.topup` to offer a\n * top-up link; the watcher itself never pays.\n */\n onLow: (balanceEur: number, billing: BillingOverview) => void | Promise<void>;\n /** Called when a poll fails; polling continues. Default: ignore. */\n onError?: (err: unknown) => void;\n}\n\nexport class Billing {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/billing` — plan, wallet, auto top-up, cards and pay links (read-only). */\n get(opts: CallOpts = {}): Promise<BillingOverview> {\n return this.http.json<BillingOverview>('/v1/billing', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/billing/invoices` — fiscal invoices and credit notes, newest first. */\n async invoices(query: { limit?: number } = {}, opts: CallOpts = {}): Promise<BillingInvoice[]> {\n const raw = await this.http.json<BillingInvoiceList>('/v1/billing/invoices', {\n query: { limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...raw.invoices];\n }\n\n /**\n * `GET /v1/studio/quote` — what a Studio action costs (USD and wallet EUR micros) and your spendable balance,\n * before you run it. Paid Studio calls answer 402 `insufficient_funds` when `sufficient` is false. Free.\n */\n studioQuote(query: StudioQuoteQuery, opts: CallOpts = {}): Promise<StudioQuote> {\n return this.http.json<StudioQuote>('/v1/studio/quote', {\n // The gateway reads `audio` as the literal `true` / `false` (the client would send 1 / 0 for a boolean).\n query: { ...query, audio: query.audio === undefined ? undefined : String(query.audio) },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Poll `get()` every `intervalMs` and call `onLow` once each time the wallet\n * balance crosses below `thresholdEur`. Read-only: never creates a checkout.\n * Returns a function that stops the watcher.\n */\n watchBalance(opts: WatchBalanceOptions): () => void {\n const intervalMs = Math.max(1_000, opts.intervalMs ?? 60_000);\n const ctrl = new AbortController();\n const stop = () => ctrl.abort();\n if (opts.signal) {\n if (opts.signal.aborted) stop();\n else opts.signal.addEventListener('abort', stop, { once: true });\n }\n let low = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tick = async (): Promise<void> => {\n if (ctrl.signal.aborted) return;\n try {\n const billing = await this.get({ signal: ctrl.signal });\n const balance = billing.wallet.balance_eur;\n if (balance < opts.thresholdEur) {\n if (!low) {\n low = true;\n await opts.onLow(balance, billing);\n }\n } else low = false;\n } catch (err) {\n if (!ctrl.signal.aborted) opts.onError?.(err);\n }\n if (!ctrl.signal.aborted) timer = setTimeout(() => void tick(), intervalMs);\n };\n ctrl.signal.addEventListener('abort', () => clearTimeout(timer), { once: true });\n void tick();\n return stop;\n }\n}\n","/**\n * `/v1/cards/*` — server-side DATA for typed cards (`@codai/cards`). Every JSON method returns `{ block, provenance }`\n * where `block` is already a valid card block (weather, places, map, metric, table or links) that can be dropped into\n * a card unchanged; `staticMap` returns PNG bytes.\n *\n * Weather and FX are free. Places, geocode and static maps are Google calls billed to your usage at Google's list price\n * (Places text/nearby $0.032, geocoding $0.005, static map $0.002) and limited per user per UTC day (200 Places,\n * 500 maps); `unfurl` and `product` are free but share a limit of 500 fetches per day (cache hits do not count). Maps methods throw a 503\n * `CodaiError` with code `maps_not_configured` when the gateway has no maps key — fall back to text.\n *\n * `render` turns a `chart` or `qr` block into a PNG or SVG on the gateway (free, 2000 per day) for surfaces that\n * cannot draw cards; Mermaid / math blocks throw a 422 `CodaiError` with code `render_unsupported`.\n *\n * `route` is Google Routes travel time (billed: $0.010 traffic-aware driving, $0.005 walk/bike/transit; maps limit).\n * `track` follows a parcel (Sameday live; FAN Courier, Cargus, DPD only when the gateway has their contract) and\n * `efactura` lists your fiscal documents issued through Brivio with their ANAF e-Factura status; both free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type QueryOf, type Reply, type Schema } from './_shared';\n\n/** `{ block, provenance }` (+ `results` for geocode) as returned by every JSON card endpoint. */\nexport type CardDataResponse = Schema<'CardDataResponse'>;\nexport type CardsWeatherParams = QueryOf<'cardsWeather'>;\nexport type CardsPlacesParams = QueryOf<'cardsPlaces'>;\nexport type CardsGeocodeParams = QueryOf<'cardsGeocode'>;\nexport type CardsStaticMapParams = QueryOf<'cardsStaticMap'>;\nexport type CardsFxParams = QueryOf<'cardsFx'>;\nexport type CardsRouteParams = QueryOf<'cardsRoute'>;\nexport type CardsTrackParams = QueryOf<'cardsTrack'>;\nexport type CardsEfacturaParams = QueryOf<'cardsEfactura'>;\nexport type CardsUnfurlBody = Body<'cardsUnfurl'>;\nexport type CardsProductBody = Body<'cardsProduct'>;\nexport type CardsRenderBody = Body<'cardsRender'>;\nexport type CardsWeatherResponse = Reply<'cardsWeather'>;\nexport type CardsPlacesResponse = Reply<'cardsPlaces'>;\nexport type CardsGeocodeResponse = Reply<'cardsGeocode'>;\nexport type CardsFxResponse = Reply<'cardsFx'>;\nexport type CardsRouteResponse = Reply<'cardsRoute'>;\nexport type CardsTrackResponse = Reply<'cardsTrack'>;\nexport type CardsEfacturaResponse = Reply<'cardsEfactura'>;\nexport type CardsUnfurlResponse = Reply<'cardsUnfurl'>;\nexport type CardsProductResponse = Reply<'cardsProduct'>;\n\n/** A rendered static map: PNG bytes plus the attribution the gateway sent (`x-codai-attribution`). */\nexport interface CardsStaticMap {\n bytes: Uint8Array;\n contentType: string;\n attribution: string | null;\n}\n\n/** A rendered card block: image bytes, `image/png` or `image/svg+xml`, and the pixel size (`x-codai-render-size`). */\nexport interface CardsRendered {\n bytes: Uint8Array;\n contentType: string;\n width: number | null;\n height: number | null;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\ntype Q = Record<string, string | number | boolean | undefined | null>;\n\nexport class Cards {\n constructor(private readonly http: HttpClient) {}\n\n private get<T>(path: string, query: object, opts: CallOpts): Promise<T> {\n return this.http.json<T>(path, { query: query as Q, ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/cards/weather` — `weather` block from MET Norway (cached 30–60 min per 0.01°, free). */\n weather(params: CardsWeatherParams, opts: CallOpts = {}): Promise<CardsWeatherResponse> {\n return this.get('/v1/cards/weather', params, opts);\n }\n\n /**\n * `GET /v1/cards/places` — `places` block from Google Places: Text Search with `q` (biased to `lat`/`lng`/`radius`),\n * Nearby Search without it. Billed per call; `block` is null when nothing matched.\n */\n places(params: CardsPlacesParams, opts: CallOpts = {}): Promise<CardsPlacesResponse> {\n return this.get('/v1/cards/places', params, opts);\n }\n\n /** `GET /v1/cards/geocode` — `map` block (≤ 5 markers) plus raw `results` (Google Geocoding, billed). */\n geocode(params: CardsGeocodeParams, opts: CallOpts = {}): Promise<CardsGeocodeResponse> {\n return this.get('/v1/cards/geocode', params, opts);\n }\n\n /**\n * `GET /v1/cards/static-map` — PNG from Google Maps Static proxied through the gateway (no maps key on the client).\n * Needs `center` or `markers` (`lat,lng[,L]` joined by `|`); ≤ 640×400 points. Billed per call.\n */\n async staticMap(params: CardsStaticMapParams, opts: CallOpts = {}): Promise<CardsStaticMap> {\n const res = await this.http.request('/v1/cards/static-map', {\n query: params as Q,\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n contentType: res.headers.get('content-type') ?? 'image/png',\n attribution: res.headers.get('x-codai-attribution'),\n };\n }\n\n /**\n * `GET /v1/cards/fx` — BNR (default) or ECB reference rates: a `metric` block with `from`+`to`, otherwise a `table`\n * block against `quote`, optionally limited to `symbols` (comma-separated). Free.\n */\n fx(params: CardsFxParams = {}, opts: CallOpts = {}): Promise<CardsFxResponse> {\n return this.get('/v1/cards/fx', params, opts);\n }\n\n /**\n * `GET /v1/cards/route` — travel time from Google Routes: `route` { mode, durationS, staticDurationS, distanceM,\n * polyline } and a `map` block. `origin`/`destination` as \"lat,lng\" or `from`/`to` as addresses; `mode` drive\n * (traffic-aware, default), walk, bicycle, transit, two_wheeler. Billed per call; both null when no route exists.\n */\n route(params: CardsRouteParams, opts: CallOpts = {}): Promise<CardsRouteResponse> {\n return this.get('/v1/cards/route', params, opts);\n }\n\n /**\n * `GET /v1/cards/track` — parcel history as a `timeline` block plus `result` (carrier, configured, found,\n * delivered, events, trackingUrl). `carrier` (sameday | fan | cargus | dpd) is guessed from the AWB when omitted;\n * carriers without gateway credentials answer `configured: false` with only the tracking link. Free.\n */\n track(params: CardsTrackParams, opts: CallOpts = {}): Promise<CardsTrackResponse> {\n return this.get('/v1/cards/track', params, opts);\n }\n\n /**\n * `GET /v1/cards/efactura` — your fiscal documents issued through Brivio with their ANAF e-Factura status\n * (`documents[]` + a `table` block, null when there are none). Free.\n */\n efactura(params: CardsEfacturaParams = {}, opts: CallOpts = {}): Promise<CardsEfacturaResponse> {\n return this.get('/v1/cards/efactura', params, opts);\n }\n\n /**\n * `POST /v1/cards/unfurl` — `links` block (variant `preview`) for a public https page; SSRF-guarded, cached 24 h.\n * Private targets throw 400 `unfurl_blocked`, non-https pages 422 `unfurl_not_https`.\n */\n unfurl(url: string, opts: CallOpts = {}): Promise<CardsUnfurlResponse> {\n const body: CardsUnfurlBody = { url };\n return this.http.json<CardsUnfurlResponse>('/v1/cards/unfurl', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/cards/product` — `products` block with one item from a public https product page's schema.org\n * `Product` JSON-LD (or OpenGraph product tags): name, image, price + currency (lowest offer), old price, rating\n * (0–5), reviews, seller, availability badge in `lang` (en default). Only what the page states; never sponsored.\n * SSRF-guarded like `unfurl`, cached 6 h. No product data throws 422 `product_not_found`.\n */\n product(url: string, lang?: 'en' | 'ro', opts: CallOpts = {}): Promise<CardsProductResponse> {\n const body: CardsProductBody = lang ? { url, lang } : { url };\n return this.http.json<CardsProductResponse>('/v1/cards/product', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/cards/render` — renders a `chart` or `qr` block to `format` (`png` default, or `svg`) at\n * `width` x `height` CSS px (64–1200, defaults 480 x 300; QR is square) times `scale` (1–3, PNG only).\n * Other block types (Mermaid `diagram`, `math`, …) throw 422 `render_unsupported`. Free; 2000 renders per day.\n */\n async render(body: CardsRenderBody, opts: CallOpts = {}): Promise<CardsRendered> {\n const res = await this.http.request('/v1/cards/render', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n const size = /^(\\d+)x(\\d+)$/.exec(res.headers.get('x-codai-render-size') ?? '');\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n contentType: res.headers.get('content-type') ?? 'image/png',\n width: size ? Number(size[1]) : null,\n height: size ? Number(size[2]) : null,\n };\n }\n}\n","/** `POST /v1/chat/completions` — OpenAI-compatible completions (JSON + SSE). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient, readSse } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type ChatCompletionRequest = Mutable<Body<'createChatCompletion'>>;\n/** Request body as accepted by the SDK: `stream` is set by the method and `model` defaults to `codai`. */\nexport type ChatCompletionInput = Omit<ChatCompletionRequest, 'stream' | 'model'> & {\n model?: string;\n};\nexport type ChatCompletionResponse = Reply<'createChatCompletion'>;\nexport type ChatMessage = Mutable<Schema<'ChatMessage'>>;\nexport type ChatTool = Mutable<Schema<'ChatTool'>>;\nexport type ChatToolCall = Mutable<Schema<'ChatToolCall'>>;\nexport type ChatUsage = Schema<'ChatUsage'>;\n\nexport interface TokenUsage {\n promptTokens: number;\n completionTokens: number;\n /** Prompt tokens served from the provider cache, when reported. */\n cachedTokens?: number;\n}\n\n/** Per-call options accepted by every chat method. */\nexport interface ChatCallOptions {\n /** `X-Codai-*` extension headers for this call. */\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface ChatResult {\n /** Assistant message content (first choice). */\n content: string;\n /** Tool calls on the first choice (empty if none). */\n toolCalls: ChatToolCall[];\n /** Raw OpenAI-shaped response. */\n raw: ChatCompletionResponse;\n /** Request id (`x-codai-trace-id` / `x-request-id`) — pass to `feedback`. */\n requestId: string | null;\n /** Usage-event id (`x-codai-event-id`) — exact target for `feedback.submit`. */\n eventId: string | null;\n /** Which upstream model actually served (`x-codai-routed-to`). */\n routedTo: string | null;\n /** Verification status for verified-execution responses, if present. */\n execVerify: string | null;\n usage: TokenUsage | null;\n /** Response headers, for the long tail of `x-codai-*` metadata. */\n headers: Headers;\n}\n\n/** Final metadata for a completed stream — resolved via `stream.final`. */\nexport interface ChatStreamResult {\n content: string;\n toolCalls: ChatToolCall[];\n requestId: string | null;\n routedTo: string | null;\n execVerify: string | null;\n usage: TokenUsage | null;\n /** `finish_reason` of the last content chunk, when sent. */\n finishReason: string | null;\n headers: Headers | null;\n}\n\n/**\n * A live chat stream. Async-iterate it for text deltas, then await `.final`\n * for metadata. `.chunks()` yields the raw `chat.completion.chunk` objects.\n */\nexport interface ChatStream extends AsyncIterable<string> {\n readonly final: Promise<ChatStreamResult>;\n chunks(): AsyncIterable<ChatCompletionChunk>;\n}\n\nexport interface ChatCompletionChunk {\n id?: string;\n object?: 'chat.completion.chunk';\n model?: string;\n choices?: Array<{\n index?: number;\n delta?: {\n role?: string;\n content?: string | null;\n tool_calls?: Array<{ index?: number } & Record<string, unknown>>;\n };\n finish_reason?: string | null;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n };\n [key: string]: unknown;\n}\n\nfunction toUsage(u: ChatCompletionChunk['usage'] | undefined): TokenUsage | null {\n if (!u) return null;\n const cached = u.prompt_tokens_details?.cached_tokens;\n return {\n promptTokens: u.prompt_tokens ?? 0,\n completionTokens: u.completion_tokens ?? 0,\n ...(cached !== undefined ? { cachedTokens: cached } : {}),\n };\n}\n\n/**\n * Merge a streamed tool-call fragment into the accumulator at `index`.\n * OpenAI streams tool calls piecewise: id/name arrive first, then the\n * `arguments` string is appended across many deltas.\n */\nexport function mergeToolCall(\n acc: Map<number, Record<string, unknown>>,\n index: number,\n fragment: Record<string, unknown>,\n): void {\n const existing = acc.get(index) ?? { index };\n for (const [key, val] of Object.entries(fragment)) {\n if (key === 'index') continue;\n if (key === 'function' && val && typeof val === 'object') {\n const fn = (existing.function as Record<string, unknown>) ?? {};\n for (const [fk, fv] of Object.entries(val as Record<string, unknown>)) {\n if (fk === 'arguments') fn.arguments = String(fn.arguments ?? '') + String(fv ?? '');\n else fn[fk] = fv;\n }\n existing.function = fn;\n } else {\n existing[key] = val;\n }\n }\n acc.set(index, existing);\n}\n\nexport class ChatCompletions {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Non-streaming completion. `stream` is forced to `false`; use\n * `stream()` for SSE.\n */\n async create(body: ChatCompletionInput, opts: ChatCallOptions = {}): Promise<ChatResult> {\n const res = await this.http.request('/v1/chat/completions', {\n body: { ...body, model: body.model ?? 'codai', stream: false },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as ChatCompletionResponse;\n const first = raw.choices?.[0];\n const usage = raw.usage as ChatCompletionChunk['usage'] | undefined;\n return {\n content: typeof first?.message?.content === 'string' ? first.message.content : '',\n toolCalls: [...((first?.message?.tool_calls ?? []) as ChatToolCall[])],\n raw,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n eventId: res.headers.get('x-codai-event-id'),\n routedTo: res.headers.get('x-codai-routed-to'),\n execVerify: res.headers.get('x-codai-exec-verify'),\n usage: toUsage(usage),\n headers: res.headers,\n };\n }\n\n /** Streaming completion (`stream: true`). */\n stream(body: ChatCompletionInput, opts: ChatCallOptions = {}): ChatStream {\n const requestPromise = this.http.request('/v1/chat/completions', {\n body: { ...body, model: body.model ?? 'codai', stream: true },\n ext: opts.ext,\n signal: opts.signal,\n timeoutMs: 0,\n noRetry: true,\n });\n\n let resolveFinal!: (r: ChatStreamResult) => void;\n let rejectFinal!: (e: unknown) => void;\n const final = new Promise<ChatStreamResult>((resolve, reject) => {\n resolveFinal = resolve;\n rejectFinal = reject;\n });\n final.catch(() => {}); // no unhandled-rejection noise when `final` is never awaited\n\n const toolCallsByIndex = new Map<number, Record<string, unknown>>();\n let content = '';\n let usage: TokenUsage | null = null;\n let finishReason: string | null = null;\n let res: Response | null = null;\n\n const buildResult = (): ChatStreamResult => ({\n content,\n toolCalls: [...toolCallsByIndex.values()] as ChatToolCall[],\n requestId: res?.headers.get('x-codai-trace-id') ?? res?.headers.get('x-request-id') ?? null,\n routedTo: res?.headers.get('x-codai-routed-to') ?? null,\n execVerify: res?.headers.get('x-codai-exec-verify') ?? null,\n usage,\n finishReason,\n headers: res?.headers ?? null,\n });\n\n async function* chunks(): AsyncGenerator<ChatCompletionChunk, void, undefined> {\n try {\n res = await requestPromise;\n for await (const frame of readSse(res, opts.signal)) {\n if (frame.data === '[DONE]') break;\n const chunk = frameJson<ChatCompletionChunk>(frame);\n if (!chunk) continue;\n if (chunk.usage) usage = toUsage(chunk.usage);\n const choice = chunk.choices?.[0];\n if (choice?.finish_reason) finishReason = choice.finish_reason;\n const delta = choice?.delta;\n if (delta?.tool_calls) {\n for (const tc of delta.tool_calls) {\n mergeToolCall(toolCallsByIndex, typeof tc.index === 'number' ? tc.index : 0, tc);\n }\n }\n if (delta?.content) content += delta.content;\n yield chunk;\n }\n resolveFinal(buildResult());\n } catch (err) {\n rejectFinal(err);\n throw err;\n }\n }\n\n async function* text(): AsyncGenerator<string, void, undefined> {\n for await (const chunk of chunks()) {\n const delta = chunk.choices?.[0]?.delta?.content;\n if (delta) yield delta;\n }\n }\n\n return {\n [Symbol.asyncIterator]: () => text(),\n chunks: () => ({ [Symbol.asyncIterator]: () => chunks() }),\n final,\n };\n }\n}\n\nexport class Chat {\n readonly completions: ChatCompletions;\n constructor(http: HttpClient) {\n this.completions = new ChatCompletions(http);\n }\n}\n","/** `/v1/devices/*` — devices bound to your account + the aggregated dispatch inbox. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Device = Schema<'DeviceListItem'>;\nexport type DevicePatch = Mutable<Body<'updateDevice'>>;\nexport type DevicePatched = Reply<'updateDevice'>;\nexport type DispatchInbox = Reply<'getMyDispatchInbox'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Devices {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/devices` — most recently seen first. */\n async list(opts: CallOpts = {}): Promise<Device[]> {\n const raw = await this.http.json<Reply<'listDevices'>>('/v1/devices', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.devices ?? [])];\n }\n\n /** `PATCH /v1/devices/{id}` — push token and/or capabilities. */\n update(id: string, body: DevicePatch, opts: CallOpts = {}): Promise<DevicePatched> {\n return this.http.json<DevicePatched>(`/v1/devices/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/devices/{id}` */\n delete(id: string, opts: CallOpts = {}): Promise<Reply<'deleteDevice'>> {\n return this.http.json<Reply<'deleteDevice'>>(`/v1/devices/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/keys/self/revoke` — the API key this client uses revokes ITSELF (sign out).\n * Every later call with it fails with 401.\n */\n revokeSelfKey(opts: CallOpts = {}): Promise<Reply<'revokeSelfKey'>> {\n return this.http.json<Reply<'revokeSelfKey'>>('/v1/keys/self/revoke', {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/devices/me/dispatch?limit=` — pending controls dispatched at the\n * calling device (`x-codai-device` required) across all owned sessions.\n */\n dispatchInbox(query: { limit?: number } = {}, opts: CallOpts = {}): Promise<DispatchInbox> {\n return this.http.json<DispatchInbox>('/v1/devices/me/dispatch', {\n query: { limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `POST /v1/embeddings`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type EmbeddingsRequest = Mutable<Body<'createEmbeddings'>>;\nexport type EmbeddingsResponse = Reply<'createEmbeddings'>;\n\nexport interface EmbeddingsResult {\n /** One vector per input, in order. */\n embeddings: number[][];\n raw: EmbeddingsResponse;\n /** Upstream embedding model that produced the vectors (`x-codai-routed-to`). */\n routedTo: string | null;\n /** `<requested>-><served>` when a different model was substituted; vectors live in another space. */\n fallback: string | null;\n headers: Headers;\n}\n\nexport class Embeddings {\n constructor(private readonly http: HttpClient) {}\n\n async create(\n body: Omit<EmbeddingsRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<EmbeddingsResult> {\n const res = await this.http.request('/v1/embeddings', {\n body: { ...body, model: body.model ?? 'codai-embed' },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as EmbeddingsResponse;\n return {\n embeddings: (raw.data ?? []).map((d) => [...(d.embedding as readonly number[])]),\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n fallback: res.headers.get('x-codai-embed-fallback'),\n headers: res.headers,\n };\n }\n}\n","/** `/v1/environments/*` — cloud / BYO dev environments, their members, ports and secrets. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Environment = Schema<'Environment'>;\nexport type EnvironmentDetail = Schema<'EnvironmentDetail'>;\nexport type EnvironmentState = Schema<'EnvironmentState'>;\nexport type EnvironmentProvider = Schema<'EnvironmentProvider'>;\nexport type EnvironmentRole = Schema<'EnvironmentRole'>;\nexport type EnvironmentTransition = Schema<'EnvironmentTransition'>;\nexport type EnvironmentEnrollToken = Schema<'EnvironmentEnrollToken'>;\nexport type EnvironmentEnrolled = Schema<'EnvironmentEnrolled'>;\nexport type EnvironmentMember = Schema<'EnvironmentMember'>;\nexport type EnvironmentMemberCreated = Schema<'EnvironmentMemberCreated'>;\nexport type EnvironmentPort = Schema<'EnvironmentPort'>;\nexport type EnvironmentSecret = Schema<'EnvironmentSecret'>;\nexport type EnvironmentSecretSet = Schema<'EnvironmentSecretSet'>;\nexport type EnvironmentCreateBody = Mutable<Body<'createEnvironment'>>;\nexport type EnvironmentPatchBody = Mutable<Body<'updateEnvironment'>>;\nexport type EnvironmentEnrollBody = Mutable<Body<'enrollEnvironment'>>;\nexport type EnvironmentAddMemberBody = Mutable<Body<'addEnvironmentMember'>>;\nexport type EnvironmentPortBody = Mutable<Body<'setEnvironmentPort'>>;\nexport type ListEnvironmentsQuery = Mutable<QueryOf<'listEnvironments'>>;\nexport type EnvironmentSshCert = Reply<'issueMyEnvironmentSshCert'>;\nexport type EnvironmentSshCertBody = Mutable<Body<'issueMyEnvironmentSshCert'>>;\nexport type EnvironmentSshCa = Reply<'getEnvironmentSshCa'>;\nexport type EnvironmentTaskList = Reply<'listEnvironmentTasks'>;\nexport type EnvironmentTaskCreateBody = Mutable<Body<'createEnvironmentTask'>>;\nexport type EnvironmentTaskCreated = Reply<'createEnvironmentTask'>;\nexport type EnvironmentTaskDetail = Reply<'getEnvironmentTask'>;\nexport type EnvironmentExecBody = Mutable<Body<'execEnvironment'>>;\nexport type EnvironmentExecResult = Schema<'EnvironmentExecResult'>;\nexport type EnvironmentFileList = Schema<'EnvironmentFileList'>;\nexport type EnvironmentFile = Schema<'EnvironmentFile'>;\nexport type EnvironmentFileWritten = Schema<'EnvironmentFileWritten'>;\nexport type EnvironmentJobStartBody = Mutable<Body<'startEnvironmentJob'>>;\nexport type EnvironmentJobStarted = Schema<'EnvironmentJobStarted'>;\nexport type EnvironmentJob = Schema<'EnvironmentJob'>;\nexport type GetEnvironmentJobQuery = Mutable<QueryOf<'getEnvironmentJob'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst envPath = (id: string, suffix = ''): string =>\n `/v1/environments/${encodeURIComponent(id)}${suffix}`;\n\n/** Absolute environment path → `/files/<each segment URL-encoded>`. */\nconst filePath = (path: string): string =>\n path\n .replace(/^\\/+/, '')\n .split('/')\n .map((s) => encodeURIComponent(s))\n .join('/');\n\nexport class EnvironmentMembers {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/members` — any role. */\n async list(envId: string, opts: CallOpts = {}): Promise<EnvironmentMember[]> {\n const raw = await this.http.json<Reply<'listEnvironmentMembers'>>(envPath(envId, '/members'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.members ?? [])];\n }\n\n /** `POST /v1/environments/{id}/members` — exactly one of `user_id` / `email`. */\n async add(\n envId: string,\n body: EnvironmentAddMemberBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentMemberCreated> {\n const raw = await this.http.json<Reply<'addEnvironmentMember', 201>>(\n envPath(envId, '/members'),\n { body, ext: opts.ext, signal: opts.signal },\n );\n return raw.member;\n }\n\n /** `PUT /v1/environments/{id}/members/me/ssh-key` — one `authorized_keys` line. */\n setSshKey(\n envId: string,\n publicKey: string,\n opts: CallOpts = {},\n ): Promise<Reply<'setMyEnvironmentSshKey'>> {\n const body: Mutable<Body<'setMyEnvironmentSshKey'>> = { public_key: publicKey };\n return this.http.json<Reply<'setMyEnvironmentSshKey'>>(envPath(envId, '/members/me/ssh-key'), {\n method: 'PUT',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/environments/{id}/members/{userId}` — 409 `last_owner` on demoting the last owner. */\n async setRole(\n envId: string,\n userId: string,\n role: EnvironmentRole,\n opts: CallOpts = {},\n ): Promise<Reply<'setEnvironmentMemberRole'>['member']> {\n const raw = await this.http.json<Reply<'setEnvironmentMemberRole'>>(\n envPath(envId, `/members/${encodeURIComponent(userId)}`),\n { method: 'PATCH', body: { role }, ext: opts.ext, signal: opts.signal },\n );\n return raw.member;\n }\n\n /** `DELETE /v1/environments/{id}/members/{userId}` — pass your own id to leave. */\n remove(\n envId: string,\n userId: string,\n opts: CallOpts = {},\n ): Promise<Reply<'removeEnvironmentMember'>> {\n return this.http.json<Reply<'removeEnvironmentMember'>>(\n envPath(envId, `/members/${encodeURIComponent(userId)}`),\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `POST /v1/environments/{id}/members/me/ssh-cert` — 12 h OpenSSH user certificate for your key. */\n sshCert(\n envId: string,\n body: EnvironmentSshCertBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentSshCert> {\n return this.http.json<EnvironmentSshCert>(envPath(envId, '/members/me/ssh-cert'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n\n/** `/v1/environments/{id}/tasks` — fire-and-forget agent tasks run in the environment. */\nexport class EnvironmentTasks {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/tasks` */\n list(envId: string, opts: CallOpts = {}): Promise<EnvironmentTaskList> {\n return this.http.json<EnvironmentTaskList>(envPath(envId, '/tasks'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/environments/{id}/tasks` — queued; you get a notification when it finishes. */\n create(\n envId: string,\n body: EnvironmentTaskCreateBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentTaskCreated> {\n return this.http.json<EnvironmentTaskCreated>(envPath(envId, '/tasks'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}/tasks/{taskId}` */\n get(envId: string, taskId: string, opts: CallOpts = {}): Promise<EnvironmentTaskDetail> {\n return this.http.json<EnvironmentTaskDetail>(\n envPath(envId, `/tasks/${encodeURIComponent(taskId)}`),\n { ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\n/** `/v1/environments/{id}/files` — read/write/list over the relay (developer role or higher). */\nexport class EnvironmentFiles {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/files?path=` — directory entries; no path → your workspace. */\n list(envId: string, path?: string, opts: CallOpts = {}): Promise<EnvironmentFileList> {\n return this.http.json<EnvironmentFileList>(envPath(envId, '/files'), {\n query: { path },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/environments/{id}/files/{path}` — UTF-8 text (64 KB default, `maxBytes` ≤ 512 KB). */\n get(\n envId: string,\n path: string,\n options: { maxBytes?: number } & CallOpts = {},\n ): Promise<EnvironmentFile> {\n return this.http.json<EnvironmentFile>(envPath(envId, `/files/${filePath(path)}`), {\n query: { max_bytes: options.maxBytes },\n ext: options.ext,\n signal: options.signal,\n });\n }\n\n /** `PUT /v1/environments/{id}/files/{path}` — replace with UTF-8 text (≤ 2 MB). */\n put(\n envId: string,\n path: string,\n content: string,\n opts: CallOpts = {},\n ): Promise<EnvironmentFileWritten> {\n return this.http.json<EnvironmentFileWritten>(envPath(envId, `/files/${filePath(path)}`), {\n method: 'PUT',\n rawBody: content,\n headers: { 'Content-Type': 'text/plain; charset=utf-8' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** `/v1/environments/{id}/jobs` — background jobs on the environment daemon. */\nexport class EnvironmentJobs {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/environments/{id}/jobs` — returns at once with `job_id`. */\n start(\n envId: string,\n body: EnvironmentJobStartBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentJobStarted> {\n return this.http.json<EnvironmentJobStarted>(envPath(envId, '/jobs'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}/jobs/{jobId}` — status + output (`since` = previous `next_offset`). */\n get(\n envId: string,\n jobId: string | number,\n query: GetEnvironmentJobQuery = {},\n opts: CallOpts = {},\n ): Promise<EnvironmentJob> {\n return this.http.json<EnvironmentJob>(\n envPath(envId, `/jobs/${encodeURIComponent(String(jobId))}`),\n {\n query: { since: query.since, tail: query.tail, session: query.session },\n ext: opts.ext,\n signal: opts.signal,\n },\n );\n }\n}\n\nexport class EnvironmentPorts {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/ports` — published (forwarded) ports. */\n async list(envId: string, opts: CallOpts = {}): Promise<EnvironmentPort[]> {\n const raw = await this.http.json<Reply<'listEnvironmentPorts'>>(envPath(envId, '/ports'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.ports ?? [])];\n }\n\n /** `PUT /v1/environments/{id}/ports/{port}` — publish or change visibility (upsert). */\n async set(\n envId: string,\n port: number,\n body: EnvironmentPortBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentPort> {\n const raw = await this.http.json<Reply<'setEnvironmentPort'>>(\n envPath(envId, `/ports/${encodeURIComponent(String(port))}`),\n { method: 'PUT', body, ext: opts.ext, signal: opts.signal },\n );\n return raw.port;\n }\n\n /** `DELETE /v1/environments/{id}/ports/{port}` — unpublish. */\n remove(\n envId: string,\n port: number,\n opts: CallOpts = {},\n ): Promise<Reply<'removeEnvironmentPort'>> {\n return this.http.json<Reply<'removeEnvironmentPort'>>(\n envPath(envId, `/ports/${encodeURIComponent(String(port))}`),\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class EnvironmentSecrets {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/environments/{id}/secrets` — names and timestamps only, never values. */\n async list(envId: string, opts: CallOpts = {}): Promise<EnvironmentSecret[]> {\n const raw = await this.http.json<Reply<'listEnvironmentSecrets'>>(envPath(envId, '/secrets'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.secrets ?? [])];\n }\n\n /** `PUT /v1/environments/{id}/secrets/{name}` — upsert; `name` is `ENV_STYLE`. */\n set(\n envId: string,\n name: string,\n value: string,\n opts: CallOpts = {},\n ): Promise<EnvironmentSecretSet> {\n const body: Mutable<Body<'setEnvironmentSecret'>> = { value };\n return this.http.json<EnvironmentSecretSet>(\n envPath(envId, `/secrets/${encodeURIComponent(name)}`),\n { method: 'PUT', body, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `DELETE /v1/environments/{id}/secrets/{name}` */\n remove(\n envId: string,\n name: string,\n opts: CallOpts = {},\n ): Promise<Reply<'removeEnvironmentSecret'>> {\n return this.http.json<Reply<'removeEnvironmentSecret'>>(\n envPath(envId, `/secrets/${encodeURIComponent(name)}`),\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class Environments {\n readonly members: EnvironmentMembers;\n readonly ports: EnvironmentPorts;\n readonly secrets: EnvironmentSecrets;\n readonly tasks: EnvironmentTasks;\n readonly files: EnvironmentFiles;\n readonly jobs: EnvironmentJobs;\n\n constructor(private readonly http: HttpClient) {\n this.members = new EnvironmentMembers(http);\n this.ports = new EnvironmentPorts(http);\n this.secrets = new EnvironmentSecrets(http);\n this.tasks = new EnvironmentTasks(http);\n this.files = new EnvironmentFiles(http);\n this.jobs = new EnvironmentJobs(http);\n }\n\n /**\n * `POST /v1/environments/{id}/exec` — run one relay op and wait (developer+). `op` defaults to\n * `shell` with `command`; 409 `environment_offline`, 504 `host_timeout`.\n */\n exec(\n envId: string,\n body: EnvironmentExecBody,\n opts: CallOpts = {},\n ): Promise<EnvironmentExecResult> {\n return this.http.json<EnvironmentExecResult>(envPath(envId, '/exec'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}/ssh-ca` — CA public keys to trust (`@cert-authority` lines). */\n sshCa(envId: string, opts: CallOpts = {}): Promise<EnvironmentSshCa> {\n return this.http.json<EnvironmentSshCa>(envPath(envId, '/ssh-ca'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/environments?project_id=&for_user_id=me` — newest first, every state. */\n async list(query: ListEnvironmentsQuery = {}, opts: CallOpts = {}): Promise<Environment[]> {\n const raw = await this.http.json<Reply<'listEnvironments'>>('/v1/environments', {\n query: { project_id: query.project_id, for_user_id: query.for_user_id },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.environments ?? [])];\n }\n\n /**\n * `POST /v1/environments` — `byo` starts `pending`; managed providers start\n * `creating`. 409 `already_has_env` in a `vm_per_dev` project (the error\n * body carries the `environment_id` to reuse).\n */\n async create(body: EnvironmentCreateBody, opts: CallOpts = {}): Promise<Environment> {\n const raw = await this.http.json<Reply<'createEnvironment', 201>>('/v1/environments', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return raw.environment;\n }\n\n /**\n * `POST /v1/environments/enroll` — daemon side. The one-time `codai_env_…`\n * token in the body is the only credential; the client's API key header is\n * ignored by this route. Managed environments additionally receive a\n * freshly minted `api_key`, returned exactly once.\n */\n enroll(body: EnvironmentEnrollBody, opts: CallOpts = {}): Promise<EnvironmentEnrolled> {\n return this.http.json<EnvironmentEnrolled>('/v1/environments/enroll', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n // The token is consumed on success; a retried POST would 401.\n noRetry: true,\n });\n }\n\n /** `GET /v1/environments/{id}` — environment, your role, members, ports, recent events. */\n get(envId: string, opts: CallOpts = {}): Promise<EnvironmentDetail> {\n return this.http.json<EnvironmentDetail>(envPath(envId), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/environments/{id}` — `name` and/or `idle_timeout_minutes` (5..1440). */\n async update(\n envId: string,\n body: EnvironmentPatchBody,\n opts: CallOpts = {},\n ): Promise<Environment> {\n const raw = await this.http.json<Reply<'updateEnvironment'>>(envPath(envId), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n return raw.environment;\n }\n\n /** `POST /v1/environments/{id}/start` — managed providers only (`stopped` → `starting`). */\n start(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'start', opts);\n }\n\n /** `POST /v1/environments/{id}/stop` — managed providers only (`running` → `stopping`). */\n stop(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'stop', opts);\n }\n\n /** `POST /v1/environments/{id}/archive` — keeps history, releases the machine. */\n archive(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'archive', opts);\n }\n\n /** `POST /v1/environments/{id}/destroy` — owner only; terminal. */\n destroy(envId: string, opts: CallOpts = {}): Promise<EnvironmentTransition> {\n return this.transition(envId, 'destroy', opts);\n }\n\n /**\n * `POST /v1/environments/{id}/enroll-token` — `byo` only; a 30-minute\n * one-time token for `enroll()`. Minting again replaces the previous one.\n */\n enrollToken(envId: string, opts: CallOpts = {}): Promise<EnvironmentEnrollToken> {\n return this.http.json<EnvironmentEnrollToken>(envPath(envId, '/enroll-token'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n private transition(\n envId: string,\n action: 'start' | 'stop' | 'archive' | 'destroy',\n opts: CallOpts,\n ): Promise<EnvironmentTransition> {\n return this.http.json<EnvironmentTransition>(envPath(envId, `/${action}`), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** Unauthenticated probes at the root: `/health`, `/health/ready`, `/status`. */\nimport { type HttpClient } from '../http';\nimport { type Reply } from './_shared';\n\nexport type HealthResponse = Reply<'getHealth'>;\nexport type HealthReadyResponse = Reply<'getHealthReady'>;\nexport type StatusResponse = Reply<'getStatus'>;\n\nexport class Health {\n constructor(private readonly http: HttpClient) {}\n\n /** Liveness probe. */\n get(opts: { signal?: AbortSignal } = {}): Promise<HealthResponse> {\n return this.http.json<HealthResponse>('/health', { signal: opts.signal, noRetry: true });\n }\n\n /**\n * Deep readiness probe. A 503 is returned as `{ ok: false, ... }` rather\n * than thrown, so callers can read the failing check.\n */\n async ready(\n opts: { signal?: AbortSignal } = {},\n ): Promise<HealthReadyResponse & { httpStatus: number }> {\n const res = await this.http.request('/health/ready', {\n signal: opts.signal,\n noRetry: true,\n acceptStatus: [503],\n });\n const body = (await res.json()) as HealthReadyResponse;\n return { ...body, httpStatus: res.status };\n }\n\n /** Registry snapshot (aliases + provider health). */\n status(opts: { signal?: AbortSignal } = {}): Promise<StatusResponse> {\n return this.http.json<StatusResponse>('/status', { signal: opts.signal, noRetry: true });\n }\n}\n","/** `/v1/hosts/*` — host relay (desktop announces itself; clients exec ops on it). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type HostPresence = Schema<'HostPresence'>;\nexport type HostOp = Schema<'HostOp'>;\nexport type HostExecBody = Mutable<Body<'execOnHost'>>;\nexport type HostExecResponse = Reply<'execOnHost'>;\nexport type HostExecRequest = Schema<'HostExecRequest'>;\nexport type HostExecResultBody = Mutable<Body<'postHostExecResult'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\n/** Frames of `GET /v1/hosts/stream`. */\nexport type HostStreamEvent =\n | { event: 'hello'; data: { device_id: string; heartbeat_ms: number } }\n | { event: 'ping'; data: { t: number } }\n | { event: 'exec'; data: HostExecRequest }\n | { event: string; data: Record<string, unknown> };\n\nexport class Hosts {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/hosts` — your devices currently connected as hosts. */\n async list(opts: CallOpts = {}): Promise<HostPresence[]> {\n const raw = await this.http.json<Reply<'listHosts'>>('/v1/hosts', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.hosts ?? [])];\n }\n\n /**\n * `POST /v1/hosts/{deviceId}/exec` — run one op on a connected host and\n * block until it answers (or `timeout_ms`, default 60 s).\n */\n exec(\n deviceId: string,\n op: HostOp,\n args: Record<string, unknown> = {},\n extra: { timeoutMs?: number; label?: string } & CallOpts = {},\n ): Promise<HostExecResponse> {\n const body: HostExecBody = {\n op,\n args,\n ...(extra.timeoutMs !== undefined ? { timeout_ms: extra.timeoutMs } : {}),\n ...(extra.label !== undefined ? { label: extra.label } : {}),\n };\n return this.http.json<HostExecResponse>(`/v1/hosts/${encodeURIComponent(deviceId)}/exec`, {\n body,\n ext: extra.ext,\n signal: extra.signal,\n // The gateway itself waits up to timeout_ms + 2 s; give the HTTP layer headroom.\n timeoutMs: (extra.timeoutMs ?? 60_000) + 10_000,\n noRetry: true,\n });\n }\n\n /** `POST /v1/hosts/exec/{reqId}/result` — host side: deliver an exec result. */\n postResult(\n reqId: string,\n body: HostExecResultBody,\n opts: CallOpts = {},\n ): Promise<Reply<'postHostExecResult'>> {\n return this.http.json<Reply<'postHostExecResult'>>(\n `/v1/hosts/exec/${encodeURIComponent(reqId)}/result`,\n { body, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /**\n * `GET /v1/hosts/stream?os=&hostname=&roots=` — host side: announce this\n * device and receive `hello` / `ping` / `exec` events. Closed by the server\n * after 6 h; reconnect to re-announce presence.\n */\n async *stream(\n query: { os?: string; hostname?: string; roots?: string[] } = {},\n opts: CallOpts = {},\n ): AsyncGenerator<HostStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/hosts/stream', {\n query: {\n os: query.os,\n hostname: query.hostname,\n roots: query.roots?.length ? query.roots.join(',') : undefined,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data) continue;\n yield { event: frame.event, data } as HostStreamEvent;\n }\n }\n}\n","/**\n * `/v1/assets` — the caller's codai Studio assets (media generated with `response_format: 'url'` and every finished\n * video job). Owner-scoped (a foreign id is 404), kept 90 days; each `ready` asset carries a 1 h V4 signed `url`.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type QueryOf, type Reply, type Schema } from './_shared';\n\n/** A stored asset (`GET /v1/assets/{id}`; `data` items with `response_format: 'url'`). */\nexport type AssetDto = Schema<'AssetDto'>;\nexport type AssetKind = Schema<'AssetKind'>;\nexport type AssetList = Reply<'listAssets'>;\nexport type AssetDeleted = Reply<'deleteAsset'>;\nexport type AssetListQuery = QueryOf<'listAssets'>;\n/** `b64_json` (default, inline bytes) or `url` (stored asset + 1 h signed URL; 503 `assets_unavailable` without storage). */\nexport type MediaResponseFormat = Schema<'MediaResponseFormat'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\n/** True for a `data` item that is a stored asset rather than inline base64. */\nexport function isAssetDto(item: unknown): item is AssetDto {\n return typeof item === 'object' && item !== null && 'asset_id' in item;\n}\n\nexport class Assets {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/assets` — newest first, `limit` ≤ 100 (default 30). Paginate by passing `next_before` as `before`. */\n list(query: AssetListQuery = {}, opts: CallOpts = {}): Promise<AssetList> {\n return this.http.json<AssetList>('/v1/assets', {\n query: { kind: query.kind, before: query.before, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Iterate every asset across pages (`list` with `before` = previous `next_before`). */\n async *iterate(\n query: Omit<AssetListQuery, 'before'> = {},\n opts: CallOpts = {},\n ): AsyncGenerator<AssetDto, void, undefined> {\n let before: string | undefined;\n for (;;) {\n const page = await this.list({ ...query, before }, opts);\n yield* page.data;\n if (!page.next_before) return;\n before = page.next_before;\n }\n }\n\n /** `GET /v1/assets/{id}` — one asset with a fresh 1 h signed `url` (`null` while not `ready`). */\n retrieve(id: string, opts: CallOpts = {}): Promise<AssetDto> {\n return this.http.json<AssetDto>(`/v1/assets/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * A fresh signed URL of the asset's bytes (valid 1 h), from `GET /v1/assets/{id}`. Throws when the asset has no\n * content yet. Use it in `<audio>`/`<video>`/`fetch` — it needs no Authorization header.\n */\n async contentUrl(id: string, opts: CallOpts = {}): Promise<string> {\n const a = await this.retrieve(id, opts);\n if (!a.url) throw new Error(`codai asset ${id} has no content yet (status ${a.status})`);\n return a.url;\n }\n\n /**\n * The authenticated redirect endpoint `GET /v1/assets/{id}/content` (302 to the signed URL). Useful for tools that\n * follow redirects with the API key (`curl -L -H 'Authorization: Bearer …'`); browsers should use `contentUrl()`.\n */\n contentPath(id: string): string {\n return this.http.url(`/v1/assets/${encodeURIComponent(id)}/content`);\n }\n\n /** Download the asset's bytes (fetches the signed URL, no API key sent to storage). */\n async content(id: string, opts: CallOpts = {}): Promise<Uint8Array> {\n const url = await this.contentUrl(id, opts);\n const res = await fetch(url, opts.signal ? { signal: opts.signal } : {});\n if (!res.ok) throw new Error(`codai asset ${id} download failed: HTTP ${res.status}`);\n return new Uint8Array(await res.arrayBuffer());\n }\n\n /** `DELETE /v1/assets/{id}` — deletes the object; signed URLs already handed out stop working. */\n delete(id: string, opts: CallOpts = {}): Promise<AssetDeleted> {\n return this.http.json<AssetDeleted>(`/v1/assets/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `POST /v1/images/generations` and `POST /v1/images/edits` — Gemini image models on Vertex AI.\n * `codai-image` (default, gemini-3.1-flash-image, EU), `codai-image-fast`, `codai-image-pro`.\n * Output from the EU endpoint carries C2PA credentials + SynthID: keep the bytes as returned.\n *\n * `response_format: 'url'` stores each image as a codai Studio asset (kept 90 days) and returns `assets`\n * (1 h signed URLs) instead of decoded bytes; the default `b64_json` is unchanged.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\nimport { type AssetDto, isAssetDto } from './assets';\n\nexport type ImagesRequest = Mutable<Body<'createImage'>>;\nexport type ImagesResponse = Reply<'createImage'>;\nexport type ImageEditRequest = Mutable<Body<'editImage'>>;\n\nexport interface ImagesResult {\n /** Decoded image bytes, one per generated image (see `mimeTypes`). Empty with `response_format: 'url'`. */\n images: Uint8Array[];\n /** MIME type of each generated image (usually `image/png`). */\n mimeTypes: string[];\n /** Stored assets with signed URLs (`response_format: 'url'` only; empty otherwise). */\n assets: AssetDto[];\n raw: ImagesResponse;\n /** Upstream model that produced the images (`x-codai-routed-to`). */\n routedTo: string | null;\n /** Vertex location that processed the request, `eu` or `global` (`x-codai-data-region`). */\n dataRegion: string | null;\n /** Usage-based charge for this request in micro-USD (`x-codai-cost-micro-usd`). */\n costMicroUsd: number | null;\n headers: Headers;\n}\n\n/** Image generation typically takes 5–30 s; the gateway allows 120 s upstream. */\nconst MIN_IMAGE_TIMEOUT_MS = 150_000;\n\nfunction decodeBase64(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nexport class Images {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Generate images. Needs a real API key (ephemeral tokens are rejected).\n * Pass `reference_images` to keep a logo/palette/product consistent.\n */\n async generate(\n body: Omit<ImagesRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ImagesResult> {\n return this.post(\n '/v1/images/generations',\n { ...body, model: body.model ?? 'codai-image' },\n opts,\n );\n }\n\n /**\n * Edit one or more input images (`image`: one `{ b64_json, mime_type }` or an array of up to 14)\n * from a text instruction. JSON body; `mask` is not supported — describe the region in `prompt`.\n */\n async edit(\n body: Omit<ImageEditRequest, 'model'> & { model?: string },\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ImagesResult> {\n return this.post('/v1/images/edits', { ...body, model: body.model ?? 'codai-image' }, opts);\n }\n\n private async post(\n path: string,\n body: unknown,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<ImagesResult> {\n const res = await this.http.request(path, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n // 0 = timeout disabled on the client; otherwise never cap below the image floor.\n timeoutMs:\n this.http.timeoutMs === 0 ? 0 : Math.max(this.http.timeoutMs, MIN_IMAGE_TIMEOUT_MS),\n });\n const raw = (await res.json()) as ImagesResponse;\n const cost = res.headers.get('x-codai-cost-micro-usd');\n const data = raw.data ?? [];\n const assets = data.filter(isAssetDto);\n const inline = data.filter((d): d is Exclude<typeof d, AssetDto> => !isAssetDto(d));\n return {\n images: inline.map((d) => decodeBase64(d.b64_json)),\n mimeTypes: data.map((d) => d.mime_type ?? 'image/png'),\n assets,\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n dataRegion: res.headers.get('x-codai-data-region'),\n costMicroUsd: cost === null ? null : Number(cost),\n headers: res.headers,\n };\n }\n}\n","/**\n * codai Studio media lanes (US-only, English prompts; refused for EU data-residency keys).\n *\n * `POST /v1/audio/music` — `codai-music` (Lyria 3 Clip, 30 s MP3 with vocals/lyrics), `codai-music-pro`\n * (Lyria 3 Pro, full song up to 184 s), `codai-music-legacy` (Lyria 2, 30 s instrumental WAV).\n * `POST /v1/videos` — Veo 3.1 Fast: starts a job (HTTP 202).\n * `GET /v1/videos/{id}` — polls the job; the MP4 is returned (and billed once) when it succeeds.\n * `POST /v1/studio/renders` — `codai-render`: renders a HyperFrames HTML composition to MP4 (HTTP 202).\n * `GET /v1/studio/renders/{id}` — polls the render; the MP4 asset is returned (and billed once) when it succeeds.\n * `GET /v1/studio/renders` — lists renders (no polling, no URLs); `root_render_id` = one timeline's versions.\n * `POST /v1/studio/timelines` — renders a list of image/video scenes (optional narration + music), HTTP 202.\n * `POST /v1/studio/renders/{id}/scenes/{sceneId}/regenerate` — new render with one timeline scene replaced (202).\n *\n * `response_format: 'url'` (music body, video poll query) returns stored assets with 1 h signed URLs (`assets`)\n * instead of base64 bytes; the default `b64_json` shape is unchanged. Wire types are declared here.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type AssetDto, type MediaResponseFormat, isAssetDto } from './assets';\n\nexport interface MusicRequest {\n /** `codai-music` (default, Lyria 3 Clip), `codai-music-pro` (Lyria 3 Pro) or `codai-music-legacy` (Lyria 2). */\n model?: 'codai-music' | 'codai-music-pro' | 'codai-music-legacy' | (string & {});\n /** Music description (genre, mood, instruments; no artist names). English is most reliable. */\n prompt: string;\n /** Lyrics to sing exactly (Lyria 3, <= 3000 chars). Non-English lyrics are best effort (see `lyrics_match`). */\n lyrics?: string;\n /** Instrumental only, no vocals (Lyria 3). */\n instrumental?: boolean;\n /** Target tempo, 40-220 (Lyria 3). */\n bpm?: number;\n /** Target length 10-184 s; `codai-music-pro` only (`codai-music` is always ~30 s). */\n duration_seconds?: number;\n /** Lyrics language hint, e.g. `ro`. */\n language?: string;\n /** `codai-music-legacy` only (400 for Lyria 3). */\n negative_prompt?: string;\n /** `codai-music-legacy` only (400 for Lyria 3). A seed forces a single clip. */\n seed?: number;\n /** Number of clips, 1-4; more than 1 only with `codai-music-legacy` (ignored when `seed` is set). */\n n?: number;\n /** `b64_json` (default) or `url` — store each clip as an asset and return signed URLs in `assets`. */\n response_format?: MediaResponseFormat;\n}\n\n/** Extra per-item fields returned by the Lyria 3 models (also present on `AssetDto` items). */\nexport interface MusicTrackMeta {\n /** Lyrics as sung, with `[start:end]` timing per line (Lyria 3 only). */\n lyrics?: string | null;\n /** The model's description of the track (may include `bpm` / `duration_secs`). */\n caption?: string | null;\n /** 0..1 match between the supplied `lyrics` and the sung words; `null` when not checked. */\n lyrics_match?: number | null;\n /** e.g. `lyrics_mismatch`, `lyrics_check_unavailable`. */\n warnings?: string[];\n}\n\nexport interface MusicClip extends MusicTrackMeta {\n b64_json: string;\n mime_type: string;\n duration_seconds: number;\n sample_rate?: number;\n}\n\nexport interface MusicResponse {\n created: number;\n model: string;\n /** `MusicClip` items by default; `AssetDto` items with `response_format: 'url'`. */\n data: Array<MusicClip | (AssetDto & MusicTrackMeta)>;\n}\n\nexport interface MusicResult {\n /** Decoded audio bytes (MP3 for Lyria 3, WAV for legacy), one per clip. Empty with `response_format: 'url'`. */\n clips: Uint8Array[];\n /** MIME type of each clip (`audio/mpeg` or `audio/wav`). */\n mimeTypes: string[];\n /** Stored assets with signed URLs (`response_format: 'url'` only; empty otherwise). */\n assets: AssetDto[];\n /** Per-item lyrics / caption / lyrics_match / warnings, in `data` order. */\n tracks: MusicTrackMeta[];\n /** All warnings across items (deduplicated), e.g. `lyrics_mismatch`. */\n warnings: string[];\n raw: MusicResponse;\n /** Upstream model (`x-codai-routed-to`). */\n routedTo: string | null;\n /** Charge in micro-USD (`x-codai-cost-micro-usd`). */\n costMicroUsd: number | null;\n headers: Headers;\n}\n\nexport interface VideoRequest {\n model?: string;\n /** English prompt. */\n prompt: string;\n negative_prompt?: string;\n seconds?: 4 | 6 | 8;\n aspect_ratio?: '16:9' | '9:16';\n resolution?: '720p' | '1080p';\n /** Generate an audio track (default true). */\n audio?: boolean;\n /** Optional first frame (image-to-video); forces 8 s. */\n image?: { b64_json: string; mime_type?: 'image/png' | 'image/jpeg' };\n /**\n * Up to 3 of your ready PNG / JPEG Studio image assets showing ONE subject (character or product) that the model\n * keeps consistent (e.g. a creative's cast `refAssetIds`). Not combinable with `image`; always 8 s. A missing or\n * foreign asset is 404, another type 400 — checked before anything is held or charged.\n */\n reference_asset_ids?: string[];\n seed?: number;\n}\n\nexport interface VideoJob {\n id: string;\n object: 'video.job';\n status: 'running';\n model: string;\n seconds: number;\n /** Price of the job in micro-USD (string, bigint-safe). */\n estimated_cost_micro_usd: string;\n}\n\nexport type VideoStatus = 'running' | 'succeeded' | 'failed' | 'filtered';\n\nexport interface VideoJobStatus {\n id: string;\n object: 'video.job';\n status: VideoStatus;\n error?: string;\n model?: string;\n seconds?: number;\n /** Inline MP4 by default; one `AssetDto` when polled with `responseFormat: 'url'`. */\n data?: Array<{ b64_json: string; mime_type: string } | AssetDto>;\n}\n\nexport interface VideoResult {\n /** Decoded MP4 bytes. Empty with `responseFormat: 'url'` (use `asset.url`). */\n video: Uint8Array;\n mimeType: string;\n id: string;\n seconds: number | null;\n /** The stored asset (`responseFormat: 'url'` only). */\n asset: AssetDto | null;\n raw: VideoJobStatus;\n}\n\nexport type RenderAspectRatio = '16:9' | '9:16' | '1:1' | '4:5';\nexport type RenderQuality = 'draft' | 'final';\nexport type RenderStatus = 'queued' | 'rendering' | 'succeeded' | 'failed';\n/**\n * Visible AI label burned into the video (EU AI Act art. 50(4)): `corner` = small \"AI-generated\" label bottom-right\n * for the whole video, `end_card` = final ~2 s card with the label, `none` = nothing. Default: `corner` when the\n * render uses TTS narration or AI-generated images, else `none`; `none` with TTS narration is 400 `ai_label_required`.\n */\nexport type RenderAiLabel = 'none' | 'corner' | 'end_card';\n\nexport interface RenderRequest {\n /** Defaults to `codai-render`. */\n model?: string;\n /**\n * A complete HyperFrames composition (`index.html`, <= 2,000,000 chars). Reference Studio assets as\n * `asset:<asset_id>` in any `src` / `href` / `url(...)` (max 50 distinct assets).\n */\n html: string;\n /** HyperFrames composition variables. */\n variables?: Record<string, unknown>;\n /** Must match the root `data-width` / `data-height` (default `16:9`). */\n aspect_ratio?: RenderAspectRatio;\n /** `final` (default) or `draft` (15 fps, 540p short side, no loudness pass, half price). */\n quality?: RenderQuality;\n /** `final` only (default 30). */\n fps?: 24 | 25 | 30;\n title?: string;\n /** EU AI Act art. 50(4) label; omit for the default (`corner` with TTS narration or AI images, else `none`). */\n ai_label?: RenderAiLabel;\n}\n\nexport interface RenderJob {\n id: string;\n object: 'studio.render';\n status: 'queued';\n model: string;\n quality: RenderQuality;\n aspect_ratio: RenderAspectRatio;\n fps: number;\n /** Micro-USD per output second (string, bigint-safe). */\n price_micro_usd_per_second: string;\n /** Minimum charge in micro-USD (string, bigint-safe). */\n minimum_micro_usd: string;\n /** The resolved AI label. */\n ai_label?: RenderAiLabel;\n}\n\nexport interface RenderQa {\n duration_seconds: number;\n width: number;\n height: number;\n lufs: number | null;\n warnings: Array<'silent_audio' | 'no_audio' | 'lufs_off_target'>;\n}\n\nexport interface RenderJobStatus {\n id: string;\n object: 'studio.render';\n status: RenderStatus;\n /** 0..1 */\n progress: number;\n quality: RenderQuality;\n aspect_ratio: RenderAspectRatio;\n fps: number;\n /** `<code>: <message>` when `failed`. */\n error: string | null;\n qa?: RenderQa | null;\n /** Charge in micro-USD (string), once succeeded. */\n cost_micro_usd?: string | null;\n /** The MP4 as one `AssetDto` (`kind: 'render'`), only when succeeded. */\n data?: AssetDto[];\n /** Signed JPEG poster URL, only when succeeded. */\n poster_url?: string | null;\n /** Worker stage while rendering; `generating_scene` while a regenerated video scene is generated (status `queued`). */\n stage?: string | null;\n title?: string | null;\n /** Timeline renders: the render this one was regenerated from. */\n parent_render_id?: string | null;\n /** Timeline renders: the original render of the version chain. */\n root_render_id?: string | null;\n /** Scenes of a timeline render; `null` for HTML and deck renders. */\n timeline?: RenderTimeline | null;\n /** The resolved AI label (EU AI Act art. 50(4)). */\n ai_label?: RenderAiLabel;\n}\n\nexport type SceneKind = 'image' | 'video';\nexport type SceneFit = 'cover' | 'contain';\n\nexport interface SceneNarration {\n text: string;\n asset_id: string | null;\n seconds: number | null;\n}\n\nexport interface TimelineScene {\n /** Stable id (`^[a-z0-9-]{1,32}$`); pass it to `regenerateScene`. */\n id: string;\n kind: SceneKind;\n asset_id: string;\n seconds: number;\n fit: SceneFit;\n /** Video scenes only. */\n video_volume?: number;\n prompt: string | null;\n narration: SceneNarration | null;\n revision: number;\n /** The visual (`url` signed only with `expandAssets`). */\n asset: AssetDto | null;\n /** The narration audio (`url` signed only with `expandAssets`). */\n narration_asset: AssetDto | null;\n}\n\nexport interface RenderTimeline {\n transition: 'fade' | 'none';\n music: { asset_id: string; volume: number } | null;\n scenes: TimelineScene[];\n}\n\nexport interface RenderListItem {\n id: string;\n object: 'studio.render';\n status: RenderStatus;\n title: string | null;\n quality: RenderQuality;\n aspect_ratio: RenderAspectRatio;\n fps: number;\n duration_seconds: number | null;\n /** Micro-USD (string); `\"0\"` until succeeded. */\n cost_micro_usd: string;\n created_at: string;\n parent_render_id: string | null;\n root_render_id: string | null;\n has_timeline: boolean;\n scene_count: number;\n}\n\nexport interface RenderList {\n object: 'list';\n data: RenderListItem[];\n /** Pass as `before` for the next page; `null` on the last page. */\n next_before: string | null;\n}\n\nexport interface TimelineSceneInput {\n /** Optional stable id, unique in the timeline (default `s1`…`sN`). */\n id?: string;\n kind: SceneKind;\n /** One of your ready image (kind `image`) or video (kind `video`) assets. */\n asset_id: string;\n /** 2..30 (default 5); a narrated scene lasts at least narration + 0.6 s. */\n seconds?: number;\n fit?: SceneFit;\n /** 0..1, video scenes only (default 1, or 0 when narrated). */\n video_volume?: number;\n /** Stored and reused by a later `regenerateScene` without a prompt. */\n prompt?: string;\n /** Narrated now (billed per call); not available for EU data-residency accounts. */\n narration?: { text: string; voice?: string; language?: string };\n}\n\nexport interface TimelineRequest {\n /** Defaults to `codai-render`. */\n model?: string;\n title?: string;\n aspect_ratio?: RenderAspectRatio;\n quality?: RenderQuality;\n /** `final` only (default 30). */\n fps?: 24 | 25 | 30;\n /** Default `fade` (0.5 s crossfade). */\n transition?: 'fade' | 'none';\n /** One of your ready audio assets, played under the whole timeline. */\n music_asset_id?: string;\n /** 0..1 (default 0.126). */\n music_volume?: number;\n narration_defaults?: {\n model?: 'codai-speech' | 'codai-speech-expressive';\n voice?: string;\n /** BCP-47, default `ro-RO`. */\n language?: string;\n instructions?: string;\n };\n /** 1..30 scenes, at most 180 s in total. */\n scenes: TimelineSceneInput[];\n}\n\nexport interface TimelineJob extends RenderJob {\n /** Narration already charged by this request, micro-USD (string). */\n narration_cost_micro_usd: string;\n scene_count: number;\n duration_seconds: number;\n /** Equal to `id`; regenerated versions keep it. */\n root_render_id: string;\n}\n\nexport interface SceneRegenerateRequest {\n /** Reuse an owned image/video asset, or generate: `codai-image` (image scene) / `codai-video` 4|6|8 s (video scene). */\n visual?: { asset_id: string } | { prompt?: string; model?: string; seconds?: 4 | 6 | 8 };\n /** Reuse an owned audio asset, re-narrate (`text` omitted = stored text), or `null` to remove the narration. */\n narration?: { asset_id: string } | { text?: string; voice?: string } | null;\n quality?: RenderQuality;\n}\n\nexport interface SceneRegenerateJob {\n id: string;\n object: 'studio.render';\n status: 'queued';\n parent_render_id: string;\n root_render_id: string;\n scene_id: string;\n /** Generation already charged (image, narration, video clip), micro-USD (string). */\n scene_cost_micro_usd: string;\n price_micro_usd_per_second: string;\n minimum_micro_usd: string;\n /** The resolved AI label of the new render. */\n ai_label?: RenderAiLabel;\n}\n\nexport interface RenderResult {\n id: string;\n /** The stored MP4 (1 h signed `url`; refresh with `assets.retrieve(id)`). */\n asset: AssetDto;\n posterUrl: string | null;\n qa: RenderQa | null;\n costMicroUsd: number | null;\n raw: RenderJobStatus;\n}\n\n/** Lyria 3 Pro can take minutes for a long song; the gateway allows 240 s upstream (+ lyrics check). */\nconst MIN_MUSIC_TIMEOUT_MS = 300_000;\n\nfunction decodeBase64(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Music {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Generate music (`POST /v1/audio/music`): `codai-music` 30 s clip with vocals, `codai-music-pro` full song up to\n * 184 s, `codai-music-legacy` instrumental Lyria 2. List price $0.04 / $0.08 / $0.06 per call.\n */\n async generate(\n body: MusicRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<MusicResult> {\n const res = await this.http.request('/v1/audio/music', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n // 0 = timeout disabled on the client; otherwise never cap below the music floor.\n timeoutMs:\n this.http.timeoutMs === 0 ? 0 : Math.max(this.http.timeoutMs, MIN_MUSIC_TIMEOUT_MS),\n });\n const raw = (await res.json()) as MusicResponse;\n const cost = res.headers.get('x-codai-cost-micro-usd');\n const data = raw.data ?? [];\n const inline = data.filter((d): d is MusicClip => !isAssetDto(d));\n const tracks = data.map((d): MusicTrackMeta => ({\n lyrics: d.lyrics ?? null,\n caption: d.caption ?? null,\n lyrics_match: d.lyrics_match ?? null,\n warnings: d.warnings ?? [],\n }));\n return {\n clips: inline.map((d) => decodeBase64(d.b64_json)),\n mimeTypes: data.map((d) => d.mime_type ?? 'audio/wav'),\n assets: data.filter(isAssetDto),\n tracks,\n warnings: [...new Set(tracks.flatMap((t) => t.warnings ?? []))],\n raw,\n routedTo: res.headers.get('x-codai-routed-to'),\n costMicroUsd: cost === null ? null : Number(cost),\n headers: res.headers,\n };\n }\n}\n\nexport class Videos {\n constructor(private readonly http: HttpClient) {}\n\n /** Start a video job (`POST /v1/videos`, HTTP 202). Nothing is charged until it succeeds. */\n async create(\n body: VideoRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<VideoJob> {\n const res = await this.http.request('/v1/videos', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return (await res.json()) as VideoJob;\n }\n\n /**\n * Poll a job (`GET /v1/videos/{id}`). Billed exactly once ($0.10 / s) on the first `succeeded` poll, across gateway\n * instances. `responseFormat: 'url'` returns the stored MP4 as one `AssetDto` (1 h signed URL) instead of base64.\n */\n async retrieve(\n id: string,\n opts: {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n responseFormat?: MediaResponseFormat;\n } = {},\n ): Promise<VideoJobStatus> {\n const res = await this.http.request(`/v1/videos/${encodeURIComponent(id)}`, {\n method: 'GET',\n query: { response_format: opts.responseFormat },\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as VideoJobStatus;\n }\n\n /** Create a job and poll until it succeeds. Throws on `failed`, `filtered` or timeout. */\n async generate(\n body: VideoRequest,\n opts: {\n pollIntervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n ext?: CodaiRequestExtensions;\n /** `url`: the final poll returns the stored asset (`result.asset`) instead of the MP4 bytes. */\n responseFormat?: MediaResponseFormat;\n } = {},\n ): Promise<VideoResult> {\n const { pollIntervalMs = 5000, timeoutMs = 300_000, signal, ext, responseFormat } = opts;\n const job = await this.create(body, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrieve(job.id, { ext, signal, responseFormat });\n if (st.status === 'succeeded') {\n const d = st.data?.[0];\n if (isAssetDto(d)) {\n return {\n video: new Uint8Array(0),\n mimeType: d.mime_type,\n id: job.id,\n seconds: st.seconds ?? job.seconds ?? null,\n asset: d,\n raw: st,\n };\n }\n if (!d?.b64_json) throw new Error(`codai video job ${job.id} succeeded without video data`);\n return {\n video: decodeBase64(d.b64_json),\n mimeType: d.mime_type ?? 'video/mp4',\n id: job.id,\n seconds: st.seconds ?? job.seconds ?? null,\n asset: null,\n raw: st,\n };\n }\n if (st.status === 'failed' || st.status === 'filtered') {\n throw new Error(`codai video job ${st.status}: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai video job ${job.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n}\n\nexport class Renders {\n constructor(private readonly http: HttpClient) {}\n\n /** Queue a render (`POST /v1/studio/renders`, HTTP 202). Nothing is charged until it succeeds. */\n async create(\n body: RenderRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<RenderJob> {\n const res = await this.http.request('/v1/studio/renders', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return (await res.json()) as RenderJob;\n }\n\n /**\n * Poll a render (`GET /v1/studio/renders/{id}`). Billed exactly once (final $0.01 / s, min $0.05; draft half) on the\n * first poll that sees the finished render; failed renders cost nothing.\n * `expandAssets` signs the timeline's scene and narration assets (`?expand=assets`).\n */\n async retrieve(\n id: string,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal; expandAssets?: boolean } = {},\n ): Promise<RenderJobStatus> {\n const res = await this.http.request(`/v1/studio/renders/${encodeURIComponent(id)}`, {\n method: 'GET',\n query: { expand: opts.expandAssets ? 'assets' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as RenderJobStatus;\n }\n\n /**\n * List renders newest first (`GET /v1/studio/renders`) — no polling, no signed URLs. `rootRenderId` restricts the\n * list to one timeline's version chain; pass `next_before` as `before` for the next page.\n */\n async list(\n params: { before?: string; limit?: number; rootRenderId?: string } = {},\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<RenderList> {\n const res = await this.http.request('/v1/studio/renders', {\n method: 'GET',\n query: {\n before: params.before,\n limit: params.limit,\n root_render_id: params.rootRenderId,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as RenderList;\n }\n\n /**\n * Render a scene timeline (`POST /v1/studio/timelines`, HTTP 202): image/video scenes, optional narration (billed\n * now, `narration_cost_micro_usd`) and music. Poll with `retrieve(id)`; the render is billed once when it succeeds.\n */\n async createTimeline(\n body: TimelineRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<TimelineJob> {\n const res = await this.http.request('/v1/studio/timelines', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return (await res.json()) as TimelineJob;\n }\n\n /**\n * Regenerate one scene (`POST /v1/studio/renders/{id}/scenes/{sceneId}/regenerate`, HTTP 202): a NEW render with\n * `parent_render_id` = `renderId`; the source must be a succeeded timeline render (409 `not_a_timeline`).\n */\n async regenerateScene(\n renderId: string,\n sceneId: string,\n body: SceneRegenerateRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SceneRegenerateJob> {\n const res = await this.http.request(\n `/v1/studio/renders/${encodeURIComponent(renderId)}/scenes/${encodeURIComponent(sceneId)}/regenerate`,\n { body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n return (await res.json()) as SceneRegenerateJob;\n }\n\n /** Queue a render and poll until it succeeds. Throws on `failed` or timeout. */\n async render(\n body: RenderRequest,\n opts: {\n pollIntervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n ext?: CodaiRequestExtensions;\n } = {},\n ): Promise<RenderResult> {\n const { pollIntervalMs = 5000, timeoutMs = 900_000, signal, ext } = opts;\n const job = await this.create(body, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrieve(job.id, { ext, signal });\n if (st.status === 'succeeded') {\n const asset = st.data?.find(isAssetDto);\n if (!asset) throw new Error(`codai render ${job.id} succeeded without an asset`);\n const cost = st.cost_micro_usd;\n return {\n id: job.id,\n asset,\n posterUrl: st.poster_url ?? null,\n qa: st.qa ?? null,\n costMicroUsd: cost === null || cost === undefined ? null : Number(cost),\n raw: st,\n };\n }\n if (st.status === 'failed') {\n throw new Error(`codai render failed: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai render ${job.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio documents (EU-served, everything runs in europe-west1).\n *\n * `POST /v1/studio/documents` — `codai-docs`: builds a deck (PPTX), doc (DOCX) or sheet (XLSX)\n * synchronously from a JSON `spec` (free; asset `kind: 'document'`).\n * `GET /v1/studio/documents/{id}` — the document, a fresh signed `file.url` and the stored `spec`.\n * `POST /v1/studio/documents/{id}/previews` — `codai-docs-preview`: tagged PDF + page PNGs + contact sheet (HTTP 202).\n * `GET /v1/studio/previews/{id}` — polls the preview; billed once ($0.002 / page, min $0.01) when done.\n * `POST /v1/studio/documents/{id}/video` — deck -> MP4 slideshow, queued as a `codai-render` (HTTP 202); poll it\n * with `renders.retrieve` (narration is billed at POST).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { isAssetDto } from './assets';\nimport { type RenderResult, Renders } from './media';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type DocumentType = 'deck' | 'doc' | 'sheet';\nexport type DocumentTheme = Schema<'DocumentTheme'>;\nexport type DeckSpec = Mutable<Schema<'DeckSpec'>>;\nexport type DocSpec = Mutable<Schema<'DocSpec'>>;\nexport type SheetSpec = Mutable<Schema<'SheetSpec'>>;\nexport type DocumentCreateRequest = Mutable<Body<'createDocument'>>;\n/** `POST` adds `cost_micro_usd` / `preview`; `GET` adds `spec` / `latest_preview_id`. */\nexport type StudioDocument = Reply<'createDocument'>;\nexport type DocumentPreviewRequest = Mutable<Body<'createDocumentPreview'>>;\nexport type DocumentPreviewAccepted = Reply<'createDocumentPreview', 202>;\nexport type DocumentPreview = Reply<'retrievePreview'>;\nexport type DocumentPreviewStatus = DocumentPreview['status'];\nexport type DocumentVideoRequest = Mutable<Body<'createDocumentVideo'>>;\nexport type DocumentVideoAccepted = Reply<'createDocumentVideo', 202>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\nexport interface DocumentPollOptions extends CallOpts {\n /** Delay between polls (default 3000 ms for previews, 5000 ms for videos). */\n pollIntervalMs?: number;\n /** Give up after this long (default 300 000 ms for previews, 900 000 ms for videos). */\n timeoutMs?: number;\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Documents {\n private readonly renders: Renders;\n\n constructor(private readonly http: HttpClient) {\n this.renders = new Renders(http);\n }\n\n /**\n * Build a document (`POST /v1/studio/documents`). `spec` must match `type` (`deck` -> `DeckSpec`, `doc` -> `DocSpec`,\n * `sheet` -> `SheetSpec`); invalid specs are 400 `invalid_spec`. Files are free. `based_on` creates the next version\n * of one of your documents; `preview: true` also queues a (billed) preview, returned as `preview`.\n */\n create(body: DocumentCreateRequest, opts: CallOpts = {}): Promise<StudioDocument> {\n return this.http.json<StudioDocument>('/v1/studio/documents', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/studio/documents/{id}` — fresh 1 h signed `file.url`, the stored `spec` and `latest_preview_id`. */\n retrieve(id: string, opts: CallOpts = {}): Promise<StudioDocument> {\n return this.http.json<StudioDocument>(`/v1/studio/documents/${encodeURIComponent(id)}`, {\n method: 'GET',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Queue a preview (`POST /v1/studio/documents/{id}/previews`, HTTP 202): tagged PDF, page PNGs (1280 px) and a\n * contact sheet. Billed once on the first poll that sees the result; at most 3 active previews per user (429).\n */\n preview(\n id: string,\n body: DocumentPreviewRequest = {},\n opts: CallOpts = {},\n ): Promise<DocumentPreviewAccepted> {\n return this.http.json<DocumentPreviewAccepted>(\n `/v1/studio/documents/${encodeURIComponent(id)}/previews`,\n { method: 'POST', body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /** Poll a preview (`GET /v1/studio/previews/{id}`): `queued` | `rendering` | `succeeded` | `failed`. */\n retrievePreview(previewId: string, opts: CallOpts = {}): Promise<DocumentPreview> {\n return this.http.json<DocumentPreview>(`/v1/studio/previews/${encodeURIComponent(previewId)}`, {\n method: 'GET',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Turn a deck into an MP4 (`POST /v1/studio/documents/{id}/video`, HTTP 202). Returns a render: poll it with\n * `renders.retrieve(id)` or use `videoAndWait`. Narration (`narrate`) is synthesized and billed now.\n */\n video(\n id: string,\n body: DocumentVideoRequest = {},\n opts: CallOpts = {},\n ): Promise<DocumentVideoAccepted> {\n return this.http.json<DocumentVideoAccepted>(\n `/v1/studio/documents/${encodeURIComponent(id)}/video`,\n { method: 'POST', body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /** Queue a preview and poll until it succeeds. Throws on `failed` or timeout. */\n async createPreviewAndWait(\n id: string,\n opts: DocumentPollOptions & { body?: DocumentPreviewRequest } = {},\n ): Promise<DocumentPreview> {\n const { pollIntervalMs = 3000, timeoutMs = 300_000, signal, ext, body } = opts;\n const job = await this.preview(id, body ?? {}, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrievePreview(job.id, { ext, signal });\n if (st.status === 'succeeded') return st;\n if (st.status === 'failed') {\n throw new Error(`codai document preview failed: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai document preview ${job.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n\n /** Queue a deck video and poll `renders.retrieve` until it succeeds. Throws on `failed` or timeout. */\n async videoAndWait(\n id: string,\n body: DocumentVideoRequest = {},\n opts: DocumentPollOptions = {},\n ): Promise<RenderResult & { accepted: DocumentVideoAccepted }> {\n const { pollIntervalMs = 5000, timeoutMs = 900_000, signal, ext } = opts;\n const accepted = await this.video(id, body, { ext, signal });\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.renders.retrieve(accepted.id, { ext, signal });\n if (st.status === 'succeeded') {\n const asset = st.data?.find(isAssetDto);\n if (!asset) throw new Error(`codai render ${accepted.id} succeeded without an asset`);\n const cost = st.cost_micro_usd;\n return {\n id: accepted.id,\n asset,\n posterUrl: st.poster_url ?? null,\n qa: st.qa ?? null,\n costMicroUsd: cost === null || cost === undefined ? null : Number(cost),\n raw: st,\n accepted,\n };\n }\n if (st.status === 'failed') {\n throw new Error(`codai deck video failed: ${st.error ?? 'no details'}`);\n }\n if (Date.now() + pollIntervalMs > deadline) {\n throw new Error(`codai deck video ${accepted.id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(pollIntervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio exports — FCPXML project zips of your video creatives, for Final Cut Pro, DaVinci Resolve or Premiere,\n * and Lottie JSON / dotLottie animations (`kind` tells them apart).\n *\n * `GET /v1/studio/creatives/{id}/export.fcpxml` — queue an export (`creatives.exportFcpxml`), HTTP 202\n * `GET /v1/studio/creatives/{id}/export.lottie` — a Lottie export, ready at once (`creatives.exportLottie`), HTTP 200\n * `GET /v1/studio/exports/{id}` — the export state; a signed zip `url` once `succeeded` (`retrieve`)\n *\n * `wait(id)` polls `retrieve` until the export has `succeeded` or `failed`. Only newly rendered seconds are billed (at\n * the final render price); polling is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type QueryOf, type Schema } from './_shared';\n\nexport type StudioExport = Schema<'StudioExport'>;\nexport type ExportFcpxmlQuery = QueryOf<'exportCreativeFcpxml'>;\n/** `creatives.exportLottie` / `downloadLottie` options (`download` is chosen by the method). */\nexport type ExportLottieQuery = Omit<QueryOf<'exportCreativeLottie'>, 'download'>;\n/** `creatives.downloadLottie`: the file bytes (`application/json` or `application/zip`) and its suggested name. */\nexport interface LottieDownload {\n bytes: Uint8Array;\n filename: string | null;\n contentType: string | null;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface ExportWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 900 000 ms = 15 min). */\n timeoutMs?: number;\n}\n\nconst path = (id: string) => `/v1/studio/exports/${encodeURIComponent(id)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Exports {\n constructor(private readonly http: HttpClient) {}\n\n /** The export: `queued` / `running`, then `succeeded` (signed `url`, valid 1 h) or `failed` (`error`). Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<StudioExport> {\n return this.http.json<StudioExport>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Poll `retrieve` every `intervalMs` (default 3 s) until the export is `succeeded` or `failed` and resolve with it\n * (a `failed` export resolves too — check `status` / `error`). Throws when it is not done within `timeoutMs`\n * (default 15 min) or when `signal` aborts.\n */\n async wait(id: string, opts: ExportWaitOptions = {}): Promise<StudioExport> {\n const { intervalMs = 3000, timeoutMs = 900_000, signal, ext } = opts;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const st = await this.retrieve(id, { ext, signal });\n if (st.status === 'succeeded' || st.status === 'failed') return st;\n if (Date.now() + intervalMs > deadline) {\n throw new Error(`codai export ${id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(intervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio creatives — editable creative documents (ECD) with an append-only version history.\n *\n * `POST /v1/studio/creatives` — create (empty doc per `kind`, your `doc`, or a `template` + `vars`;\n * `brand_kit_id`), HTTP 201\n * `GET /v1/studio/creatives` — list (`kind`, `before`, `limit`)\n * `GET /v1/studio/creatives/{id}` — the doc at the head (or `seq`) + signed assets\n * `GET /v1/studio/creatives/{id}/outline` — compact text outline for prompts\n * `POST /v1/studio/creatives/{id}/find` — node ids matching a query\n * `POST /v1/studio/creatives/{id}/subtree` — full JSON of ids / a scene\n * `POST /v1/studio/creatives/{id}/ops` — apply ops against `baseSeq` (rebased when possible, 409 `stale` else)\n * `GET /v1/studio/creatives/{id}/versions` — history; `revert`, `fork`, `lint`, `compiled`, `render`, `frame`\n * `GET /v1/studio/creatives/{id}/frames/{jobId}` — poll a frame job (`frameJob`)\n * `POST /v1/studio/creatives/{id}/comments` — turn a frame comment into an edit (`comment`, token-metered)\n * `POST /v1/studio/creatives/{id}/variants` — A/B variants as forks (`variants`, token-metered + draft renders)\n * `GET /v1/studio/creatives/{id}/variants` — the latest variant group (`listVariants`)\n * `POST /v1/studio/creatives/{id}/variants/{variantId}/pick` — apply the winner to the original (`pickVariant`)\n * `POST /v1/studio/creatives/{id}/template` — save as a private template (`saveTemplate`; see `templates`)\n * `GET /v1/studio/creatives/{id}/export.fcpxml` — queue an FCPXML project zip (`exportFcpxml`; see `exports`)\n * `GET /v1/studio/creatives/{id}/export.lottie` — Lottie JSON / dotLottie, free and ready at once (`exportLottie`;\n * `downloadLottie` for the file itself)\n * `POST /v1/studio/documents/{id}/creative` — edit a Studio document as a creative (`fromDocument`; 201 / 200)\n * `POST /v1/studio/creatives/{id}/build` — build a deck / doc / sheet creative into PPTX / DOCX / XLSX (`build`);\n * a carousel (PNG zip / PDF) or print (PDF/X-4) creative answers 202\n * with an export job (`buildAndWait`, `exports.wait`)\n * `POST /v1/studio/creatives/{id}/post-copy` — caption + hashtags per platform, alt text per slide (`postCopy`;\n * token-metered)\n * `POST /v1/studio/creatives/{id}/transcript-cut` — delete transcript word ranges from a clip (`transcriptCut`)\n * `POST /v1/studio/creatives/{id}/nodes/{nodeId}/regenerate` — new picture for an image node, cast-consistent\n * (`regenerateNode`; billed like an image generation)\n * `POST /v1/studio/creatives/{id}/restyle` — re-apply a brand kit / token map as one new version (`restyle`)\n * `POST /v1/studio/creatives/{id}/captions` — auto-captions from a voice clip (`captions`; transcription billed)\n * `GET /v1/studio/creatives/{id}/captions.srt|.vtt` — captions as SRT / WebVTT text (`captionsSrt`, `captionsVtt`)\n * `POST /v1/studio/creatives/{id}/adapt` — add platform formats with safe zones (`adapt`; vision focal billed)\n * `POST /v1/studio/creatives/{id}/lint/fix` — fix lint issues (`lintFix`; deterministic free, `agent` billed)\n * `GET /v1/studio/creatives/{id}/controls` — the tweak panel model (`controls`)\n * `GET /v1/studio/creatives/{id}/locales` — localisation state + units of a locale (`locales`)\n * `POST /v1/studio/creatives/{id}/localize` — translate into up to 10 locales (`localize`; token-metered)\n * `POST /v1/studio/creatives/{id}/locales/{locale}/fork` — a locale as a new creative (`forkLocale`)\n * `POST /v1/studio/creatives/{id}/shares` — a public view / review link, token shown once (`createShare`)\n * `GET /v1/studio/creatives/{id}/shares` — active links (`listShares`); `DELETE …/shares/{shareId}` (`revokeShare`)\n * `GET|POST /v1/studio/creatives/{id}/review` — review state; request review / back to draft (`review`,\n * `requestReview`, `resetReview`)\n * `GET|POST /v1/studio/creatives/{id}/review/threads` — comment threads (`reviewThreads`, `createReviewThread`);\n * `…/{threadId}/replies|resolve|reopen`, `DELETE …/review/comments/{commentId}`\n * `DELETE /v1/studio/creatives/{id}`\n *\n * `POST /v1/studio/creatives/{id}/render` (audio creative) — mixdown + master + stems / LRC (`renderAudio`), HTTP 202\n *\n * Everything but `render`, `comment` / `variants` (token-metered `codai` calls; variants also queue draft renders)\n * and frames beyond the daily free quota is free. `render` queues a `codai-render`\n * (HTTP 202; poll it with `renders.retrieve`) or returns an identical existing render (HTTP 200, `cached: true`).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport {\n type Body,\n type Mutable,\n type QueryOf,\n type Reply,\n type Schema,\n stripUndefined,\n} from './_shared';\nimport {\n type ExportFcpxmlQuery,\n type ExportLottieQuery,\n type ExportWaitOptions,\n Exports,\n type LottieDownload,\n type StudioExport,\n} from './exports';\n\nexport type CreativeKind = Schema<'CreativeKind'>;\nexport type CreativeDoc = Mutable<Schema<'CreativeDoc'>>;\nexport type CreativeOp = Mutable<Schema<'CreativeOp'>>;\nexport type CreativeCreateRequest = Mutable<Body<'createCreative'>>;\nexport type Creative = Reply<'createCreative', 201>;\nexport type CreativeDetail = Reply<'getCreative'>;\nexport type CreativeList = Reply<'listCreatives'>;\nexport type CreativeListQuery = QueryOf<'listCreatives'>;\nexport type CreativeOutline = Reply<'getCreativeOutline'>;\nexport type CreativeFindRequest = Mutable<Body<'findCreativeNodes'>>;\nexport type CreativeFindResult = Reply<'findCreativeNodes'>;\nexport type CreativeSubtreeRequest = Mutable<Body<'getCreativeSubtree'>>;\nexport type CreativeSubtree = Reply<'getCreativeSubtree'>;\nexport type CreativeOpsResult = Reply<'applyCreativeOps'>;\nexport type CreativeVersionList = Reply<'listCreativeVersions'>;\nexport type CreativeVersionListQuery = QueryOf<'listCreativeVersions'>;\nexport type CreativeRevertResult = Reply<'revertCreative'>;\nexport type CreativeForkRequest = Mutable<Body<'forkCreative'>>;\nexport type CreativeLintResult = Reply<'lintCreative'>;\nexport type CreativeCompiled = Reply<'getCreativeCompiled'>;\nexport type CreativeRenderRequest = Mutable<Schema<'CreativeRenderRequest'>>;\nexport type CreativeRenderAccepted = Schema<'CreativeRenderAccepted'>;\nexport type CreativeRenderCached = Reply<'renderCreative', 200>;\n/** `render` answer: a new queued render (202, `cached: false`) or the identical existing one (200, `cached: true`). */\nexport type CreativeRenderResult = CreativeRenderAccepted | CreativeRenderCached;\n/** `renderAudio` body (MU-05): `formats` (wav | mp3 | flac), `stems`, `lrc`, `loudness` (preset or LUFS), `title`. */\nexport type CreativeAudioRenderRequest = Mutable<Schema<'CreativeAudioRenderRequest'>>;\n/** `renderAudio` answer (202): the queued mixdown with its planned `outputs` and `quote_micro_usd`. */\nexport type CreativeAudioRenderAccepted = Schema<'CreativeAudioRenderAccepted'>;\nexport type CreativeAudioRenderOutput = Schema<'CreativeAudioRenderOutput'>;\n/** `GET /v1/studio/renders/{id}` of an audio render (`target: 'audio'`): one `data[]` asset per output. */\nexport type StudioAudioRender = Schema<'StudioAudioRender'>;\nexport type CreativeFrameRequest = Mutable<Body<'createCreativeFrame'>>;\nexport type CreativeFrame = Schema<'CreativeFrame'>;\nexport type CreativeFrames = Reply<'createCreativeFrame', 200>;\nexport type CreativeFrameJob = Reply<'createCreativeFrame', 202>;\n/** `frame` / `frameJob` answer: frames ready (`status: succeeded`) or a running job to poll (`status: running`). */\nexport type CreativeFrameResult = CreativeFrames | CreativeFrameJob;\nexport type CreativeDeleted = Reply<'deleteCreative'>;\nexport type CreativeCommentRequest = Mutable<Body<'commentCreative'>>;\nexport type CreativeCommentResult = Reply<'commentCreative'>;\nexport type CreativeVariantsRequest = Mutable<Body<'createCreativeVariants'>>;\nexport type CreativeVariantsResult = Reply<'createCreativeVariants'>;\nexport type CreativeVariant = Schema<'CreativeVariant'>;\nexport type CreativeVariantList = Reply<'listCreativeVariants'>;\nexport type CreativeVariantPickRequest = Mutable<Body<'pickCreativeVariant'>>;\nexport type CreativeVariantPickResult = Reply<'pickCreativeVariant'>;\nexport type SaveTemplateRequest = Mutable<Body<'saveCreativeTemplate'>>;\nexport type CreativeTemplate = Schema<'CreativeTemplate'>;\n/** `fromDocument` answer: the creative (`existing: false`, HTTP 201) or the one already linked (`existing: true`, 200). */\nexport type StudioCreativeFromDocument = Schema<'StudioCreativeFromDocument'>;\nexport type CreativeBuildRequest = Mutable<Schema<'CreativeBuildRequest'>>;\nexport type StudioCreativeBuild = Schema<'StudioCreativeBuild'>;\n/** Build request of a carousel (`format: 'png' | 'pdf'`) or print (`format: 'pdf'`) creative. */\nexport type CreativePagedBuildRequest = Mutable<Schema<'CreativePagedBuildRequest'>>;\n/** HTTP 202 answer of `build` for a carousel / print creative: the queued export job is in `export`. */\nexport type StudioCreativePagedBuild = Schema<'StudioCreativePagedBuild'>;\nexport type CreativePrintLintIssue = Schema<'CreativePrintLintIssue'>;\n/** `build` answers a stored document version (200, deck / doc / sheet) or a queued export (202, carousel / print). */\nexport type CreativeBuildResult = StudioCreativeBuild | StudioCreativePagedBuild;\nexport type StudioPostCopyRequest = Mutable<Schema<'StudioPostCopyRequest'>>;\nexport type StudioPostCopy = Schema<'StudioPostCopy'>;\nexport type CreativeTranscriptCutRequest = Mutable<Schema<'CreativeTranscriptCutRequest'>>;\nexport type CreativeTranscriptCutResult = Schema<'CreativeTranscriptCutResult'>;\nexport type CreativeRegenerateNodeRequest = Mutable<Schema<'CreativeRegenerateNodeRequest'>>;\nexport type CreativeRegenerateNodeResult = Schema<'CreativeRegenerateNodeResult'>;\nexport type CreativeCast = Schema<'CreativeCast'>;\n\n/** True when a `build` answer is the 202 carousel / print export job (poll `exports.wait(r.export.id)`). */\nexport const isPagedBuild = (r: CreativeBuildResult): r is StudioCreativePagedBuild =>\n 'export' in r && (r as StudioCreativePagedBuild).export != null;\n/** `{ brand_kit_id }` or `{ tokens }` (exactly one) + optional `base_seq`, `snap`, `fonts`, `force`. */\nexport type CreativeRestyleRequest = Mutable<Body<'restyleCreative'>>;\n/** Same shape as the `edit` answer (`seq`, `doc_hash`, `changed`, `warnings`, `rebased`). */\nexport type CreativeRestyleResult = Reply<'restyleCreative'>;\nexport type CaptionPresetId = Schema<'CaptionPresetId'>;\nexport type PlatformId = Schema<'PlatformId'>;\nexport type CreativeLintCode = Schema<'CreativeLintCode'>;\nexport type LintIssue = Schema<'CreativeLintIssue'>;\n/** Optional `clip_id`, `preset`, `node_id`, `script`, `language`, `retranscribe`, `base_seq`, `force`. */\nexport type CreativeCaptionsRequest = Mutable<Schema<'CreativeCaptionsRequest'>>;\n/** The `edit` answer plus `node_id`, `words`, `cached`, `corrected`, `cost_micro_usd`. */\nexport type CreativeCaptionsResult = Schema<'CreativeCaptionsResult'>;\nexport type CreativeCaptionsQuery = { node_id?: string; seq?: number; locale?: string };\n/** `platforms` (1..6) + optional `focal` (`none` | `vision`), `base_seq`, `force`. */\nexport type CreativeAdaptRequest = Mutable<Schema<'CreativeAdaptRequest'>>;\n/** The `edit` answer plus `formats` and `focal`. */\nexport type CreativeAdaptResult = Schema<'CreativeAdaptResult'>;\n/** Optional `codes`, `agent`, `base_seq`, `force`. */\nexport type CreativeLintFixRequest = Mutable<Schema<'CreativeLintFixRequest'>>;\nexport type CreativeLintFixResult = Schema<'CreativeLintFixResult'>;\n/** A tweak panel control (`doc.meta.controls[varKey]`), set with a `setControl` op. */\nexport type CreativeControl = Mutable<Schema<'Control'>>;\nexport type PanelControl = Schema<'PanelControl'>;\nexport type CreativeControls = Reply<'getCreativeControls'>;\nexport type CreativeLocaleStatus = Schema<'CreativeLocaleStatus'>;\nexport type CreativeLocaleUnit = Schema<'CreativeLocaleUnit'>;\nexport type CreativeLocalesQuery = QueryOf<'getCreativeLocales'>;\n/** `locales` (1..10) + optional `base_seq`, `tone`, `glossary`, `only_missing`, `voice`, `force`. */\nexport type CreativeLocalizeRequest = Mutable<Schema<'CreativeLocalizeRequest'>>;\n/** The `edit` answer plus `locales` (per-locale summary) and `cost_micro_usd`. */\nexport type CreativeLocalizeResult = Schema<'CreativeLocalizeResult'>;\n/** Optional `title` and `seq`. */\nexport type CreativeLocaleForkRequest = Mutable<Schema<'CreativeLocaleForkRequest'>>;\n/** The new creative plus `locale` and `fork_of`. */\nexport type CreativeLocaleForkResult = Schema<'CreativeLocaleForkResult'>;\n/** `kind` (`view` | `review`) + optional `label`, `expires_in_days`, `seq` / `allow_remix` (view), `can_approve` (review). */\nexport type StudioShareCreateRequest = Mutable<Schema<'StudioShareCreateRequest'>>;\n/** The new link with its `token` and public `url` — shown only once. */\nexport type StudioShareCreated = Schema<'StudioShareCreated'>;\n/** An active link (`url` is always null: the token is stored hashed). */\nexport type StudioShare = Schema<'StudioShare'>;\nexport type StudioShareList = Schema<'StudioShareList'>;\nexport type StudioReviewStatus = Schema<'StudioReviewStatus'>;\nexport type StudioReview = Schema<'StudioReview'>;\nexport type StudioReviewComment = Schema<'StudioReviewComment'>;\n/** A thread: anchor (`node_id`, `scene_id`, `t_ms`), `status`, and `comments` (root first). */\nexport type StudioReviewThread = Schema<'StudioReviewThread'>;\nexport type StudioReviewThreadList = Schema<'StudioReviewThreadList'>;\n/** `body` (1..2000) + optional anchor `node_id`, `scene_id`, `t_ms`. */\nexport type StudioReviewThreadCreateRequest = Mutable<Schema<'StudioReviewThreadCreateRequest'>>;\nexport type StudioReviewThreadsQuery = { status?: 'open' | 'resolved' | 'all' };\n/** Optional `locale`: lint the document translated into it. */\nexport type CreativeLintRequest = { locale?: string };\nexport type CreativeCompiledQuery = { format?: string; scene?: string; locale?: string };\n\n/** Body of `edit` (camelCase; sent as `base_seq` / `ops` / `intent` / `author` / `force`). */\nexport interface CreativeEditRequest {\n /** The version the ops were authored against (`head_seq` of what you read). */\n baseSeq: number;\n ops: CreativeOp[];\n /** Why — shown in the version history. */\n intent?: string;\n author?: 'user' | 'agent';\n /** Bypass locked nodes and variables. */\n force?: boolean;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst path = (id: string, tail = '') => `/v1/studio/creatives/${encodeURIComponent(id)}${tail}`;\nconst lottieQuery = (q: ExportLottieQuery) => ({\n format: q.format,\n formats: q.formats,\n seq: q.seq,\n container: q.container,\n});\n\nexport class Creatives {\n constructor(private readonly http: HttpClient) {}\n\n /** List your creatives, most recently updated first (`next_before` pages). */\n list(query: CreativeListQuery = {}, opts: CallOpts = {}): Promise<CreativeList> {\n return this.http.json<CreativeList>('/v1/studio/creatives', {\n query: { kind: query.kind, before: query.before, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Create a creative (`kind` + optional `title` / `doc`); without `doc` you get an empty document for the kind.\n * `brand_kit_id` applies one of your brand kits (`brandKits`) to version 1: `brand = { kitId, tokens }` + its logo.\n * `template` (+ `vars`, values by var key) starts from one of your templates (`templates`) instead of `doc`.\n */\n create(body: CreativeCreateRequest, opts: CallOpts = {}): Promise<Creative> {\n return this.http.json<Creative>('/v1/studio/creatives', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The document at the head (or `seq`) with signed `assets` (1 h URLs). */\n retrieve(id: string, query: { seq?: number } = {}, opts: CallOpts = {}): Promise<CreativeDetail> {\n return this.http.json<CreativeDetail>(path(id), {\n query: { seq: query.seq },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Compact text outline (+ formats and vars) — the cheapest structure for a prompt. */\n outline(id: string, opts: CallOpts = {}): Promise<CreativeOutline> {\n return this.http.json<CreativeOutline>(path(id, '/outline'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Node ids matching `query` (a string = text/name/id substring, or `{ text, type, sceneId, assetId, locked }`). */\n find(\n id: string,\n query: CreativeFindRequest['query'],\n opts: CallOpts = {},\n ): Promise<CreativeFindResult> {\n return this.http.json<CreativeFindResult>(path(id, '/find'), {\n method: 'POST',\n body: { query },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Full JSON of `ids` (scene ids return whole scenes) or of one `sceneId`. */\n subtree(id: string, body: CreativeSubtreeRequest, opts: CallOpts = {}): Promise<CreativeSubtree> {\n return this.http.json<CreativeSubtree>(path(id, '/subtree'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Apply an op batch (all or nothing) authored against `baseSeq`. A stale base is rebased when the touched\n * targets did not change meanwhile; otherwise the call throws `CodaiError` 409 `stale` (reload and retry). Rejected\n * ops throw 400 with `code` (`invalid`, `not_found`, `locked`, `duplicate_id`).\n */\n edit(id: string, body: CreativeEditRequest, opts: CallOpts = {}): Promise<CreativeOpsResult> {\n return this.http.json<CreativeOpsResult>(path(id, '/ops'), {\n method: 'POST',\n body: {\n base_seq: body.baseSeq,\n ops: body.ops,\n ...(body.intent !== undefined ? { intent: body.intent } : {}),\n ...(body.author !== undefined ? { author: body.author } : {}),\n ...(body.force !== undefined ? { force: body.force } : {}),\n },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Version history, newest first (`beforeSeq` pages). */\n versions(\n id: string,\n query: { beforeSeq?: number; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<CreativeVersionList> {\n return this.http.json<CreativeVersionList>(path(id, '/versions'), {\n query: { before_seq: query.beforeSeq, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** New head whose document is version `seq`'s (undo / redo). */\n revert(id: string, seq: number, opts: CallOpts = {}): Promise<CreativeRevertResult> {\n return this.http.json<CreativeRevertResult>(path(id, '/revert'), {\n method: 'POST',\n body: { seq },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** New creative from version `seq` (default the head). */\n fork(id: string, body: CreativeForkRequest = {}, opts: CallOpts = {}): Promise<Creative> {\n return this.http.json<Creative>(path(id, '/fork'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Soft-delete the creative. */\n delete(id: string, opts: CallOpts = {}): Promise<CreativeDeleted> {\n return this.http.json<CreativeDeleted>(path(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Contrast, safe area, empty text, missing assets, brand colours, platform safe zones and text floors, alt text,\n * missing captions, reading speed, flashing, missing / stale translations. Issues carry `format` / `fixable` /\n * `locale`; `fixable` counts them (`lintFix`). `locale` lints the translated document (adds\n * `text_overflow_locale`); 404 `Locale not found.` for an unknown locale.\n */\n lint(\n id: string,\n body: CreativeLintRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeLintResult> {\n return this.http.json<CreativeLintResult>(path(id, '/lint'), {\n method: 'POST',\n ...(body.locale !== undefined ? { body: { locale: body.locale } } : {}),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Preview HTML (signed asset URLs) for `format` / one `scene` / a translation (`locale`). */\n compiled(\n id: string,\n query: CreativeCompiledQuery = {},\n opts: CallOpts = {},\n ): Promise<CreativeCompiled> {\n return this.http.json<CreativeCompiled>(path(id, '/compiled'), {\n query: { format: query.format, scene: query.scene, locale: query.locale },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Queue an MP4 render of the head (`codai-render`, HTTP 202, `cached: false`); poll `renders.retrieve(render_id)`.\n * When the same render already exists for this version / format / quality / fps you get it back at once\n * (HTTP 200, `cached: true`, `status: 'succeeded'`, no new charge). Unchanged scenes are reused either way.\n * `locale` renders a translation (404 `Locale not found.` when the creative has no such locale).\n * `ai_label` (`none` | `corner` | `end_card`, EU AI Act art. 50(4)) burns a visible AI label into the video; omitted =\n * `corner` when the creative uses TTS narration or AI images, else `none` (`none` with narration: 400 `ai_label_required`).\n */\n render(\n id: string,\n body: CreativeRenderRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeRenderResult> {\n return this.http.json<CreativeRenderResult>(path(id, '/render'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Mixdown + mastering + exports of an `audio` creative (MU-05; same `POST …/render` route, HTTP 202). `formats`\n * (default `['wav', 'mp3']`), `stems: true` adds one WAV per audible track (+50 %), `lrc` exports the timed lyrics\n * (default on when the document has them), `loudness` is `streaming` (−14) | `podcast` (−16) | `broadcast` (−23) or\n * LUFS (−40…−5). Poll `renders.retrieve(render_id)`: the finished render's `data[]` holds one signed asset per output\n * (`output: mix | stem | lrc`). $0.001 per output second, minimum $0.01; held up front, billed on the measured length.\n * 400 `empty_audio` / `too_long` (20 min) / `no_lyrics`; video creatives use `render`.\n */\n renderAudio(\n id: string,\n body: CreativeAudioRenderRequest = {},\n opts: CallOpts & { idempotencyKey?: string } = {},\n ): Promise<CreativeAudioRenderAccepted> {\n return this.http.json<CreativeAudioRenderAccepted>(path(id, '/render'), {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: !opts.idempotencyKey,\n });\n }\n\n /**\n * PNG still frames at up to 6 times (`t_ms`). `exact: false` (default) screenshots the compiled HTML; `exact: true`\n * cuts them from a draft render of the covering scenes. Waits up to ~90 s: frames (`status: 'succeeded'`) or a\n * running job (`status: 'running'`) to poll with `frameJob(id, frame_job_id)`. Cached frames are free; 60 frame\n * jobs per UTC day are free, then billed (`billed_micro_usd`).\n */\n frame(id: string, body: CreativeFrameRequest, opts: CallOpts = {}): Promise<CreativeFrameResult> {\n return this.http.json<CreativeFrameResult>(path(id, '/frame'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Turn a comment pinned on a frame (`t_ms`, optional `node_id` / `scene_id`) into an edit: one bounded `codai`\n * model turn proposes ops, applied like `edit` against `base_seq` (rebased when possible, 409 `stale` else).\n * 422 `no_edit` when the model made no edit (its answer in `error.text`); `apply: false` only proposes the ops.\n * Token-metered like any `codai` text call.\n */\n comment(\n id: string,\n body: CreativeCommentRequest,\n opts: CallOpts = {},\n ): Promise<CreativeCommentResult> {\n return this.http.json<CreativeCommentResult>(path(id, '/comments'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Generate A/B variants: one bounded `codai` model turn proposes `count` (default 3) variants changing only\n * `focus` (default hook / title / cta); each becomes a fork of the creative at `base_seq` with the ops applied, plus\n * a queued draft render (`render: false` to skip; poll `renders.retrieve(render_id)`). The original is unchanged\n * until `pickVariant`. 422 `no_edit` when no valid variant came back, 504 `timeout` after 90 s. Token-metered.\n */\n variants(\n id: string,\n body: CreativeVariantsRequest,\n opts: CallOpts = {},\n ): Promise<CreativeVariantsResult> {\n return this.http.json<CreativeVariantsResult>(path(id, '/variants'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The latest variant group of a creative (`group_id: null` when none) with statuses and stored render state. */\n listVariants(id: string, opts: CallOpts = {}): Promise<CreativeVariantList> {\n return this.http.json<CreativeVariantList>(path(id, '/variants'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Pick the winner: its ops are applied to the original against `base_seq` (rebased when possible, 409 `stale`\n * else); the winner is marked `winner`, the rest of its group `rejected`.\n */\n pickVariant(\n id: string,\n variantId: string,\n body: CreativeVariantPickRequest,\n opts: CallOpts = {},\n ): Promise<CreativeVariantPickResult> {\n return this.http.json<CreativeVariantPickResult>(\n path(id, `/variants/${encodeURIComponent(variantId)}/pick`),\n { method: 'POST', body, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /**\n * Save the creative (at `seq`, default the head) as a private template: each `vars` entry turns a text node's text\n * (`prop: 'text'`) or an image node's asset (`prop: 'image'`) into a variable whose default is the current value.\n * 400 `node_not_found` / `invalid_pick` / `duplicate_key`. Free.\n */\n saveTemplate(\n id: string,\n body: SaveTemplateRequest,\n opts: CallOpts = {},\n ): Promise<CreativeTemplate> {\n return this.http.json<CreativeTemplate>(path(id, '/template'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Queue an FCPXML export of a video creative (`seq`, default the head; `format`, default the first 1920×1080 /\n * 1080×1920 / 1080×1080 format): a zip with `project.fcpxml` + per-scene MP4 segments + audio, for Final Cut Pro,\n * DaVinci Resolve or Premiere. Resolves to the queued export; poll it with `exports.wait(e.id)`. Only newly\n * rendered seconds are billed (final render price). 400 `unsupported_kind` / `unsupported_format` / `too_long`.\n */\n exportFcpxml(\n id: string,\n query: ExportFcpxmlQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioExport> {\n return this.http.json<StudioExport>(path(id, '/export.fcpxml'), {\n query: { format: query.format, seq: query.seq },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Export a video creative as a Lottie animation (`seq`, default the head; `format`, default the document's default\n * format, or `formats: 'all'`; `container: 'json'` (default, Bodymovin JSON with embedded images) or `'dotlottie'`).\n * Free and synchronous: resolves to an export that is already `succeeded` with a signed `url` (valid 1 h) and the\n * fidelity report in `warnings` (video, chart, HTML block, table, cell grid and audio nodes are not exported).\n * 400 `unsupported_kind` / `invalid_request`, 413 `too_large` (over 20 MB).\n */\n exportLottie(\n id: string,\n query: ExportLottieQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioExport> {\n return this.http.json<StudioExport>(path(id, '/export.lottie'), {\n query: lottieQuery(query),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * The Lottie file itself (`download=1`, nothing stored): `application/json` for one Bodymovin JSON, `application/zip`\n * for a dotLottie archive or a zip of JSON files (`formats: 'all'`). Same options and errors as `exportLottie`. Free.\n */\n async downloadLottie(\n id: string,\n query: ExportLottieQuery = {},\n opts: CallOpts = {},\n ): Promise<LottieDownload> {\n const res = await this.http.request(path(id, '/export.lottie'), {\n query: { ...lottieQuery(query), download: '1' },\n ext: opts.ext,\n signal: opts.signal,\n });\n const m = /filename=\"([^\"]+)\"/i.exec(res.headers.get('content-disposition') ?? '');\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n filename: m ? m[1]! : null,\n contentType: res.headers.get('content-type'),\n };\n }\n\n /**\n * Turn one of your Studio documents (deck, doc, sheet) into an editable creative — slides become scenes with a\n * `layout` and speaker `notes`, doc pages a `flow` group, sheets a `cell_grid`; nodes carry semantic `role`s.\n * Idempotent: a document that already has a creative resolves to it (`existing: true`). Free. 404 unknown document,\n * 409 `document_spec_missing`, 400 `invalid_spec`, 413 `too_large`.\n */\n fromDocument(documentId: string, opts: CallOpts = {}): Promise<StudioCreativeFromDocument> {\n return this.http.json<StudioCreativeFromDocument>(\n `/v1/studio/documents/${encodeURIComponent(documentId)}/creative`,\n { method: 'POST', ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /**\n * Build a deck / doc / sheet creative (at `seq`, default the head) into a PPTX / DOCX / XLSX — a new version of its\n * Studio document (`document`, exactly the `POST /v1/studio/documents` body). Converter notes come back in\n * `warnings`. The file is free; `preview: true` also queues a billed preview (poll it with\n * `documents.waitForPreview`). 400 `not_supported_for_kind` (video / image) or `invalid_spec`.\n *\n * A carousel (`format: 'png'` zip of slides or `'pdf'`) or print (`'pdf'`, PDF/X-4 with bleed and optional\n * `crop_marks`) creative answers HTTP 202 with a queued export job in `export` (`format_id` picks the format,\n * `quote_micro_usd` is held). Tell the two apart with `isPagedBuild`, poll with `exports.wait(r.export.id)` or use\n * `buildAndWait`.\n */\n build(\n id: string,\n body: CreativeBuildRequest | CreativePagedBuildRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeBuildResult> {\n return this.http.json<CreativeBuildResult>(path(id, '/build'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * `build`, then — for a carousel / print creative — poll the export job until it has `succeeded` or `failed`\n * (`exports.wait`). Resolves to the 200 build for deck / doc / sheet, or to the finished `StudioExport`.\n */\n async buildAndWait(\n id: string,\n body: CreativeBuildRequest | CreativePagedBuildRequest = {},\n opts: ExportWaitOptions = {},\n ): Promise<StudioCreativeBuild | StudioExport> {\n const r = await this.build(id, body, { ext: opts.ext, signal: opts.signal });\n if (!isPagedBuild(r)) return r;\n const e = r.export;\n if (e.status === 'succeeded' || e.status === 'failed') return e;\n return new Exports(this.http).wait(e.id, opts);\n }\n\n /**\n * Social post copy for a carousel, image or video creative: a caption + hashtags per platform (`platforms`,\n * default Instagram + LinkedIn; `language` `ro` (default) | `en`; optional `brief`, `tone`, `seq`) and one alt text\n * per slide, every answer repaired to the platform's hard limits (changes listed in `fixes`). Nothing is written to\n * the creative. Token-metered (`cost_micro_usd`) under a small wallet hold (402 `insufficient_funds`); 400\n * `not_supported_for_kind`, 422 `no_post_copy`, 504 `timeout`. `idempotencyKey` replays a retry (24 h).\n */\n postCopy(\n id: string,\n body: StudioPostCopyRequest = {},\n opts: CallOpts & { idempotencyKey?: string } = {},\n ): Promise<StudioPostCopy> {\n return this.http.json<StudioPostCopy>(path(id, '/post-copy'), {\n method: 'POST',\n body: stripUndefined(body),\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: !opts.idempotencyKey,\n });\n }\n\n /**\n * Edit a video clip by its transcript: delete word ranges (`remove: [{ from_word, to_word }]`, indexes into the\n * clip asset's cached transcript from `captions`) from video node `node_id`; the pieces are placed back to back as\n * one new version (`base_seq` rebased like `edit`, locks honoured unless `force`). Free. 409 `captions_required`\n * (run `captions` on that clip first) or `stale`; video creatives only.\n */\n transcriptCut(\n id: string,\n body: CreativeTranscriptCutRequest,\n opts: CallOpts = {},\n ): Promise<CreativeTranscriptCutResult> {\n return this.http.json<CreativeTranscriptCutResult>(path(id, '/transcript-cut'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Generate a new picture for an `image` node (`prompt`, optional `model`, `aspect_ratio` — default the closest\n * ratio of the node box — `base_seq`, `force`) and swap it in as one new version. A node with a `castId` sends that\n * cast entry's `refAssetIds` as references and appends its `description`, so the subject stays consistent. Billed\n * like `images.generate` (402 `insufficient_funds`); 400 `content_filtered` charges nothing. `idempotencyKey`\n * replays a retry (24 h).\n */\n regenerateNode(\n id: string,\n nodeId: string,\n body: CreativeRegenerateNodeRequest,\n opts: CallOpts & { idempotencyKey?: string } = {},\n ): Promise<CreativeRegenerateNodeResult> {\n return this.http.json<CreativeRegenerateNodeResult>(\n path(id, `/nodes/${encodeURIComponent(nodeId)}/regenerate`),\n {\n method: 'POST',\n body: stripUndefined(body),\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: !opts.idempotencyKey,\n },\n );\n }\n\n /**\n * Re-apply a brand kit (`brand_kit_id`) or a flat token map (`tokens`) to the creative as one new version: literal\n * colours equal to the old brand become token refs, `snap: true` maps every other colour to the nearest kit colour,\n * `fonts` (default true) sets heading / body font refs by role, locked nodes are skipped unless `force`. The kit\n * logo is registered too. `base_seq` defaults to the head (rebased like `edit`, 409 `stale` else). Free.\n */\n restyle(\n id: string,\n body: CreativeRestyleRequest,\n opts: CallOpts = {},\n ): Promise<CreativeRestyleResult> {\n return this.http.json<CreativeRestyleResult>(path(id, '/restyle'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Auto-captions: transcribe a voice clip (`clip_id`, default the first voice clip) word by word and add or update a\n * captions node (`preset`, default `bold-pill`) as one new version. Words are cached on the asset (free next time\n * unless `retranscribe`); `script` (default the narration of a codai speech asset) corrects the spelling. A fresh\n * transcription is billed at the speech-to-text rate (`cost_micro_usd`). Video creatives only (400\n * `unsupported_kind`); 403 `residency_unavailable`, 503 `transcription_unavailable`.\n */\n captions(\n id: string,\n body: CreativeCaptionsRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeCaptionsResult> {\n return this.http.json<CreativeCaptionsResult>(path(id, '/captions'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The captions as SubRip text on the document timeline (`node_id`, `seq` optional); 404 without captions. Free. */\n async captionsSrt(\n id: string,\n query: CreativeCaptionsQuery = {},\n opts: CallOpts = {},\n ): Promise<string> {\n const res = await this.http.request(path(id, '/captions.srt'), {\n query: { node_id: query.node_id, seq: query.seq, locale: query.locale },\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /** The captions as WebVTT text on the document timeline (`node_id`, `seq` optional); 404 without captions. Free. */\n async captionsVtt(\n id: string,\n query: CreativeCaptionsQuery = {},\n opts: CallOpts = {},\n ): Promise<string> {\n const res = await this.http.request(path(id, '/captions.vtt'), {\n query: { node_id: query.node_id, seq: query.seq, locale: query.locale },\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /**\n * Adapt to platforms (`tiktok`, `reels`, `shorts`, `feed-square`, `feed-portrait`, `youtube`): one format per\n * platform in one new version, text kept inside each platform's safe zone and above its legible size.\n * `focal: 'vision'` (token-metered) finds the focal point of full-bleed images; it fails open. Free otherwise.\n */\n adapt(id: string, body: CreativeAdaptRequest, opts: CallOpts = {}): Promise<CreativeAdaptResult> {\n return this.http.json<CreativeAdaptResult>(path(id, '/adapt'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Fix lint issues as one new version: deterministic fixes (free) for `off_brand_color`, `text_too_small`,\n * `outside_platform_safe_zone` and `flashing` (`codes` limits them); `agent: true` (token-metered) gives the rest\n * to one `codai` turn. Nothing to fix: the current `seq`, empty `fixed`, no new version.\n */\n lintFix(\n id: string,\n body: CreativeLintFixRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeLintFixResult> {\n return this.http.json<CreativeLintFixResult>(path(id, '/lint/fix'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * The tweak panel model: one control per variable (stored `meta.controls` entry or derived from the type). Change\n * values with a `setVar` op and controls with a `setControl` op (`edit`). Free.\n */\n controls(id: string, opts: CallOpts = {}): Promise<CreativeControls> {\n return this.http.json<CreativeControls>(path(id, '/controls'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Localisation state: source locale, glossary, unit count and per locale translated / missing / stale / voice.\n * With `locale` (+ `units`, default 1) also the units of that locale (paged with `offset` / `limit` ≤ 500). Free.\n */\n locales(\n id: string,\n query: CreativeLocalesQuery = {},\n opts: CallOpts = {},\n ): Promise<CreativeLocaleStatus> {\n return this.http.json<CreativeLocaleStatus>(path(id, '/locales'), {\n query: { locale: query.locale, units: query.units, offset: query.offset, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Translate every text into up to 10 BCP-47 `locales` as per-locale overrides (one new version, author `agent`).\n * Token-metered `codai` turns; `glossary` terms and the brand kit name stay verbatim, `tone` picks the address,\n * `only_missing` (default true) skips fresh translations, `voice: true` (video, billed) narrates voice clips again.\n * 400 `nothing_to_translate`; 503 `localize_unavailable` when every locale failed.\n */\n localize(\n id: string,\n body: CreativeLocalizeRequest,\n opts: CallOpts = {},\n ): Promise<CreativeLocalizeResult> {\n return this.http.json<CreativeLocalizeResult>(path(id, '/localize'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Save `locale` as a new standalone creative (translations applied, overrides dropped, `fork_of` recorded; default\n * title `<title> (<locale>)`). 404 `Locale not found.`. Free (HTTP 201).\n */\n forkLocale(\n id: string,\n locale: string,\n body: CreativeLocaleForkRequest = {},\n opts: CallOpts = {},\n ): Promise<CreativeLocaleForkResult> {\n return this.http.json<CreativeLocaleForkResult>(\n path(id, `/locales/${encodeURIComponent(locale)}/fork`),\n {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n }\n\n /**\n * Create a public link: `view` (read-only preview of version `seq` or the head; `allow_remix` default false) or\n * `review` (comments by name, no account; `can_approve` lets the holder approve). The `token` and `url` are shown\n * only in this answer (HTTP 201). 400 `unknown_seq`; 409 `too_many_shares` (20 active links). Free.\n */\n createShare(\n id: string,\n body: StudioShareCreateRequest,\n opts: CallOpts = {},\n ): Promise<StudioShareCreated> {\n return this.http.json<StudioShareCreated>(path(id, '/shares'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The active links (not revoked, not expired), newest first; `url` is always null. Free. */\n listShares(id: string, opts: CallOpts = {}): Promise<StudioShareList> {\n return this.http.json<StudioShareList>(path(id, '/shares'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Revoke a link: it answers 404 from now on. 404 when unknown or already revoked. Free. */\n async revokeShare(id: string, shareId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(path(id, `/shares/${encodeURIComponent(shareId)}`), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * The review state: `status` (`draft` → `in_review` → `approved` | `changes_requested`), requested / approved\n * version (`approved_is_head` false once the creative changed), decider and thread counts. Free.\n */\n review(id: string, opts: CallOpts = {}): Promise<StudioReview> {\n return this.http.json<StudioReview>(path(id, '/review'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Send the head to review (`in_review`, earlier decision cleared) so approver links can decide. Free. */\n requestReview(id: string, opts: CallOpts = {}): Promise<StudioReview> {\n return this.http.json<StudioReview>(path(id, '/review'), {\n method: 'POST',\n body: { action: 'request' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Back to `draft` (decision cleared, comments kept). Free. */\n resetReview(id: string, opts: CallOpts = {}): Promise<StudioReview> {\n return this.http.json<StudioReview>(path(id, '/review'), {\n method: 'POST',\n body: { action: 'reset' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Comment threads, newest first (≤ 200), replies oldest first; `status` `open` | `resolved` | `all`. Free. */\n reviewThreads(\n id: string,\n query: StudioReviewThreadsQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioReviewThreadList> {\n return this.http.json<StudioReviewThreadList>(path(id, '/review/threads'), {\n query: { status: query.status },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Start a thread as the owner, optionally anchored to `node_id` / `scene_id` / `t_ms` (checked against the head:\n * 400 `unknown_node` / `unknown_scene`; HTTP 201). 409 `too_many_comments`. Free.\n */\n createReviewThread(\n id: string,\n body: StudioReviewThreadCreateRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(path(id, '/review/threads'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Reply in a thread as the owner (HTTP 201) — returns the whole thread. Free. */\n replyReviewThread(\n id: string,\n threadId: string,\n body: { body: string },\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(\n path(id, `/review/threads/${encodeURIComponent(threadId)}/replies`),\n {\n method: 'POST',\n body: { body: body.body },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n }\n\n /** Resolve a thread. Free. */\n resolveReviewThread(\n id: string,\n threadId: string,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(\n path(id, `/review/threads/${encodeURIComponent(threadId)}/resolve`),\n { method: 'POST', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** Reopen a resolved thread. Free. */\n reopenReviewThread(\n id: string,\n threadId: string,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(\n path(id, `/review/threads/${encodeURIComponent(threadId)}/reopen`),\n { method: 'POST', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** Delete any comment (owner moderation; deleting a root hides the thread). 404 when unknown. Free. */\n async deleteReviewComment(id: string, commentId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(path(id, `/review/comments/${encodeURIComponent(commentId)}`), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Poll a frame job: frames when done (`status: 'succeeded'`), `status: 'running'` meanwhile; 404 unknown job. */\n frameJob(id: string, jobId: string, opts: CallOpts = {}): Promise<CreativeFrameResult> {\n return this.http.json<CreativeFrameResult>(path(id, `/frames/${encodeURIComponent(jobId)}`), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * codai Studio brand kits — reusable brand tokens (5 colour roles + extras, 2 fonts, optional radius) stored as a\n * Design Tokens (DTCG 2025.10) document, plus a logo.\n *\n * `POST /v1/studio/brand-kits` — create from flat `tokens` or a DTCG document (`create`), HTTP 201\n * `PATCH /v1/studio/brand-kits/{id}` — edit name / tokens (merged) / dtcg (replaced) / logo (`update`)\n * `GET /v1/studio/brand-kits/{id}/dtcg` — the kit as a DTCG JSON document (`exportDtcg`)\n * `POST /v1/studio/brand-kits/extract` — from a public https page (`{ url }`) or a logo image asset\n * (`{ logo_asset_id }`); one `codai` turn (`extract`, token-metered)\n * `GET /v1/studio/brand-kits` — your kits, newest first (`list`)\n * `GET /v1/studio/brand-kits/{id}` — one kit with a signed logo URL (`retrieve`)\n * `DELETE /v1/studio/brand-kits/{id}` — soft delete (`delete`)\n *\n * Apply a kit when creating a creative (`creatives.create({ kind, brand_kit_id })`), re-apply it to an existing one\n * with `creatives.restyle(id, { brand_kit_id })`, or set tokens directly with a `setBrand` op.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type BrandKit = Schema<'BrandKit'>;\nexport type BrandKitTokens = Schema<'BrandKitTokens'>;\nexport type BrandKitDtcg = Mutable<Schema<'BrandKitDtcg'>>;\nexport type BrandKitContrastPair = Schema<'BrandKitContrastPair'>;\n/** `{ url, name? }` (a web page) or `{ logo_asset_id, name? }` (one of your image assets) — exactly one source. */\nexport type BrandKitExtractRequest = Mutable<Body<'extractBrandKit'>>;\n/** `{ name, tokens }` or `{ name, dtcg }` (exactly one), optional `logo_asset_id` / `source_url`. */\nexport type BrandKitCreateRequest = Mutable<Body<'createBrandKit'>>;\n/** At least one of `name`, `tokens` (partial, merged), `dtcg` (replaces), `logo_asset_id` (`null` removes). */\nexport type BrandKitUpdateRequest = Mutable<Body<'updateBrandKit'>>;\nexport type BrandKitList = Reply<'listBrandKits'>;\nexport type BrandKitDeleted = Reply<'deleteBrandKit'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst path = (id: string, tail = '') => `/v1/studio/brand-kits/${encodeURIComponent(id)}${tail}`;\n\nexport class BrandKits {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a kit you define: flat `tokens` (the 5 colours `#rrggbb`, optional fonts) or a DTCG document in `dtcg`\n * (import) — exactly one. 400 `invalid_tokens` (with `details.issues`) for an invalid DTCG document, 404 when\n * `logo_asset_id` is not one of your ready image assets. Free.\n */\n create(body: BrandKitCreateRequest, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>('/v1/studio/brand-kits', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Edit a kit: `tokens` is merged onto the current kit, `dtcg` replaces the whole document (not both),\n * `logo_asset_id: null` removes the logo. Creatives keep their tokens until `creatives.restyle`. Free.\n */\n update(id: string, body: BrandKitUpdateRequest, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>(path(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The kit as a DTCG 2025.10 JSON document (`$extensions['ro.codai']` = kit id, name, logo asset id). Free. */\n exportDtcg(id: string, opts: CallOpts = {}): Promise<BrandKitDtcg> {\n return this.http.json<BrandKitDtcg>(path(id, '/dtcg'), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Extract a brand kit from a public `https` page (`{ url }`) or from one of your logo images\n * (`{ logo_asset_id }`, PNG / JPEG / WebP up to 5 MB; it becomes the kit logo): palette (primary, secondary, accent,\n * background, text) and heading / body fonts. One bounded `codai` model call (token-metered); 400 `url_blocked` for\n * private hosts, 400 `unsupported_media` for a bad logo, 422 `fetch_failed` / `extract_failed`, 504 `timeout`.\n */\n extract(body: BrandKitExtractRequest, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>('/v1/studio/brand-kits/extract', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Your brand kits, newest first (`limit` 1–100, default 50). Free. */\n list(query: { limit?: number } = {}, opts: CallOpts = {}): Promise<BrandKitList> {\n return this.http.json<BrandKitList>('/v1/studio/brand-kits', {\n query: { limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** One kit with a signed logo URL (1 h), its `dtcg` and the WCAG `contrast` pairs. Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<BrandKit> {\n return this.http.json<BrandKit>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** Delete a kit (creatives keep their tokens; the logo asset stays). Free. */\n delete(id: string, opts: CallOpts = {}): Promise<BrandKitDeleted> {\n return this.http.json<BrandKitDeleted>(path(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * codai Studio templates — private, reusable creative documents with variables, saved from your own creatives.\n *\n * `POST /v1/studio/creatives/{id}/template` — save a creative as a template (`creatives.saveTemplate`), HTTP 201\n * `GET /v1/studio/templates` — your templates (newest first), then the 40 built-in starters\n * (`source: \"starter\"`, ids `starter:<slug>:<en|ro>`) (`list`, without `doc`)\n * `GET /v1/studio/templates/{id}` — one template with its `doc` (`retrieve`)\n * `DELETE /v1/studio/templates/{id}` — soft delete (`delete`)\n *\n * Create a creative from a template with `creatives.create({ kind, template, vars })`. Everything here is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type CreativeTemplateVar = Schema<'CreativeTemplateVar'>;\nexport type CreativeTemplateList = Reply<'listCreativeTemplates'>;\nexport type CreativeTemplateListQuery = QueryOf<'listCreativeTemplates'>;\nexport type CreativeTemplateDeleted = Reply<'deleteCreativeTemplate'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst path = (id: string) => `/v1/studio/templates/${encodeURIComponent(id)}`;\n\nexport class Templates {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Your templates (newest first; `limit` 1–100, default 50), then the built-in starters in `locale` (`en` | `ro`,\n * default from Accept-Language) with in-season ones first (`month` 1–12). `source`: `own` | `starter` | `all`\n * (default). `kind` filters both. Without `doc`. Free. A starter id works anywhere a template id does\n * (`retrieve`, `creatives.create({ template })`, batches); starters cannot be deleted.\n */\n list(query: CreativeTemplateListQuery = {}, opts: CallOpts = {}): Promise<CreativeTemplateList> {\n return this.http.json<CreativeTemplateList>('/v1/studio/templates', {\n query: {\n kind: query.kind,\n limit: query.limit,\n source: query.source,\n locale: query.locale,\n month: query.month,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** One template with its variables and `doc`. Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<Schema<'CreativeTemplate'>> {\n return this.http.json<Schema<'CreativeTemplate'>>(path(id), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Delete a template (creatives made from it are not affected). Free. */\n delete(id: string, opts: CallOpts = {}): Promise<CreativeTemplateDeleted> {\n return this.http.json<CreativeTemplateDeleted>(path(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/studio/productions` — codai Studio brief → finished promo video (RC-20).\n *\n * `POST /v1/studio/productions` — storyboard on a built-in starter, images + voice-over, an editable creative and\n * a draft render (`create`, 202, ~1 min)\n * `GET /v1/studio/productions/{id}` — the production (`retrieve`); reading it advances render → review → repair →\n * ready like a poll\n *\n * `wait(id)` polls until `status` is `succeeded` or `failed`; `run(body)` = `create` + `wait`. The storyboard and\n * review turns are token-metered; images, voice-over and renders are billed at their usual prices; `budget_micro_usd`\n * (default $3) caps the whole production.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Schema } from './_shared';\n\nexport type StudioProductionCreate = Mutable<Body<'createStudioProduction'>>;\nexport type StudioProduction = Schema<'StudioProduction'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface ProductionCreateOptions extends CallOpts {\n /** `Idempotency-Key`: a retry with the same key replays the first production instead of starting another one. */\n idempotencyKey?: string;\n}\n\nexport interface ProductionWaitOptions extends CallOpts {\n /** Delay between polls (default 5000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 600 000 ms = 10 min). */\n timeoutMs?: number;\n}\n\nconst path = (id: string) => `/v1/studio/productions/${encodeURIComponent(id)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport const isProductionFinished = (p: Pick<StudioProduction, 'status'>): boolean =>\n p.status === 'succeeded' || p.status === 'failed';\n\nexport class Productions {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/studio/productions` — brief → storyboard → assets → creative → queued draft render (202). */\n create(\n body: StudioProductionCreate,\n opts: ProductionCreateOptions = {},\n ): Promise<StudioProduction> {\n return this.http.json<StudioProduction>('/v1/studio/productions', {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/studio/productions/{id}` — advances the production and returns it (another account's id is a 404). */\n retrieve(id: string, opts: CallOpts = {}): Promise<StudioProduction> {\n return this.http.json<StudioProduction>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Poll `retrieve` every `intervalMs` (default 5 s) until the production `succeeded` or `failed` (a failed one\n * resolves too — check `status` / `error`). Throws after `timeoutMs` (default 10 min) or when `signal` aborts.\n */\n async wait(id: string, opts: ProductionWaitOptions = {}): Promise<StudioProduction> {\n const interval = opts.intervalMs ?? 5_000;\n const deadline = Date.now() + (opts.timeoutMs ?? 600_000);\n for (;;) {\n const p = await this.retrieve(id, opts);\n if (isProductionFinished(p)) return p;\n if (Date.now() + interval > deadline)\n throw new Error(`codai: production ${id} did not finish in time (phase ${p.phase})`);\n await abortableSleep(interval, opts.signal);\n }\n }\n\n /** `create` + `wait`. */\n async run(\n body: StudioProductionCreate,\n opts: ProductionCreateOptions & ProductionWaitOptions = {},\n ): Promise<StudioProduction> {\n const p = await this.create(body, opts);\n return isProductionFinished(p) ? p : this.wait(p.id, opts);\n }\n}\n","/**\n * `/v1/studio/media-ops` — codai Studio media operations on your assets (AR-02).\n *\n * `GET /v1/studio/media-ops` — the op catalogue with list quotes and availability (`list`, free)\n * `POST /v1/studio/media-ops/{op}/quote` — exact price of a request, same validation as the run (`quote`, free)\n * `POST /v1/studio/media-ops/{op}` — run: 200 with the outputs (sync ops) or 202 with a job (async ops)\n * (`run`; `Idempotency-Key` honoured)\n * `GET /v1/studio/media-ops/jobs/{id}` — an async job; a finished one is settled on read (`job`)\n *\n * Ops: `image.remove_background` / `upscale` / `inpaint` / `outpaint` / `erase`, `audio.separate_stems` / `denoise` /\n * `to_midi` / `master` / `analyze`, `music.generate_ace` / `repaint` / `extend` / `cover`, `sfx.generate`. The quote is\n * held on the wallet (402 `insufficient_funds`), the measured cost billed once. Every output is AI-marked and carries\n * lineage (`parent_asset_id`, `op`, `op_inputs`). A lane that is not configured answers 503 `media_ops_unavailable`.\n * `wait(id)` polls a job until it is `ready` or `failed`; `runAndWait` = `run` + `wait` for async ops.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Reply, type Schema } from './_shared';\n\nexport type MediaOpId = Schema<'MediaOpId'>;\nexport type MediaOp = Schema<'MediaOp'>;\nexport type MediaOpList = Reply<'listStudioMediaOps'>;\nexport type MediaOpRequest = Mutable<Schema<'MediaOpRequest'>>;\nexport type MediaOpQuote = Schema<'MediaOpQuote'>;\nexport type MediaOpResult = Schema<'MediaOpResult'>;\nexport type MediaOpJob = Schema<'MediaOpJob'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface MediaOpInput {\n /** Owned, ready Studio asset ids in the order the op expects (mask second for inpaint / erase). */\n assetIds?: string[];\n /** Per-op parameters (validated strictly by the gateway; see the docs table). */\n params?: Record<string, unknown>;\n /**\n * `image.inpaint` / `image.erase` only: a mask painted in an editor, base64 PNG (white = edit, black = keep, at most\n * 8 MB). Send ONE asset id (the image); the gateway stores the mask as a free private asset and passes it as the\n * second input. A quote validates it without storing anything.\n */\n maskPngB64?: string;\n}\n\nexport interface MediaOpRunOptions extends CallOpts {\n /** `Idempotency-Key`: a retry with the same key replays the first answer instead of running (and billing) again. */\n idempotencyKey?: string;\n}\n\nexport interface MediaOpWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 1 200 000 ms = 20 min, the server-side job timeout). */\n timeoutMs?: number;\n}\n\nconst BASE = '/v1/studio/media-ops';\nconst opPath = (op: string) => `${BASE}/${encodeURIComponent(op)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nconst toBody = (input: MediaOpInput): MediaOpRequest => ({\n asset_ids: input.assetIds ?? [],\n params: input.params ?? {},\n ...(input.maskPngB64 !== undefined ? { mask_png_b64: input.maskPngB64 } : {}),\n});\n\n/** A run answer is a job (async op, HTTP 202) when `object` is `media_op.job`. */\nexport const isMediaOpJob = (r: MediaOpResult | MediaOpJob): r is MediaOpJob =>\n r.object === 'media_op.job';\n\nexport const isMediaOpJobFinished = (j: Pick<MediaOpJob, 'status'>): boolean =>\n j.status === 'ready' || j.status === 'failed';\n\nexport class MediaOps {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/studio/media-ops` — every op with engine, mode, inputs, `available` and a list quote (free). */\n list(opts: CallOpts = {}): Promise<MediaOpList> {\n return this.http.json<MediaOpList>(BASE, { ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/studio/media-ops/{op}/quote` — exact price of this request; nothing is held or billed. */\n quote(\n op: MediaOpId | string,\n input: MediaOpInput = {},\n opts: CallOpts = {},\n ): Promise<MediaOpQuote> {\n return this.http.json<MediaOpQuote>(`${opPath(op)}/quote`, {\n method: 'POST',\n body: toBody(input),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/studio/media-ops/{op}` — sync ops resolve to a `media_op.result` with the outputs, async ops to a\n * `media_op.job` (`status: pending`; poll with `job` / `wait`). Use `isMediaOpJob` to tell them apart.\n */\n run(\n op: MediaOpId | string,\n input: MediaOpInput = {},\n opts: MediaOpRunOptions = {},\n ): Promise<MediaOpResult | MediaOpJob> {\n return this.http.json<MediaOpResult | MediaOpJob>(opPath(op), {\n method: 'POST',\n body: toBody(input),\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/studio/media-ops/jobs/{id}` — the job; reading a finished one stores its outputs and bills it once. */\n job(id: string, opts: CallOpts = {}): Promise<MediaOpJob> {\n return this.http.json<MediaOpJob>(`${BASE}/jobs/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Poll `job` every `intervalMs` (default 3 s) until it is `ready` or `failed` (a failed job resolves too — check\n * `status` / `error`). Throws after `timeoutMs` (default 20 min) or when `signal` aborts.\n */\n async wait(id: string, opts: MediaOpWaitOptions = {}): Promise<MediaOpJob> {\n const interval = opts.intervalMs ?? 3_000;\n const deadline = Date.now() + (opts.timeoutMs ?? 1_200_000);\n for (;;) {\n const j = await this.job(id, opts);\n if (isMediaOpJobFinished(j)) return j;\n if (Date.now() + interval > deadline)\n throw new Error(`codai: media job ${id} did not finish in time (status ${j.status})`);\n await abortableSleep(interval, opts.signal);\n }\n }\n\n /** `run`, then `wait` when the op is async. */\n async runAndWait(\n op: MediaOpId | string,\n input: MediaOpInput = {},\n opts: MediaOpRunOptions & MediaOpWaitOptions = {},\n ): Promise<MediaOpResult | MediaOpJob> {\n const r = await this.run(op, input, opts);\n return isMediaOpJob(r) && !isMediaOpJobFinished(r) ? this.wait(r.id, opts) : r;\n }\n}\n","/**\n * `/v1/studio/lyrics` — codai Studio lyrics writer and karaoke alignment (MU-06).\n *\n * `POST /v1/studio/lyrics` — write original lyrics for a brief (`write`), checked for syllables per line and\n * the rhyme scheme; one repair turn when more than 30 % of the lines miss.\n * Token-metered (`codai::lyrics`) under a small wallet hold.\n * `POST /v1/studio/lyrics/align` — align written lyrics to one clip of an audio / video creative (`align`): timed\n * lines applied with one `setLyrics` edit (unless `apply: false`) + an LRC file.\n * Cached clip words are free; a fresh transcription bills `codai::lyrics-align`.\n *\n * Both honour `Idempotency-Key`. 402 `insufficient_funds` when the hold does not fit; alignment is 403\n * `residency_unavailable` for EU data-residency accounts.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema } from './_shared';\n\nexport type LyricsRequest = Mutable<Schema<'StudioLyricsRequest'>>;\nexport type LyricsSectionKind = Schema<'StudioLyricsSectionKind'>;\nexport type LyricsLine = Schema<'StudioLyricsLine'>;\nexport type Lyrics = Schema<'StudioLyrics'>;\nexport type LyricsAlignRequest = Mutable<Schema<'StudioLyricsAlignRequest'>>;\nexport type LyricsAlignment = Schema<'StudioLyricsAlignment'>;\n\nexport interface LyricsCallOptions {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n /** `Idempotency-Key`: a retry with the same key replays the first answer instead of running (and billing) again. */\n idempotencyKey?: string;\n}\n\nconst BASE = '/v1/studio/lyrics';\n\nexport class LyricsResource {\n constructor(private readonly http: HttpClient) {}\n\n private post<T>(path: string, body: unknown, opts: LyricsCallOptions): Promise<T> {\n return this.http.json<T>(path, {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/studio/lyrics` — `{ brief, language: 'ro' | 'en', genre?, mood?, structure?, syllables_per_line?,\n * rhyme_scheme?, lines_per_section?, title? }` → `studio.lyrics` with every line's syllables and rhyme letter, the\n * whole song as `text` (`[kind]` headers) and a `report`. `repaired: true` when the repair turn won.\n */\n write(body: LyricsRequest, opts: LyricsCallOptions = {}): Promise<Lyrics> {\n return this.post<Lyrics>(BASE, body, opts);\n }\n\n /**\n * `POST /v1/studio/lyrics/align` — `{ creative_id, clip_id, lyrics_text, language?, apply?, base_seq?,\n * retranscribe? }` → `studio.lyrics_alignment`: timed `lines`, `lrc`, `match_ratio`, `cached`, and `seq` /\n * `doc_hash` of the new version when applied.\n */\n align(body: LyricsAlignRequest, opts: LyricsCallOptions = {}): Promise<LyricsAlignment> {\n return this.post<LyricsAlignment>(`${BASE}/align`, body, opts);\n }\n}\n","/**\n * `wss://…/v1/studio/jam` — codai Studio live jam (MU-09): live generated music (Lyria RealTime) steered with weighted\n * prompts. Not an OpenAPI operation (OpenAPI cannot describe WebSockets), so it is outside `OPERATION_METHODS`.\n *\n * const jam = codai.jam.connect({ token }); // browser: ephemeral token (scope realtime | live)\n * jam.on('audio', (pcm) => player.push(pcm)); // PCM16 LE interleaved stereo at 48 kHz\n * jam.prompts([{ text: 'warm lo-fi piano', weight: 1 }]);\n * jam.config({ bpm: 90, density: 0.4 });\n * jam.play();\n *\n * Auth: server runtimes send `Authorization: Bearer <key>` (needs a WebSocket constructor that accepts headers, e.g.\n * `ws`); browsers send the subprotocols `codai-jam` + `bearer.<token>` (the server answers `codai-jam` and never echoes\n * the credential). Raw long-lived keys are never put in the URL.\n *\n * Close codes: 4400 invalid message, 4401 credentials, 4402 insufficient funds, 4403 EU residency / not allowed / spend\n * cap, 4408 10-minute limit, 4409 another jam already open, 4502 upstream error, 4503 not configured. Billed $0.03 per\n * started minute of the open upstream session (`codai::jam`); the 10-minute price is held when the session opens.\n */\nimport type { RealtimeSocket, RealtimeSocketCtor } from './realtime';\n\nexport const JAM_SUBPROTOCOL = 'codai-jam';\n\n/** WebSocket close codes of `/v1/studio/jam`. */\nexport const JAM_CLOSE_CODES = {\n invalidMessage: 4400,\n unauthorized: 4401,\n insufficientFunds: 4402,\n forbidden: 4403,\n maxDuration: 4408,\n busy: 4409,\n upstream: 4502,\n unavailable: 4503,\n} as const;\n\nexport const JAM_SCALES = [\n 'SCALE_UNSPECIFIED',\n 'C_MAJOR_A_MINOR',\n 'D_FLAT_MAJOR_B_FLAT_MINOR',\n 'D_MAJOR_B_MINOR',\n 'E_FLAT_MAJOR_C_MINOR',\n 'E_MAJOR_D_FLAT_MINOR',\n 'F_MAJOR_D_MINOR',\n 'G_FLAT_MAJOR_E_FLAT_MINOR',\n 'G_MAJOR_E_MINOR',\n 'A_FLAT_MAJOR_F_MINOR',\n 'A_MAJOR_G_FLAT_MINOR',\n 'B_FLAT_MAJOR_G_MINOR',\n 'B_MAJOR_A_FLAT_MINOR',\n] as const;\nexport type JamScale = (typeof JAM_SCALES)[number];\n\n/** A weighted prompt: 1..8 per message, `weight` in [-10, 10] and not 0. */\nexport interface JamPrompt {\n text: string;\n weight: number;\n}\n\n/** Partial config; the server merges it into the last full config. bpm / scale changes reset the context. */\nexport interface JamConfig {\n bpm?: number;\n density?: number;\n brightness?: number;\n scale?: JamScale;\n}\n\nexport type JamClientMessage =\n | { type: 'prompts'; prompts: JamPrompt[] }\n | ({ type: 'config' } & JamConfig)\n | { type: 'play' | 'pause' | 'stop' | 'reset' };\n\nexport type JamState =\n 'connecting' | 'ready' | 'playing' | 'paused' | 'stopped' | (string & Record<never, never>);\n\nexport type JamEvent =\n | {\n type: 'status';\n state: JamState;\n remaining_ms: number;\n sample_rate?: number;\n channels?: number;\n }\n | { type: 'filtered'; text: string; reason: string }\n | { type: 'error'; code: string; message: string }\n /** Emitted by the client for every binary frame. */\n | { type: 'audio'; data: ArrayBuffer }\n /** Emitted by the client itself when the socket closes (always the last event). */\n | { type: 'close'; code: number; reason: string };\n\nexport interface JamConnectOptions {\n /** Ephemeral token (scope `realtime` or `live`) — sent as the `bearer.<token>` subprotocol. Required in browsers. */\n token?: string;\n /** API key — sent as `Authorization: Bearer` (needs a ctor that supports headers). */\n apiKey?: string;\n /** Conversation id recorded on the usage row (`?session_id=`). */\n sessionId?: string;\n /** Injectable WebSocket constructor (tests, `ws` on older Node). Defaults to `globalThis.WebSocket`. */\n WebSocket?: RealtimeSocketCtor;\n /** Override the gateway base URL (default: the client's `baseUrl`). */\n baseUrl?: string;\n}\n\ntype Listener<T extends JamEvent['type']> = (ev: Extract<JamEvent, { type: T }>) => void;\ntype AnyListener = (ev: JamEvent) => void;\n\nconst OPEN = 1;\n\nfunction toArrayBuffer(data: unknown): ArrayBuffer | null {\n if (data instanceof ArrayBuffer) return data;\n if (ArrayBuffer.isView(data)) {\n const v = data as ArrayBufferView;\n return v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength) as ArrayBuffer;\n }\n return null;\n}\n\n/** A live jam session: `on()` listeners for status / audio / errors and typed senders. */\nexport class JamSession {\n private readonly listeners = new Map<string, Set<AnyListener>>();\n private readonly outbox: string[] = [];\n private closed = false;\n /** Resolves when the socket is open (rejects if it closes first). */\n readonly ready: Promise<void>;\n\n constructor(readonly socket: RealtimeSocket) {\n let resolveReady!: () => void;\n let rejectReady!: (e: Error) => void;\n this.ready = new Promise<void>((res, rej) => {\n resolveReady = res;\n rejectReady = rej;\n });\n this.ready.catch(() => undefined);\n socket.onopen = () => {\n for (const f of this.outbox.splice(0)) socket.send(f);\n resolveReady();\n };\n socket.onmessage = (ev) => {\n if (typeof ev.data !== 'string') {\n const buf = toArrayBuffer(ev.data);\n if (buf) this.emit({ type: 'audio', data: buf });\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(ev.data);\n } catch {\n return;\n }\n if (\n parsed &&\n typeof parsed === 'object' &&\n typeof (parsed as { type?: unknown }).type === 'string'\n )\n this.emit(parsed as JamEvent);\n };\n socket.onerror = () => {\n /* the close event carries the code */\n };\n socket.onclose = (ev) => {\n rejectReady(new Error(`jam socket closed before open (${String(ev.code)} ${ev.reason})`));\n this.closed = true;\n this.emit({ type: 'close', code: ev.code, reason: ev.reason });\n };\n }\n\n /** Listen for one event type (`'*'` = every event). Returns an unsubscribe function. */\n on<T extends JamEvent['type']>(type: T, fn: Listener<T>): () => void;\n on(type: '*', fn: AnyListener): () => void;\n on(type: string, fn: AnyListener): () => void {\n let set = this.listeners.get(type);\n if (!set) this.listeners.set(type, (set = new Set()));\n set.add(fn);\n return () => set.delete(fn);\n }\n\n /** Send one client message (JSON). Queued until the socket opens. */\n send(msg: JamClientMessage): void {\n if (this.closed) throw new Error('jam session is closed');\n const frame = JSON.stringify(msg);\n if (this.socket.readyState === OPEN) this.socket.send(frame);\n else this.outbox.push(frame);\n }\n\n prompts(prompts: JamPrompt[]): void {\n this.send({ type: 'prompts', prompts });\n }\n\n config(config: JamConfig): void {\n this.send({ type: 'config', ...config });\n }\n\n play(): void {\n this.send({ type: 'play' });\n }\n\n pause(): void {\n this.send({ type: 'pause' });\n }\n\n stop(): void {\n this.send({ type: 'stop' });\n }\n\n reset(): void {\n this.send({ type: 'reset' });\n }\n\n close(code = 1000, reason = 'client closed'): void {\n if (this.closed) return;\n this.socket.close(code, reason);\n }\n\n private emit(ev: JamEvent): void {\n for (const fn of this.listeners.get(ev.type) ?? []) fn(ev);\n for (const fn of this.listeners.get('*') ?? []) fn(ev);\n }\n}\n\n/** Build the `wss://…/v1/studio/jam` URL (exported for tests and custom transports). */\nexport function jamUrl(baseUrl: string, opts: Pick<JamConnectOptions, 'sessionId'> = {}): string {\n const url = new URL(`${baseUrl.replace(/\\/$/, '').replace(/^http/, 'ws')}/v1/studio/jam`);\n if (opts.sessionId) url.searchParams.set('session_id', opts.sessionId);\n return url.toString();\n}\n\nexport class Jam {\n constructor(private readonly defaults: { baseUrl: string; apiKey?: string }) {}\n\n /** Open a live jam. Returns immediately; `await session.ready` to wait for the socket. */\n connect(opts: JamConnectOptions = {}): JamSession {\n const Ctor = opts.WebSocket ?? (globalThis as { WebSocket?: RealtimeSocketCtor }).WebSocket;\n if (!Ctor) throw new Error('codai.jam: no WebSocket available — pass options.WebSocket');\n let token = opts.token;\n let apiKey = token ? undefined : (opts.apiKey ?? this.defaults.apiKey);\n if (apiKey?.startsWith('codai_eph_v1.')) {\n token = apiKey;\n apiKey = undefined;\n }\n if (!token && !apiKey) throw new Error('codai.jam: pass `token` (browser) or `apiKey`');\n const url = jamUrl(opts.baseUrl ?? this.defaults.baseUrl, opts);\n const socket = apiKey\n ? new Ctor(url, [JAM_SUBPROTOCOL], { headers: { Authorization: `Bearer ${apiKey}` } })\n : new Ctor(url, [JAM_SUBPROTOCOL, `bearer.${token!}`]);\n if ('binaryType' in socket) socket.binaryType = 'arraybuffer';\n return new JamSession(socket);\n }\n}\n","/**\n * codai Studio batches — one creative per CSV / sheet row, from a template or a creative with variables.\n *\n * `POST /v1/studio/batches` — create (`create`, HTTP 201) or validate only (`dryRun`, HTTP 200)\n * `GET /v1/studio/batches` — your batches, newest first (`list`)\n * `GET /v1/studio/batches/{id}` — the batch (+ rows with `rows: 1`); every poll advances it (`get`)\n * `POST /v1/studio/batches/{id}/cancel` — stop it; rows not started become `skipped` (`cancel`)\n * `POST /v1/studio/batches/{id}/retry` — queue the failed rows again (`retry`)\n * `GET /v1/studio/batches/{id}/export.csv` — the original rows + `creative_id,status,error,render_url` (`exportCsv`)\n * `POST /v1/studio/batches/{id}/zip` — build a ZIP of the finished renders (`zip`, HTTP 202)\n *\n * `wait(id)` polls `get` until the batch is `completed`, `failed` or `cancelled`. Creating a batch is free; rows with a\n * `locale` column are translated (token-metered) and `render: true` renders every row (billed like any render).\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type QueryOf, type Schema, stripUndefined } from './_shared';\n\nexport type StudioBatchStatus = Schema<'StudioBatchStatus'>;\nexport type StudioBatchRowStatus = Schema<'StudioBatchRowStatus'>;\nexport type StudioBatch = Schema<'StudioBatch'>;\nexport type StudioBatchRow = Schema<'StudioBatchRow'>;\nexport type StudioBatchColumn = Schema<'StudioBatchColumn'>;\n/** `{ batch, rows? }` (rows only with `rows: 1`). */\nexport type StudioBatchDetail = Schema<'StudioBatchDetail'>;\nexport type StudioBatchList = Schema<'StudioBatchList'>;\nexport type StudioBatchDryRun = Schema<'StudioBatchDryRun'>;\n/**\n * `source` (`{ template_id }` or `{ creative_id, seq? }`) + exactly one of `csv` / `sheet`, optional `delimiter`,\n * `mapping` (column → variable, `null` ignores), `title`, `render`, `quality`, `ai_label`, `format`, `localize`, `dry_run`.\n */\nexport type StudioBatchCreateRequest = Mutable<Schema<'StudioBatchCreateRequest'>>;\nexport type StudioBatchListQuery = QueryOf<'listStudioBatches'>;\nexport type StudioBatchGetQuery = QueryOf<'getStudioBatch'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface BatchWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 600 000 ms = 10 min). */\n timeoutMs?: number;\n}\n\nconst BATCH_DONE: readonly StudioBatchStatus[] = ['completed', 'failed', 'cancelled'];\n\nconst path = (id: string, tail = '') => `/v1/studio/batches/${encodeURIComponent(id)}${tail}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport class Batches {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Create a batch: rows are validated (invalid rows are stored as `failed`) and run in the background; poll `get`\n * or `wait`. 400 `invalid_rows` when every row is invalid. Free (translations and renders are billed as usual).\n */\n async create(body: StudioBatchCreateRequest, opts: CallOpts = {}): Promise<StudioBatchDetail> {\n return this.http.json<StudioBatchDetail>('/v1/studio/batches', {\n method: 'POST',\n body: stripUndefined({ ...body, dry_run: false }),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Validate only (`dry_run: true`): the mapping, row errors, a 3-row preview and an estimate; nothing stored. Free. */\n dryRun(body: StudioBatchCreateRequest, opts: CallOpts = {}): Promise<StudioBatchDryRun> {\n return this.http.json<StudioBatchDryRun>('/v1/studio/batches', {\n method: 'POST',\n body: stripUndefined({ ...body, dry_run: true }),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Your batches, newest first (`limit` 1–50, `before` = the previous `next_before`). Free. */\n list(query: StudioBatchListQuery = {}, opts: CallOpts = {}): Promise<StudioBatchList> {\n return this.http.json<StudioBatchList>('/v1/studio/batches', {\n query: { limit: query.limit, before: query.before },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** The batch (`rows: 1` adds rows; `status`, `offset`, `limit` ≤ 100). Each poll advances it a little. Free. */\n get(\n id: string,\n query: StudioBatchGetQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioBatchDetail> {\n return this.http.json<StudioBatchDetail>(path(id), {\n query: { rows: query.rows, status: query.status, offset: query.offset, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Stop the batch; rows not started become `skipped`. 409 `not_cancellable` when already finished. Free. */\n cancel(id: string, opts: CallOpts = {}): Promise<StudioBatch> {\n return this.http.json<StudioBatch>(path(id, '/cancel'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Queue the failed rows again (≤ 3 attempts each). 409 `nothing_to_retry`. Free. */\n retry(id: string, opts: CallOpts = {}): Promise<StudioBatch> {\n return this.http.json<StudioBatch>(path(id, '/retry'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** The original CSV plus `creative_id`, `status`, `error`, `render_url` per row (formula-safe). Free. */\n async exportCsv(id: string, opts: CallOpts = {}): Promise<string> {\n const res = await this.http.request(path(id, '/export.csv'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /**\n * Start building a ZIP of the finished renders (202, `zip.status: 'building'`; unchanged when already building or\n * ready). Poll `get` until `zip.status` is `ready` (signed `zip.url`). 409 `no_renders`. Free.\n */\n zip(id: string, opts: CallOpts = {}): Promise<StudioBatch> {\n return this.http.json<StudioBatch>(path(id, '/zip'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * Poll `get` every `intervalMs` (default 3 s) until the batch is `completed`, `failed` or `cancelled` and resolve\n * with it. Throws when it is not done within `timeoutMs` (default 10 min) or when `signal` aborts.\n */\n async wait(id: string, opts: BatchWaitOptions = {}): Promise<StudioBatch> {\n const { intervalMs = 3000, timeoutMs = 600_000, signal, ext } = opts;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const { batch } = await this.get(id, {}, { ext, signal });\n if (BATCH_DONE.includes(batch.status)) return batch;\n if (Date.now() + intervalMs > deadline) {\n throw new Error(`codai batch ${id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(intervalMs, signal);\n }\n }\n}\n","/**\n * codai Studio share links seen from the outside — read, remix and review a creative someone shared with you.\n *\n * `GET /v1/public/studio/shares/{token}` — the shared creative (`get`; no key needed)\n * `POST /v1/studio/shares/{token}/remix` — copy a `view` link into your account (`remix`)\n * `POST /v1/public/studio/reviews/{token}/threads` — comment through a review link (`comment`)\n * `POST /v1/public/studio/reviews/{token}/threads/{threadId}/replies` — reply (`reply`)\n * `POST /v1/public/studio/reviews/{token}/threads/{threadId}/resolve|reopen` — (`resolve`, `reopen`)\n * `POST /v1/public/studio/reviews/{token}/decision` — approve / request changes (`decide`)\n *\n * Every method takes the token or the whole link (`https://hub.codai.ro/s/<token>` or `/r/<token>`). The public\n * routes ignore the API key; reviewers are identified only by the `name` they type (visible to the owner and other\n * reviewers). Owners create and revoke links with `creatives.createShare` / `creatives.revokeShare`. Everything is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema, stripUndefined } from './_shared';\nimport { type StudioReviewThread } from './creatives';\n\nexport type StudioShareKind = Schema<'StudioShareKind'>;\nexport type StudioPublicShare = Schema<'StudioPublicShare'>;\nexport type StudioPublicReview = Schema<'StudioPublicReview'>;\n/** The new creative (same shape as `creatives.create`) plus `remixed_from` and optional `warnings`. */\nexport type StudioRemixResult = Schema<'StudioRemixResult'>;\n/** Optional `title` of the new creative. */\nexport type StudioRemixRequest = Mutable<Schema<'StudioRemixRequest'>>;\n/** `name` + `body`, optional anchor `node_id` / `scene_id` / `t_ms`. */\nexport type StudioPublicThreadCreateRequest = Mutable<Schema<'StudioPublicThreadCreateRequest'>>;\n/** `name` + `body`. */\nexport type StudioPublicReplyRequest = Mutable<Schema<'StudioPublicReplyRequest'>>;\n/** `name`. */\nexport type StudioPublicNameRequest = Mutable<Schema<'StudioPublicNameRequest'>>;\n/** `name`, `decision` (`approve` | `request_changes`), `seq` (the head you reviewed), optional `note`. */\nexport type StudioPublicDecisionRequest = Mutable<Schema<'StudioPublicDecisionRequest'>>;\nexport type StudioPublicShareQuery = { format?: string; locale?: string };\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst SHARE_TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * The share token in `input`: a raw token, or any `https://…/s/<token>` / `…/r/<token>` URL (query and fragment\n * ignored). Trims; `null` for anything else (same rule as the gateway and the apps).\n */\nexport function shareTokenFrom(input: string): string | null {\n const s = input.trim();\n if (SHARE_TOKEN_RE.test(s)) return s;\n let url: URL;\n try {\n url = new URL(s);\n } catch {\n return null;\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;\n const parts = url.pathname.split('/').filter(Boolean);\n if (parts.length < 2) return null;\n const kind = parts[parts.length - 2];\n const token = parts[parts.length - 1]!;\n return (kind === 's' || kind === 'r') && SHARE_TOKEN_RE.test(token) ? token : null;\n}\n\nfunction tokenOf(tokenOrUrl: string): string {\n const token = shareTokenFrom(tokenOrUrl);\n if (!token)\n throw new TypeError('codai: not a share link or token (expected …/s/<token> or …/r/<token>)');\n return token;\n}\n\nconst review = (tokenOrUrl: string, tail: string) =>\n `/v1/public/studio/reviews/${encodeURIComponent(tokenOf(tokenOrUrl))}${tail}`;\nconst thread = (tokenOrUrl: string, threadId: string, tail: string) =>\n review(tokenOrUrl, `/threads/${encodeURIComponent(threadId)}${tail}`);\n\nexport class Shares {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * The shared creative: title, kind, version, formats, locales and the compiled preview HTML of `format` /\n * `locale` (null for images); review links add the review state and every thread. 404 for unknown, revoked or\n * expired links. No key needed.\n */\n get(\n tokenOrUrl: string,\n query: StudioPublicShareQuery = {},\n opts: CallOpts = {},\n ): Promise<StudioPublicShare> {\n return this.http.json<StudioPublicShare>(\n `/v1/public/studio/shares/${encodeURIComponent(tokenOf(tokenOrUrl))}`,\n { query: { format: query.format, locale: query.locale }, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /**\n * Copy the version a `view` link shows into a new creative of yours (the owner's ready assets are copied, the\n * foreign brand kit dropped; HTTP 201). 404 for review links or links without remix; 413 `remix_too_large`. Free.\n */\n remix(\n tokenOrUrl: string,\n body: StudioRemixRequest = {},\n opts: CallOpts = {},\n ): Promise<StudioRemixResult> {\n return this.http.json<StudioRemixResult>(\n `/v1/studio/shares/${encodeURIComponent(tokenOf(tokenOrUrl))}/remix`,\n {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n }\n\n /** Start a thread through a review link (`name`, `body`, optional anchor; HTTP 201). 400 `invalid_name`. */\n comment(\n tokenOrUrl: string,\n body: StudioPublicThreadCreateRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(review(tokenOrUrl, '/threads'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Reply in a thread through a review link (`name`, `body`; HTTP 201) — returns the whole thread. */\n reply(\n tokenOrUrl: string,\n threadId: string,\n body: StudioPublicReplyRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(thread(tokenOrUrl, threadId, '/replies'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** Resolve a thread through a review link (`resolved_by` = `name`). */\n resolve(\n tokenOrUrl: string,\n threadId: string,\n body: StudioPublicNameRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(thread(tokenOrUrl, threadId, '/resolve'), {\n method: 'POST',\n body: { name: body.name },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** Reopen a resolved thread through a review link. */\n reopen(\n tokenOrUrl: string,\n threadId: string,\n body: StudioPublicNameRequest,\n opts: CallOpts = {},\n ): Promise<StudioReviewThread> {\n return this.http.json<StudioReviewThread>(thread(tokenOrUrl, threadId, '/reopen'), {\n method: 'POST',\n body: { name: body.name },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * Approve or request changes (approver review links only). 403 `not_an_approver`, 409 `review_not_open`, 409\n * `stale` (with `head_seq`) when `seq` is not the head. Returns the new review state.\n */\n decide(\n tokenOrUrl: string,\n body: StudioPublicDecisionRequest,\n opts: CallOpts = {},\n ): Promise<StudioPublicReview> {\n return this.http.json<StudioPublicReview>(review(tokenOrUrl, '/decision'), {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/**\n * `POST /v1/studio/voice-revocations` — ask for a voice cloned in codai Studio to be taken down (for people without a\n * codai account). Public: the key is not required by the route; nothing in the request is echoed back. Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema, stripUndefined } from './_shared';\n\n/** `email`, `voice_owner_name`, `details`, optional `evidence_url`. */\nexport type StudioVoiceRevocationRequest = Mutable<Schema<'StudioVoiceRevocationRequest'>>;\n/** `{ id, object: 'studio.voice_revocation', status: 'open' }`. */\nexport type StudioVoiceRevocation = Schema<'StudioVoiceRevocation'>;\n\nexport class VoiceRevocations {\n constructor(private readonly http: HttpClient) {}\n\n /** Store a takedown ticket for manual review (HTTP 202). Rate-limited per IP; never retried. */\n create(\n body: StudioVoiceRevocationRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<StudioVoiceRevocation> {\n return this.http.json<StudioVoiceRevocation>('/v1/studio/voice-revocations', {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/**\n * `/v1/vault/*` — the zero-knowledge credentials vault (V-01..V-10). Everything the server stores is ciphertext built\n * client-side (bundles, envelopes, sealed keys): this resource only moves those blobs. The agent broker calls\n * (`catalog`, `use`, `http`, `resolve`) never return secret values. Device approval keys (V-27) hold public keys\n * only: `vault.devices` enrols, lists, renames and revokes them. Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport {\n type Body,\n type Mutable,\n type QueryOf,\n type Reply,\n type Schema,\n stripUndefined,\n} from './_shared';\n\nexport type VaultAccount = Schema<'VaultAccount'>;\nexport type VaultItemEnvelope = Mutable<Schema<'VaultItemEnvelope'>>;\nexport type VaultUseDecision = Schema<'VaultUseDecision'>;\nexport type VaultAccountPut = Mutable<Body<'putVaultAccount'>>;\nexport type VaultCreate = Mutable<Body<'createVault'>>;\nexport type VaultRuleCreate = Mutable<Body<'createVaultRule'>>;\nexport type VaultDecision = Mutable<Body<'decideVaultApproval'>>;\n/** v2 proof for `decide`: an enrolled device key or a passkey assertion. */\nexport type VaultApprovalProof = Mutable<Schema<'VaultApprovalProof'>>;\nexport type VaultDeviceKey = Schema<'VaultDeviceKey'>;\nexport type VaultDeviceChallenge = Schema<'VaultDeviceChallenge'>;\nexport type VaultDeviceEnroll = Mutable<Schema<'VaultDeviceEnroll'>>;\nexport type VaultDeviceAttestation = VaultDeviceKey['attestation'];\nexport type VaultUseRequest = Mutable<Body<'vaultUse'>>;\nexport type VaultHttpRequest = Mutable<Body<'vaultHttp'>>;\nexport type VaultResolveRequest = Mutable<Body<'vaultResolve'>>;\nexport type VaultTier = VaultAccount['default_tier'];\n/** Anomaly guards (V-32): new host, burst, allowed hours. An anomaly forces t4. */\nexport type VaultGuards = Schema<'VaultGuards'>;\nexport type VaultSettingsPatch = Mutable<Body<'patchVaultSettings'>>;\nexport type VaultSettings = Reply<'patchVaultSettings'>;\nexport type VaultLockResult = Schema<'VaultLockResult'>;\nexport type VaultUnlockChallenge = Schema<'VaultUnlockChallenge'>;\nexport type VaultUnlockRequest = Mutable<Body<'unlockVault'>>;\n/** Per-handle limits (V-21); an `http` use costs 2 units, other modes 1. */\nexport type VaultItemLimits = Schema<'VaultItemLimits'>;\nexport type VaultItemLimitsInput = Mutable<Body<'setVaultItemLimits'>>;\n/** Where a lock/unlock was triggered from. */\nexport type VaultVia = 'hub' | 'desktop' | 'phone' | 'wear' | 'extension';\n\n/** The UTF-8 message an unlock proof covers: `codai-vault/unlock/v1|<challenge>|<device_id or \"passkey\">`. */\nexport function vaultUnlockMessage(challenge: string, deviceIdOrPasskey: string): string {\n return `codai-vault/unlock/v1|${challenge}|${deviceIdOrPasskey}`;\n}\n/** Loose JSON object answers (lists, acks) as documented in the OpenAPI spec. */\nexport type VaultObject = Record<string, unknown>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst seg = (base: string, id: string, suffix = '') => `${base}/${encodeURIComponent(id)}${suffix}`;\n\n/** `/v1/vault/devices/*` — hardware-backed device approval keys (public keys only; revocation is instant). */\nexport class VaultDevices {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/vault/devices/challenge` — single-use enrolment nonce, valid 5 minutes. */\n challenge(opts: CallOpts = {}): Promise<VaultDeviceChallenge> {\n return this.http.json<Reply<'createVaultDeviceChallenge'>>('/v1/vault/devices/challenge', {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/vault/devices` — enrol (or re-enrol) a device key; vault-signed, possession-proven, attested (201). */\n async enroll(body: VaultDeviceEnroll, opts: CallOpts = {}): Promise<VaultDeviceKey> {\n const r = await this.http.json<Reply<'enrollVaultDevice', 201>>('/v1/vault/devices', {\n method: 'POST',\n body: stripUndefined({ ...body }),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return r.device;\n }\n\n /** `GET /v1/vault/devices` — your device keys, revoked ones included, newest first. */\n async list(opts: CallOpts = {}): Promise<VaultDeviceKey[]> {\n const r = await this.http.json<Reply<'listVaultDevices'>>('/v1/vault/devices', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.devices];\n }\n\n /** `PATCH /v1/vault/devices/{id}` — change the display name (1-80 characters). */\n async rename(id: string, name: string, opts: CallOpts = {}): Promise<VaultDeviceKey> {\n const r = await this.http.json<Reply<'renameVaultDevice'>>(seg('/v1/vault/devices', id), {\n method: 'PATCH',\n body: { name },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n return r.device;\n }\n\n /** `DELETE /v1/vault/devices/{id}` — revoke at once; later proofs answer 403 `device_revoked`. */\n revoke(id: string, opts: CallOpts = {}): Promise<Reply<'revokeVaultDevice'>> {\n return this.http.json<Reply<'revokeVaultDevice'>>(seg('/v1/vault/devices', id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Vault {\n readonly devices: VaultDevices;\n\n constructor(private readonly http: HttpClient) {\n this.devices = new VaultDevices(http);\n }\n\n private get<T>(\n path: string,\n opts: CallOpts,\n query?: Record<string, string | number | undefined>,\n ): Promise<T> {\n return this.http.json<T>(path, { query, ext: opts.ext, signal: opts.signal });\n }\n\n private send<T>(\n method: 'POST' | 'PUT' | 'PATCH' | 'DELETE',\n path: string,\n opts: CallOpts,\n body?: Record<string, unknown>,\n ): Promise<T> {\n return this.http.json<T>(path, {\n method,\n ...(body ? { body: stripUndefined(body) } : {}),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: method !== 'DELETE',\n });\n }\n\n /** `GET /v1/vault/account` — bundle, fingerprint, default tier, revision (404 `vault_not_setup` before setup). */\n account(opts: CallOpts = {}): Promise<VaultAccount> {\n return this.get<Reply<'getVaultAccount'>>('/v1/vault/account', opts);\n }\n\n /** `PUT /v1/vault/account` — upload the client-built bundle; updates send the current `revision` (409 otherwise). */\n putAccount(body: VaultAccountPut, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('PUT', '/v1/vault/account', opts, body);\n }\n\n /** `PATCH /v1/vault/settings` — default approval tier for items without a matching rule. */\n setDefaultTier(defaultTier: VaultTier, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('PATCH', '/v1/vault/settings', opts, { default_tier: defaultTier });\n }\n\n /**\n * `PATCH /v1/vault/settings` — `default_tier` and/or partial anomaly `guards` (merged over the current ones).\n * Answers the effective `{ default_tier, guards }`.\n */\n updateSettings(body: VaultSettingsPatch, opts: CallOpts = {}): Promise<VaultSettings> {\n if (body.default_tier === undefined && body.guards === undefined)\n return Promise.reject(new TypeError('updateSettings needs default_tier and/or guards'));\n return this.send<VaultSettings>('PATCH', '/v1/vault/settings', opts, { ...body });\n }\n\n /**\n * `POST /v1/vault/lock` — panic: revoke every live grant, deny every pending approval, lock the vault (agent uses\n * then answer `vault_locked`). Device keys stay enrolled. Idempotent.\n */\n lock(params: { via?: VaultVia } = {}, opts: CallOpts = {}): Promise<VaultLockResult> {\n return this.send<VaultLockResult>('POST', '/v1/vault/lock', opts, { via: params.via });\n }\n\n /** `POST /v1/vault/unlock/challenge` — single-use unlock challenge, valid 5 minutes. */\n unlockChallenge(opts: CallOpts = {}): Promise<VaultUnlockChallenge> {\n return this.send<VaultUnlockChallenge>('POST', '/v1/vault/unlock/challenge', opts, {});\n }\n\n /**\n * `POST /v1/vault/unlock` — end a lock with a device-key proof over {@link vaultUnlockMessage} or a passkey whose\n * challenge is base64url(SHA-256(that message with `passkey`)). 403 `challenge_invalid`, `wear_t3_only`, …\n */\n unlock(body: VaultUnlockRequest, opts: CallOpts = {}): Promise<Reply<'unlockVault'>> {\n return this.send<Reply<'unlockVault'>>('POST', '/v1/vault/unlock', opts, { ...body });\n }\n\n /** `GET /v1/vault/limits` — per-handle usage caps on your items. */\n async limits(opts: CallOpts = {}): Promise<VaultItemLimits[]> {\n const r = await this.get<Reply<'listVaultLimits'>>('/v1/vault/limits', opts);\n return [...r.limits];\n }\n\n /**\n * `PUT /v1/vault/items/{id}/limits` — all three keys required; `null` removes a cap, all `null` removes the limits\n * (answers `null`). Over a cap the broker calls answer 429 `vault_rate_limited` with `Retry-After`.\n */\n async setLimits(\n id: string,\n limits: VaultItemLimitsInput,\n opts: CallOpts = {},\n ): Promise<VaultItemLimits | null> {\n const r = await this.http.json<Reply<'setVaultItemLimits'>>(\n seg('/v1/vault/items', id, '/limits'),\n {\n method: 'PUT',\n body: {\n per_minute: limits.per_minute,\n per_day: limits.per_day,\n units_per_day: limits.units_per_day,\n },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n },\n );\n return r.limits ?? null;\n }\n\n /** `GET /v1/vault/vaults` — vaults you belong to, with your role and sealed vault key. */\n vaults(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/vaults', opts);\n }\n\n /** `POST /v1/vault/vaults` — register a vault created client-side (HTTP 201). */\n createVault(body: VaultCreate, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/vaults', opts, body);\n }\n\n /** `GET /v1/vault/items` — envelopes you can read; with `since` (ISO) only changes after it, tombstones included. */\n items(params: QueryOf<'listVaultItems'> = {}, opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/items', opts, { since: params.since });\n }\n\n /** `PUT /v1/vault/items/{id}` — store an envelope (new = revision 1, update = revision + 1, 409 otherwise). */\n putItem(id: string, envelope: VaultItemEnvelope, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('PUT', seg('/v1/vault/items', id), opts, envelope);\n }\n\n /** `DELETE /v1/vault/items/{id}` — tombstone; revokes every grant on the item and drops its cloud copy. */\n deleteItem(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('DELETE', seg('/v1/vault/items', id), opts);\n }\n\n /** `PUT /v1/vault/items/{id}/cloud` — owner only: the decrypted item to seal with KMS for cloud agents, or null. */\n setItemCloud(\n id: string,\n item: Record<string, unknown> | null,\n opts: CallOpts = {},\n ): Promise<VaultObject> {\n return this.http.json<VaultObject>(seg('/v1/vault/items', id, '/cloud'), {\n method: 'PUT',\n body: { item },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/vault/rules` — policy rules (item, agent glob, mode → tier). */\n rules(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/rules', opts);\n }\n\n /** `POST /v1/vault/rules` — add a rule (HTTP 201). Host binding and honeytokens cannot be overridden. */\n createRule(body: VaultRuleCreate, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/rules', opts, body);\n }\n\n /** `DELETE /v1/vault/rules/{id}`. */\n deleteRule(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('DELETE', seg('/v1/vault/rules', id), opts);\n }\n\n /** `GET /v1/vault/grants` — standing grants created by your approvals. */\n grants(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/grants', opts);\n }\n\n /** `DELETE /v1/vault/grants/{id}` — revoke a grant immediately. */\n revokeGrant(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('DELETE', seg('/v1/vault/grants', id), opts);\n }\n\n /** `POST /v1/vault/grants/revoke-task` — revoke every live grant of a task / session; answers `{ revoked }`. */\n revokeTaskGrants(task: string, opts: CallOpts = {}): Promise<Reply<'revokeVaultTaskGrants'>> {\n return this.send<Reply<'revokeVaultTaskGrants'>>('POST', '/v1/vault/grants/revoke-task', opts, {\n task,\n });\n }\n\n /** `GET /v1/vault/events` — append-only audit log (never contains secret values). */\n events(params: QueryOf<'listVaultEvents'> = {}, opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/events', opts, { limit: params.limit });\n }\n\n /** `GET /v1/vault/approvals` — agent requests waiting for your decision. */\n approvals(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/approvals', opts);\n }\n\n /** `GET /v1/vault/approvals/{id}` — pending, approved, denied or expired. */\n approval(id: string, opts: CallOpts = {}): Promise<VaultObject> {\n return this.get(seg('/v1/vault/approvals', id), opts);\n }\n\n /**\n * `POST /v1/vault/approvals/{id}/decide` — send `signature` (v1 vault key) or `proof` (v2 device key / passkey),\n * never both. Deny needs no proof; a t4 approve needs a device or passkey proof (Wear: t3 only).\n */\n decide(id: string, body: VaultDecision, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', seg('/v1/vault/approvals', id, '/decide'), opts, body);\n }\n\n /** `GET /v1/vault/catalog` — items exposed to agents (handle, title, kind, hosts, env name); no values. */\n catalog(opts: CallOpts = {}): Promise<VaultObject> {\n return this.get('/v1/vault/catalog', opts);\n }\n\n /** `POST /v1/vault/use` — a policy decision for one use; t3/t4 return a pending approval id. */\n use(body: VaultUseRequest, opts: CallOpts = {}): Promise<VaultUseDecision> {\n return this.send<Reply<'vaultUse'>>('POST', '/v1/vault/use', opts, body);\n }\n\n /** `POST /v1/vault/http` — brokered HTTPS call with `{{vault:<slug>}}` handles; 202 = approval required. */\n httpCall(body: VaultHttpRequest, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/http', opts, body);\n }\n\n /** `POST /v1/vault/resolve` — codai local brokers only (cloud fallback of `codaid vault run`); 202 = approval. */\n resolve(body: VaultResolveRequest, opts: CallOpts = {}): Promise<VaultObject> {\n return this.send('POST', '/v1/vault/resolve', opts, body);\n }\n}\n","/**\n * `POST /v1/studio/abuse-reports` — report illegal or abusive content seen on a codai Studio share (`/s/<token>`) or\n * review (`/r/<token>`) link (DSA art. 16 notice). Public: the key is not required by the route; an unknown link still\n * answers 202 (no enumeration). Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type Schema, stripUndefined } from './_shared';\n\n/** `share_token`, `surface`, `category`, `explanation`, `reporter_name`, `reporter_email`, `good_faith: true`. */\nexport type StudioAbuseReportRequest = Mutable<Schema<'StudioAbuseReportRequest'>>;\n/** `{ id, object: 'studio.abuse_report', status: 'open' }`. */\nexport type StudioAbuseReport = Schema<'StudioAbuseReport'>;\n\nexport class AbuseReports {\n constructor(private readonly http: HttpClient) {}\n\n /** Store an abuse report for manual review (HTTP 202). Rate-limited per IP; never retried. */\n create(\n body: StudioAbuseReportRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<StudioAbuseReport> {\n return this.http.json<StudioAbuseReport>('/v1/studio/abuse-reports', {\n method: 'POST',\n body: stripUndefined(body),\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/**\n * `POST /v1/public/provenance/check` — check a file for the AI-provenance marks codai writes (C2PA manifest presence +\n * claimed issuer, WAV RIFF INFO, MP3 ID3 TXXX, MP4 udta/meta, image XMP). Public: the route does not require the key;\n * the file is not stored. C2PA signatures are not verified and SynthID is never checked (see the result flags). Free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Schema } from './_shared';\n\n/** `{ media_type, findings, codai_generated, synthid_checked: false, signature_verified: false }`. */\nexport type ProvenanceCheckResult = Schema<'ProvenanceCheckResult'>;\n/** One mark: `{ kind, present, ai_marked, codai, details }`. */\nexport type ProvenanceFinding = Schema<'ProvenanceFinding'>;\n\n/** Largest file the checker accepts (25 MB). */\nexport const PROVENANCE_MAX_BYTES = 25 * 1024 * 1024;\n\nexport class Provenance {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Upload `file` (PNG, JPEG, WebP, WAV, MP3 or MP4, ≤ 25 MB) and return what was found. A `Blob`/`File` sends its own\n * `type`; raw bytes need `contentType` (default `application/octet-stream`). Never retried.\n */\n check(\n file: Blob | Uint8Array<ArrayBuffer> | ArrayBuffer,\n opts: { contentType?: string; ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<ProvenanceCheckResult> {\n const type =\n opts.contentType ||\n (file instanceof Blob && file.type ? file.type : 'application/octet-stream');\n return this.http.json<ProvenanceCheckResult>('/v1/public/provenance/check', {\n method: 'POST',\n rawBody: file,\n headers: { 'Content-Type': type },\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n}\n","/** `POST /v1/messages` — Anthropic Messages wire (JSON + named-event SSE). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient, readSse } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type MessageRequest = Mutable<Body<'createMessage'>>;\nexport type MessageResponse = Reply<'createMessage'>;\n/** Request body as accepted by the SDK: `stream` is set by the method and `model` defaults to `codai`. */\nexport type MessageInput = Omit<MessageRequest, 'stream' | 'model'> & { model?: string };\n\nexport interface MessageCallOptions {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface MessageResult {\n /** Concatenated `text` blocks of the reply. */\n text: string;\n raw: MessageResponse;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers;\n}\n\n/** One Anthropic streaming event: `event.type` mirrors the SSE `event:` name. */\nexport interface MessageStreamEvent {\n type:\n | 'message_start'\n | 'content_block_start'\n | 'content_block_delta'\n | 'content_block_stop'\n | 'message_delta'\n | 'message_stop'\n | 'ping'\n | 'error'\n | (string & {});\n [key: string]: unknown;\n}\n\nexport interface MessageStreamResult {\n /** Concatenated `text_delta` payloads. */\n text: string;\n /** Final `stop_reason` from `message_delta`, when sent. */\n stopReason: string | null;\n /** Cumulative usage: `input_tokens` from `message_start`, `output_tokens` from `message_delta`. */\n usage: { inputTokens: number; outputTokens: number } | null;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers | null;\n}\n\nexport interface MessageStream extends AsyncIterable<MessageStreamEvent> {\n readonly final: Promise<MessageStreamResult>;\n /** Text deltas only. */\n text(): AsyncIterable<string>;\n}\n\nexport class Messages {\n constructor(private readonly http: HttpClient) {}\n\n async create(body: MessageInput, opts: MessageCallOptions = {}): Promise<MessageResult> {\n const res = await this.http.request('/v1/messages', {\n body: { ...body, model: body.model ?? 'codai', stream: false },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as MessageResponse;\n const text = (raw.content ?? [])\n .map((b) => (b.type === 'text' && typeof b.text === 'string' ? b.text : ''))\n .join('');\n return {\n text,\n raw,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n stream(body: MessageInput, opts: MessageCallOptions = {}): MessageStream {\n const requestPromise = this.http.request('/v1/messages', {\n body: { ...body, model: body.model ?? 'codai', stream: true },\n ext: opts.ext,\n signal: opts.signal,\n timeoutMs: 0,\n noRetry: true,\n });\n\n let resolveFinal!: (r: MessageStreamResult) => void;\n let rejectFinal!: (e: unknown) => void;\n const final = new Promise<MessageStreamResult>((resolve, reject) => {\n resolveFinal = resolve;\n rejectFinal = reject;\n });\n final.catch(() => {});\n\n let text = '';\n let stopReason: string | null = null;\n let inputTokens: number | null = null;\n let outputTokens: number | null = null;\n let res: Response | null = null;\n\n async function* events(): AsyncGenerator<MessageStreamEvent, void, undefined> {\n try {\n res = await requestPromise;\n for await (const frame of readSse(res, opts.signal)) {\n const ev = frameJson<MessageStreamEvent>(frame);\n if (!ev) continue;\n if (typeof ev.type !== 'string') ev.type = frame.event;\n if (ev.type === 'message_start') {\n const usage = (ev.message as { usage?: { input_tokens?: number } } | undefined)?.usage;\n if (usage?.input_tokens !== undefined) inputTokens = usage.input_tokens;\n } else if (ev.type === 'content_block_delta') {\n const delta = ev.delta as { type?: string; text?: string } | undefined;\n if (delta?.type === 'text_delta' && typeof delta.text === 'string') text += delta.text;\n } else if (ev.type === 'message_delta') {\n const delta = ev.delta as { stop_reason?: string | null } | undefined;\n if (delta?.stop_reason) stopReason = delta.stop_reason;\n const usage = ev.usage as { output_tokens?: number } | undefined;\n if (usage?.output_tokens !== undefined) outputTokens = usage.output_tokens;\n }\n yield ev;\n if (ev.type === 'message_stop') break;\n }\n resolveFinal({\n text,\n stopReason,\n usage:\n inputTokens !== null || outputTokens !== null\n ? { inputTokens: inputTokens ?? 0, outputTokens: outputTokens ?? 0 }\n : null,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id') ?? null,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n });\n } catch (err) {\n rejectFinal(err);\n throw err;\n }\n }\n\n async function* textOnly(): AsyncGenerator<string, void, undefined> {\n for await (const ev of events()) {\n if (ev.type !== 'content_block_delta') continue;\n const delta = ev.delta as { type?: string; text?: string } | undefined;\n if (delta?.type === 'text_delta' && delta.text) yield delta.text;\n }\n }\n\n return {\n [Symbol.asyncIterator]: () => events(),\n text: () => ({ [Symbol.asyncIterator]: () => textOnly() }),\n final,\n };\n }\n}\n","/** `GET /v1/models`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type Model = Schema<'CoreModel'>;\nexport type ModelList = Reply<'listModels'>;\n\nexport class Models {\n constructor(private readonly http: HttpClient) {}\n\n /** Every model the calling key may address (OpenAI list shape, `data[]`). */\n async list(opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {}): Promise<Model[]> {\n const raw = await this.http.json<ModelList>('/v1/models', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.data ?? [])];\n }\n}\n","/** `/v1/orgs/*` — the orgs (teams) you belong to and their members. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Org = Schema<'OrgWithRole'>;\nexport type OrgMember = Schema<'OrgMember'>;\nexport type OrgRole = Schema<'OrgRole'>;\nexport type OrgAddMemberBody = Mutable<Body<'addOrgMember'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class OrgMembers {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/orgs/{id}/members` */\n async list(orgId: string, opts: CallOpts = {}): Promise<OrgMember[]> {\n const raw = await this.http.json<Reply<'listOrgMembers'>>(\n `/v1/orgs/${encodeURIComponent(orgId)}/members`,\n { ext: opts.ext, signal: opts.signal },\n );\n return [...(raw.members ?? [])];\n }\n\n /** `POST /v1/orgs/{id}/members` — add or re-role (owner/admin). */\n add(\n orgId: string,\n body: OrgAddMemberBody,\n opts: CallOpts = {},\n ): Promise<Reply<'addOrgMember', 201>> {\n return this.http.json<Reply<'addOrgMember', 201>>(\n `/v1/orgs/${encodeURIComponent(orgId)}/members`,\n { body, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `DELETE /v1/orgs/{id}/members/{userId}` */\n remove(orgId: string, userId: string, opts: CallOpts = {}): Promise<Reply<'removeOrgMember'>> {\n return this.http.json<Reply<'removeOrgMember'>>(\n `/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(userId)}`,\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class Orgs {\n readonly members: OrgMembers;\n constructor(private readonly http: HttpClient) {\n this.members = new OrgMembers(http);\n }\n\n /** `POST /v1/orgs` */\n create(name: string, opts: CallOpts = {}): Promise<Org> {\n return this.http.json<Org>('/v1/orgs', { body: { name }, ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/orgs` */\n async list(opts: CallOpts = {}): Promise<Org[]> {\n const raw = await this.http.json<Reply<'listOrgs'>>('/v1/orgs', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.orgs ?? [])];\n }\n}\n","/** `/v1/projects/*` — projects (a repo + isolation policy) that group environments. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Project = Schema<'Project'>;\nexport type ProjectIsolation = Schema<'ProjectIsolation'>;\nexport type ProjectCreateBody = Mutable<Body<'createProject'>>;\nexport type ProjectPatchBody = Mutable<Body<'updateProject'>>;\nexport type ProjectDetail = Reply<'getProject'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Projects {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/projects` — projects you own plus those of your orgs, newest first. */\n async list(opts: CallOpts = {}): Promise<Project[]> {\n const raw = await this.http.json<Reply<'listProjects'>>('/v1/projects', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.projects ?? [])];\n }\n\n /** `POST /v1/projects` — 409 `slug_taken` when the slug is already yours. */\n async create(body: ProjectCreateBody, opts: CallOpts = {}): Promise<Project> {\n const raw = await this.http.json<Reply<'createProject', 201>>('/v1/projects', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n return raw.project;\n }\n\n /** `GET /v1/projects/{id}` — the project plus every environment in it. */\n get(projectId: string, opts: CallOpts = {}): Promise<ProjectDetail> {\n return this.http.json<ProjectDetail>(`/v1/projects/${encodeURIComponent(projectId)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/projects/{id}` — owner or org owner/admin; the slug cannot change. */\n async update(projectId: string, body: ProjectPatchBody, opts: CallOpts = {}): Promise<Project> {\n const raw = await this.http.json<Reply<'updateProject'>>(\n `/v1/projects/${encodeURIComponent(projectId)}`,\n { method: 'PATCH', body, ext: opts.ext, signal: opts.signal },\n );\n return raw.project;\n }\n\n /** `DELETE /v1/projects/{id}` — 409 `project_has_environments` until all are destroyed. */\n delete(projectId: string, opts: CallOpts = {}): Promise<Reply<'deleteProject'>> {\n return this.http.json<Reply<'deleteProject'>>(`/v1/projects/${encodeURIComponent(projectId)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `wss://…/v1/realtime` — dependency-free realtime client (live transcription and the OpenAI\n * Realtime protocol lanes). Not an OpenAPI operation (OpenAPI cannot describe WebSockets), so it is\n * outside the `OPERATION_METHODS` parity table.\n *\n * const live = codai.realtime.connect({ model: 'codai-transcribe-live', language: 'ro', token });\n * live.appendAudio(pcm16At24kHz); // Int16Array | ArrayBuffer | Uint8Array\n * for await (const ev of live) {\n * if (ev.type === 'conversation.item.input_audio_transcription.delta') draw(ev.delta);\n * }\n *\n * Uses the global `WebSocket` (browsers, Node ≥ 22, Deno, Bun) or an injected constructor.\n * - Browser path: pass an ephemeral `token` (scope `realtime` or `live`); it travels as `?key=`.\n * Raw `codai_` keys in the query string are refused by the gateway (close 4401).\n * - Server path: pass `apiKey` (or a token) with a WebSocket constructor that accepts headers\n * (e.g. `ws`); it is sent as `Authorization: Bearer` on the upgrade.\n */\n\n/** Minimal WebSocket surface (browser `WebSocket`, Node 22 global, or the `ws` package). */\nexport interface RealtimeSocket {\n readonly readyState: number;\n binaryType?: string;\n send(data: string | ArrayBuffer | ArrayBufferView): void;\n close(code?: number, reason?: string): void;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\n/** `new (url, protocols?, options?)` — the third argument is used for headers by `ws`. */\nexport type RealtimeSocketCtor = new (\n url: string,\n protocols?: string | string[],\n options?: { headers?: Record<string, string> },\n) => RealtimeSocket;\n\nexport type RealtimeModel =\n 'codai-transcribe-live' | 'codai-realtime' | 'codai-voice' | (string & Record<never, never>);\n\nexport interface RealtimeConnectOptions {\n /** Default `codai-transcribe-live`. */\n model?: RealtimeModel;\n /** Language hint (`ro`, `en`, …). `ro` uses the Deepgram Nova-3 lane when the gateway has it. */\n language?: string;\n /** Ephemeral token (scope `realtime` or `live`) — sent as `?key=`. Required in browsers. */\n token?: string;\n /** Raw API key — sent as `Authorization: Bearer` (needs a ctor that supports headers). */\n apiKey?: string;\n /** Conversation id recorded on the usage row (`?session_id=`). */\n sessionId?: string;\n /**\n * First frame sent on open. Default for `codai-transcribe-live`: a transcription\n * `session.update` (PCM 24 kHz, `language` when set). Pass `null` to send nothing.\n */\n sessionUpdate?: Record<string, unknown> | null;\n /** Injectable WebSocket constructor (tests, `ws` on older Node). Defaults to `globalThis.WebSocket`. */\n WebSocket?: RealtimeSocketCtor;\n /** Override the gateway base URL (default: the client's `baseUrl`). */\n baseUrl?: string;\n}\n\n/** Typed subset of server events; anything else arrives as `RealtimeUnknownEvent`. */\nexport type RealtimeEvent =\n | {\n type: 'session.created' | 'session.updated';\n session?: Record<string, unknown>;\n event_id?: string;\n }\n | {\n type: 'conversation.item.input_audio_transcription.delta';\n item_id: string;\n content_index?: number;\n delta: string;\n event_id?: string;\n }\n | {\n type: 'conversation.item.input_audio_transcription.completed';\n item_id: string;\n content_index?: number;\n transcript: string;\n event_id?: string;\n }\n | { type: 'input_audio_buffer.committed'; item_id?: string; previous_item_id?: string | null }\n | { type: 'input_audio_buffer.cleared' }\n | { type: 'error'; error: { type?: string; code?: string; message?: string } }\n /** Emitted by the client itself when the socket closes (always the last event). */\n | { type: 'close'; code: number; reason: string };\nexport type RealtimeUnknownEvent = { type: string; [k: string]: unknown };\nexport type RealtimeAnyEvent = RealtimeEvent | RealtimeUnknownEvent;\n\ntype Listener = (ev: RealtimeAnyEvent) => void;\n\nconst OPEN = 1;\n\nfunction toBytes(audio: Int16Array | ArrayBuffer | Uint8Array): Uint8Array {\n if (audio instanceof ArrayBuffer) return new Uint8Array(audio);\n return new Uint8Array(audio.buffer, audio.byteOffset, audio.byteLength);\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let bin = '';\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(bin);\n}\n\n/** A live realtime session: async-iterable of events + `on()` listeners. */\nexport class RealtimeSession implements AsyncIterable<RealtimeAnyEvent> {\n private readonly listeners = new Map<string, Set<Listener>>();\n private readonly queue: RealtimeAnyEvent[] = [];\n private readonly waiters: Array<(r: IteratorResult<RealtimeAnyEvent>) => void> = [];\n private readonly outbox: string[] = [];\n private closed = false;\n /** Resolves when the socket is open (rejects if it closes first). */\n readonly ready: Promise<void>;\n\n constructor(\n readonly socket: RealtimeSocket,\n firstFrame: Record<string, unknown> | null,\n ) {\n let resolveReady!: () => void;\n let rejectReady!: (e: Error) => void;\n this.ready = new Promise<void>((res, rej) => {\n resolveReady = res;\n rejectReady = rej;\n });\n // Unhandled-rejection safety: callers that never await `ready` still get the `close` event.\n this.ready.catch(() => undefined);\n socket.onopen = () => {\n if (firstFrame) socket.send(JSON.stringify(firstFrame));\n for (const f of this.outbox.splice(0)) socket.send(f);\n resolveReady();\n };\n socket.onmessage = (ev) => {\n if (typeof ev.data !== 'string') return;\n let parsed: unknown;\n try {\n parsed = JSON.parse(ev.data);\n } catch {\n return;\n }\n if (\n parsed &&\n typeof parsed === 'object' &&\n typeof (parsed as { type?: unknown }).type === 'string'\n ) {\n this.emit(parsed as RealtimeAnyEvent);\n }\n };\n socket.onerror = () => {\n /* the close event carries the code */\n };\n socket.onclose = (ev) => {\n rejectReady(\n new Error(`realtime socket closed before open (${String(ev.code)} ${ev.reason})`),\n );\n this.emit({ type: 'close', code: ev.code, reason: ev.reason });\n this.closed = true;\n for (const w of this.waiters.splice(0)) w({ value: undefined, done: true });\n };\n }\n\n /** Listen for one event type (`'*'` = every event). Returns an unsubscribe function. */\n on(type: string, fn: Listener): () => void {\n let set = this.listeners.get(type);\n if (!set) this.listeners.set(type, (set = new Set()));\n set.add(fn);\n return () => set.delete(fn);\n }\n\n /** Send any client event (JSON). Queued until the socket opens. */\n send(event: Record<string, unknown>): void {\n if (this.closed) throw new Error('realtime session is closed');\n const frame = JSON.stringify(event);\n if (this.socket.readyState === OPEN) this.socket.send(frame);\n else this.outbox.push(frame);\n }\n\n /** Append PCM16 little-endian mono audio (24 kHz for `codai-transcribe-live`). */\n appendAudio(audio: Int16Array | ArrayBuffer | Uint8Array): void {\n const bytes = toBytes(audio);\n if (bytes.byteLength === 0) return;\n this.send({ type: 'input_audio_buffer.append', audio: bytesToBase64(bytes) });\n }\n\n /** Close the current utterance: the server answers with one `...transcription.completed`. */\n commit(): void {\n this.send({ type: 'input_audio_buffer.commit' });\n }\n\n /** Drop audio the server holds for the current utterance. */\n clear(): void {\n this.send({ type: 'input_audio_buffer.clear' });\n }\n\n close(code = 1000, reason = 'client closed'): void {\n if (this.closed) return;\n this.socket.close(code, reason);\n }\n\n [Symbol.asyncIterator](): AsyncIterator<RealtimeAnyEvent> {\n return {\n next: () => {\n const ev = this.queue.shift();\n if (ev) return Promise.resolve({ value: ev, done: false });\n if (this.closed) return Promise.resolve({ value: undefined, done: true });\n return new Promise((resolve) => this.waiters.push(resolve));\n },\n return: () => {\n this.close();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n }\n\n private emit(ev: RealtimeAnyEvent): void {\n for (const fn of this.listeners.get(ev.type) ?? []) fn(ev);\n for (const fn of this.listeners.get('*') ?? []) fn(ev);\n const w = this.waiters.shift();\n if (w) w({ value: ev, done: false });\n else this.queue.push(ev);\n }\n}\n\n/** Build the `wss://…/v1/realtime?…` URL (exported for tests and custom transports). */\nexport function realtimeUrl(baseUrl: string, opts: RealtimeConnectOptions): string {\n const url = new URL(`${baseUrl.replace(/\\/$/, '').replace(/^http/, 'ws')}/v1/realtime`);\n url.searchParams.set('model', opts.model ?? 'codai-transcribe-live');\n if (opts.language) url.searchParams.set('language', opts.language);\n if (opts.sessionId) url.searchParams.set('session_id', opts.sessionId);\n if (opts.token) url.searchParams.set('key', opts.token);\n return url.toString();\n}\n\nexport class Realtime {\n constructor(private readonly defaults: { baseUrl: string; apiKey?: string }) {}\n\n /** Open a realtime session. Returns immediately; `await session.ready` to wait for the socket. */\n connect(opts: RealtimeConnectOptions = {}): RealtimeSession {\n const Ctor = opts.WebSocket ?? (globalThis as { WebSocket?: RealtimeSocketCtor }).WebSocket;\n if (!Ctor) throw new Error('codai.realtime: no WebSocket available — pass options.WebSocket');\n const model = opts.model ?? 'codai-transcribe-live';\n let token = opts.token;\n let apiKey = token ? undefined : (opts.apiKey ?? this.defaults.apiKey);\n // A client constructed with an ephemeral token uses it the browser way (`?key=`).\n if (apiKey?.startsWith('codai_eph_v1.')) {\n token = apiKey;\n apiKey = undefined;\n }\n if (!token && !apiKey) throw new Error('codai.realtime: pass `token` (browser) or `apiKey`');\n const url = realtimeUrl(opts.baseUrl ?? this.defaults.baseUrl, { ...opts, model, token });\n const socket = apiKey\n ? new Ctor(url, undefined, { headers: { Authorization: `Bearer ${apiKey}` } })\n : new Ctor(url);\n if ('binaryType' in socket) socket.binaryType = 'arraybuffer';\n const first =\n opts.sessionUpdate !== undefined\n ? opts.sessionUpdate\n : model === 'codai-transcribe-live'\n ? {\n type: 'session.update',\n session: {\n type: 'transcription',\n audio: {\n input: {\n format: { type: 'audio/pcm', rate: 24000 },\n transcription: {\n model,\n ...(opts.language ? { language: opts.language } : {}),\n },\n },\n },\n },\n }\n : null;\n return new RealtimeSession(socket, first);\n }\n}\n","/** `/v1/referrals` — referral stats and invitees; mutations go through `PATCH /v1/account`. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\nimport { type AccountPatchResponse } from './account';\n\nexport type ReferralsView = Reply<'getReferrals'>;\nexport type ReferralRow = Schema<'ReferralRow'>;\nexport type ReferralStats = Schema<'AccountReferral'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Referrals {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/referrals` — stats, redeem deadline and invitees (masked, no PII). */\n get(opts: CallOpts = {}): Promise<ReferralsView> {\n return this.http.json<ReferralsView>('/v1/referrals', { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Redeem a referrer's code (their username) — `PATCH /v1/account\n * { referral_code }`. Allowed within 7 days of signup; the outcome is in\n * `referral_result` of the response.\n */\n redeem(code: string, opts: CallOpts = {}): Promise<AccountPatchResponse> {\n return this.patch({ referral_code: code }, opts);\n }\n\n /** Opt in/out of the referral programme — `PATCH /v1/account { referral_consent }`. */\n setConsent(consent: boolean, opts: CallOpts = {}): Promise<AccountPatchResponse> {\n return this.patch({ referral_consent: consent }, opts);\n }\n\n private patch(\n body: { referral_code?: string; referral_consent?: boolean },\n opts: CallOpts,\n ): Promise<AccountPatchResponse> {\n return this.http.json<AccountPatchResponse>('/v1/account', {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * codai Resolve — execution-verified bug fixes, no fix no fee\n * (`https://resolve.codai.ro`, spec `apps/docs/openapi/en/resolve.yaml`).\n *\n * Resolve is a separate service from the gateway: it has its own host and a\n * flat `{ error: string }` error shape, so it gets its own `HttpClient` and\n * maps failures to `ResolveError` / `ResolveInsufficientFundsError`.\n */\nimport type { components } from '../generated/resolve';\nimport { CodaiError, type HttpClient, type RequestOptions } from '../http';\nimport { type Mutable } from './_shared';\n\ntype ResolveSchemas = components['schemas'];\n\nexport type ResolveIntake = Mutable<ResolveSchemas['ResolveIntake']>;\nexport type ResolveQuote = ResolveSchemas['ResolveQuote'];\nexport type ResolveDeclined = ResolveSchemas['ResolveDeclined'];\n/** `submit()` result: `201` quote / free-tier auto-accept, or `200` decline. */\nexport type ResolveSubmitResult = ResolveQuote | ResolveDeclined;\nexport type ResolveAccepted = ResolveSchemas['ResolveAccepted'];\n/** How an accepted job is paid: `free` > `intro` (€1) > `credit` (t7 fix credit) > `wallet`. */\nexport type ResolvePaidWith = ResolveSchemas['ResolvePaidWith'];\n/** `GET /v1/resolve/balance` — fix credits, intro availability, wallet (EUR micros). */\nexport type ResolveBalance = ResolveSchemas['ResolveBalance'];\nexport type ResolveJob = ResolveSchemas['ResolveJob'];\n/** `GET /v1/resolve/jobs` page: `{ jobs, next_cursor }`. */\nexport type ResolveJobList = ResolveSchemas['ResolveJobList'];\nexport type ResolveJobStatus = ResolveSchemas['ResolveJobStatus'];\nexport type ResolveTier = ResolveSchemas['ResolveTier'];\nexport type ResolveAttestation = ResolveSchemas['ResolveAttestation'];\n/** DSSE v1 envelope in `ResolveAttestation.signature` (`null` = unsigned, pre-2026-09-27). */\nexport type ResolveAttestationEnvelope = ResolveSchemas['ResolveAttestationEnvelope'];\nexport type ResolveKeys = ResolveSchemas['ResolveKeys'];\nexport type ResolveKey = ResolveSchemas['ResolveKey'];\nexport type ResolveReproTest = ResolveSchemas['ResolveReproTest'];\nexport type ResolveHealth = ResolveSchemas['ResolveHealth'];\nexport type ResolveValidationDetails = ResolveSchemas['ResolveValidationDetails'];\nexport type ResolveInsufficientFunds = ResolveSchemas['ResolveInsufficientFunds'];\n/** Body POSTed to `callback_url` (verify with `verifyResolveWebhook` first). */\nexport type ResolveWebhookEvent = ResolveSchemas['ResolveWebhookEvent'];\nexport type ResolveWebhookEventName = ResolveSchemas['ResolveWebhookEventName'];\nexport type ResolveWebhookJob = ResolveSchemas['ResolveWebhookJob'];\n\nexport interface VerifyResolveWebhookOptions {\n /** Maximum age (and future skew) of `t`, in seconds. Default 300. */\n toleranceSeconds?: number;\n /** Current unix time in seconds (tests). Default `Date.now() / 1000`. */\n nowSeconds?: number;\n}\n\n/**\n * Verify a Resolve webhook delivery: `x-codai-signature: t=<unix>,v1=<hex>`\n * with `v1 = HMAC-SHA256(callback_secret, \"<t>.<rawBody>\")`. Pass the RAW\n * request body (before JSON parsing). Constant-time compare; rejects a\n * timestamp outside `toleranceSeconds`. Returns `false` for any bad input.\n *\n * Server-side only: uses `node:crypto` (Node 20.16+/22.3+, Bun, Deno), loaded\n * lazily so the rest of the SDK still bundles for browsers and edge runtimes.\n * Throws only when `node:crypto` is unavailable in the current runtime.\n */\nexport function verifyResolveWebhook(\n secret: string,\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n opts: VerifyResolveWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false;\n let t: string | undefined;\n const v1s: string[] = [];\n for (const part of signatureHeader.split(',')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n const k = part.slice(0, eq).trim();\n const v = part.slice(eq + 1).trim();\n if (k === 't') t = v;\n else if (k === 'v1') v1s.push(v.toLowerCase());\n }\n if (!t || !/^\\d+$/.test(t) || v1s.length === 0) return false;\n const tolerance = opts.toleranceSeconds ?? 300;\n const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - Number(t)) > tolerance) return false;\n const { createHmac, timingSafeEqual } = nodeCrypto();\n const enc = new TextEncoder();\n const body = typeof rawBody === 'string' ? enc.encode(rawBody) : rawBody;\n const expected = createHmac('sha256', secret)\n .update(enc.encode(`${t}.`))\n .update(body)\n .digest();\n return v1s.some((v1) => {\n if (!/^[0-9a-f]{64}$/.test(v1)) return false;\n return timingSafeEqual(hexToBytes(v1), expected);\n });\n}\n\ntype NodeCrypto = {\n createHmac(\n alg: string,\n key: string,\n ): { update(d: Uint8Array): { update(d: Uint8Array): { digest(): Uint8Array } } };\n timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;\n};\n\nfunction nodeCrypto(): NodeCrypto {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const mod = proc?.getBuiltinModule?.('node:crypto') as NodeCrypto | undefined;\n if (!mod) {\n throw new Error(\n 'verifyResolveWebhook needs node:crypto (Node 20.16+/22.3+, Bun or Deno); run it server-side',\n );\n }\n return mod;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/** `payloadType` of Resolve attestation envelopes. */\nexport const RESOLVE_ATTESTATION_PAYLOAD_TYPE =\n 'application/vnd.codai.resolve.attestation+json;v=1';\n\nexport type ResolveAttestationVerifyResult =\n | { ok: true; keyid: string }\n | { ok: false; reason: 'UNSIGNED' | 'BAD_SIGNATURE' | 'STATEMENT_MISMATCH' | 'BAD_PAYLOAD_TYPE' };\n\ntype VerifyCrypto = {\n createHash(alg: string): { update(d: Uint8Array): { digest(enc: 'hex'): string } };\n createVerify(alg: string): {\n update(d: Uint8Array): void;\n verify(key: { key: string; dsaEncoding: 'der' }, sig: Uint8Array): boolean;\n };\n};\n\nfunction verifyCrypto(): VerifyCrypto {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const mod = proc?.getBuiltinModule?.('node:crypto') as VerifyCrypto | undefined;\n if (!mod) {\n throw new Error(\n 'verifyAttestation needs node:crypto (Node 20.16+/22.3+, Bun or Deno); run it server-side',\n );\n }\n return mod;\n}\n\n/** RFC 8785 (JCS) for the JSON subset a statement uses: sorted keys, no whitespace. */\nfunction canonicalJson(v: unknown): string {\n if (v === null || typeof v !== 'object') return JSON.stringify(v);\n if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;\n const o = v as Record<string, unknown>;\n return `{${Object.keys(o)\n .filter((k) => o[k] !== undefined)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`)\n .join(',')}}`;\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/** DSSE v1 PAE: `\"DSSEv1\" SP len(type) SP type SP len(body) SP body` (byte lengths). */\nfunction pae(payloadType: string, body: Uint8Array): Uint8Array {\n const enc = new TextEncoder();\n const typeBytes = enc.encode(payloadType);\n const head = enc.encode(`DSSEv1 ${typeBytes.length} ${payloadType} ${body.length} `);\n const out = new Uint8Array(head.length + body.length);\n out.set(head, 0);\n out.set(body, head.length);\n return out;\n}\n\n/** The statement the Resolve service signs, recomputed from the attestation JSON. */\nexport function resolveAttestationStatement(att: ResolveAttestation): Record<string, unknown> {\n const { createHash } = verifyCrypto();\n const enc = new TextEncoder();\n const sha = (s: string | null | undefined) =>\n s == null ? null : createHash('sha256').update(enc.encode(s)).digest('hex');\n return {\n kind: 'codai.resolve.attestation.v1',\n attestation_id: att.id,\n repo_url: att.repo_url,\n base_commit: att.base_commit,\n patch_sha256: sha(att.patch),\n repro_test: att.repro_test?.path\n ? { path: att.repro_test.path, sha256: sha(att.repro_test.content) }\n : null,\n test_command: att.test_command,\n regression_command: att.regression_command,\n test_output_before_sha256: sha(att.test_output_before),\n test_output_after_sha256: sha(att.test_output_after),\n regression_output_sha256: sha(att.regression_output),\n runner_image_digest: att.runner_image_digest,\n started_at: att.started_at,\n verified_at: att.verified_at,\n };\n}\n\n/**\n * Verify a Resolve attestation offline against published keys: the DSSE\n * signature (ECDSA P-256/SHA-256, DER) over `PAE(payloadType, payload)` must\n * match one key, AND the signed statement must equal the one recomputed from\n * the attestation's own fields (so a valid signature over other content fails).\n * Server-side only (`node:crypto`, loaded lazily).\n */\nexport function verifyAttestationWithKeys(\n att: ResolveAttestation,\n keys: ResolveKeys,\n): ResolveAttestationVerifyResult {\n const env = att.signature;\n if (!env || !Array.isArray(env.signatures) || env.signatures.length === 0)\n return { ok: false, reason: 'UNSIGNED' };\n if (env.payloadType !== RESOLVE_ATTESTATION_PAYLOAD_TYPE)\n return { ok: false, reason: 'BAD_PAYLOAD_TYPE' };\n const { createVerify } = verifyCrypto();\n let body: Uint8Array;\n try {\n body = base64ToBytes(env.payload);\n } catch {\n return { ok: false, reason: 'BAD_SIGNATURE' };\n }\n const msg = pae(env.payloadType, body);\n let keyid: string | null = null;\n outer: for (const s of env.signatures) {\n let sig: Uint8Array;\n try {\n sig = base64ToBytes(s.sig);\n } catch {\n continue;\n }\n for (const k of keys.keys) {\n if (k.payload_type && k.payload_type !== env.payloadType) continue;\n try {\n const v = createVerify('SHA256');\n v.update(msg);\n if (v.verify({ key: k.public_key_pem, dsaEncoding: 'der' }, sig)) {\n keyid = k.keyid;\n break outer;\n }\n } catch {\n /* malformed key/signature — try the next */\n }\n }\n }\n if (keyid === null) return { ok: false, reason: 'BAD_SIGNATURE' };\n let signed: unknown;\n try {\n signed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body));\n } catch {\n return { ok: false, reason: 'STATEMENT_MISMATCH' };\n }\n if (canonicalJson(signed) !== canonicalJson(resolveAttestationStatement(att)))\n return { ok: false, reason: 'STATEMENT_MISMATCH' };\n return { ok: true, keyid };\n}\n\n/** Statuses after which a job never changes again. */\nexport const RESOLVE_TERMINAL_STATUSES: ReadonlySet<ResolveJobStatus> = new Set<ResolveJobStatus>([\n 'resolved',\n 'failed',\n 'declined',\n 'error',\n]);\n\n/** Any non-2xx answer from the Resolve service (flat `{ error }` body). */\nexport class ResolveError extends CodaiError {\n /** The `error` field of the body: a message, or Zod `flatten()` details on a 400. */\n readonly detail: string | ResolveValidationDetails | null;\n\n constructor(\n message: string,\n status: number,\n body: unknown,\n meta: { requestId?: string | null; retryAfter?: number | null } = {},\n ) {\n super(message, status, body, meta);\n this.name = 'ResolveError';\n this.detail = extractDetail(body);\n }\n}\n\n/** `402` on `accept()` — the wallet cannot hold the quote; the job stays `quoted`. */\nexport class ResolveInsufficientFundsError extends ResolveError {\n /** Wallet balance, in `currency` units (EUR micros). */\n readonly balance: number;\n /** Amount the hold needs, in `currency` units (EUR micros). */\n readonly required: number;\n readonly currency: 'micro_eur';\n /** pay.codai.ro checkout link for the shortfall — open it, then retry `accept()`. */\n readonly topupUrl: string;\n /** Present only for a `t7` job: fix-bundle checkout (10 t7 fix credits for €49). */\n readonly bundleUrl?: string;\n\n constructor(\n message: string,\n body: ResolveInsufficientFunds,\n meta: { requestId?: string | null } = {},\n ) {\n super(message, 402, body, meta);\n this.name = 'ResolveInsufficientFundsError';\n this.balance = body.balance;\n this.required = body.required;\n this.currency = body.currency;\n this.topupUrl = body.topup_url;\n if (typeof body.bundle_url === 'string') this.bundleUrl = body.bundle_url;\n }\n}\n\nexport interface ResolveWaitOptions {\n /** Poll interval (ms). Default 5_000. */\n intervalMs?: number;\n /** Give up after this long (ms); throws `ResolveError` (status 0, body = last job). Default 1_800_000. */\n timeoutMs?: number;\n /** Stop when the job reaches one of these. Default `RESOLVE_TERMINAL_STATUSES`. */\n until?: Iterable<ResolveJobStatus>;\n signal?: AbortSignal;\n /** Called with every polled job (progress UIs). */\n onPoll?: (job: ResolveJob) => void;\n}\n\ntype CallOpts = { signal?: AbortSignal };\n\n/** Query of `resolve.list()` / `resolve.iterate()`. */\nexport interface ResolveListQuery {\n /** One status or several (sent as a comma list). Omitted = every status. */\n status?: ResolveJobStatus | ResolveJobStatus[];\n /** Page size 1–100 (server default 20). */\n limit?: number;\n /** `next_cursor` of the previous page. */\n cursor?: string;\n}\n\nexport class Resolve {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/resolve/jobs` — submit a public GitHub repo + issue for triage.\n * Returns a quote (`status: 'quoted'`), a free-tier auto-accept\n * (`status: 'accepted'`) or a decline (`status: 'declined'`). Never retried:\n * a retry could create a second job.\n */\n submit(body: ResolveIntake, opts: CallOpts = {}): Promise<ResolveSubmitResult> {\n if (!body.issue_url && !body.issue_text)\n throw new TypeError('resolve.submit: one of issue_url or issue_text is required');\n return this.call<ResolveSubmitResult>('/v1/resolve/jobs', {\n method: 'POST',\n body,\n noRetry: true,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/resolve/jobs/{id}` — status, quote, reasons, cost and attestation pointer. */\n get(id: string, opts: CallOpts = {}): Promise<ResolveJob> {\n return this.call<ResolveJob>(`/v1/resolve/jobs/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/resolve/jobs` — one page of your jobs, newest first. Pass the\n * page's `next_cursor` back as `cursor` for the next page (`null` = last).\n * `status` filters by one or more statuses.\n */\n list(query: ResolveListQuery = {}, opts: CallOpts = {}): Promise<ResolveJobList> {\n const status = Array.isArray(query.status) ? query.status.join(',') : query.status;\n return this.call<ResolveJobList>('/v1/resolve/jobs', {\n query: { status: status || undefined, limit: query.limit, cursor: query.cursor },\n signal: opts.signal,\n });\n }\n\n /**\n * Every job matching `query`, newest first, following `next_cursor` page by\n * page (`limit` = page size). Stop early with `break`.\n */\n async *iterate(\n query: Omit<ResolveListQuery, 'cursor'> = {},\n opts: CallOpts = {},\n ): AsyncGenerator<ResolveJob, void, undefined> {\n let cursor: string | undefined;\n for (;;) {\n const page = await this.list({ ...query, cursor }, opts);\n for (const job of page.jobs) yield job;\n if (!page.next_cursor) return;\n cursor = page.next_cursor;\n }\n }\n\n /**\n * `POST /v1/resolve/jobs/{id}/accept` — accept a paid quote and start the job.\n * The result's `paid_with` says how it was paid (`intro` €1 hold, `credit`\n * t7 fix credit, or `wallet`). Throws `ResolveInsufficientFundsError` (402,\n * carries `topupUrl`, plus `bundleUrl` for t7) when the wallet is short,\n * `ResolveError` 409 when the job is not `quoted`.\n */\n accept(id: string, opts: CallOpts = {}): Promise<ResolveAccepted> {\n return this.call<ResolveAccepted>(`/v1/resolve/jobs/${encodeURIComponent(id)}/accept`, {\n method: 'POST',\n rawBody: '', // no body — sent with content-length: 0\n noRetry: true,\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/resolve/attestations/{id}` — public execution proof (no auth needed\n * server-side). Accepts the attestation id or the job's `attestation_url`.\n */\n attestation(idOrUrl: string, opts: CallOpts = {}): Promise<ResolveAttestation> {\n const id = idOrUrl.replace(/^.*\\/v1\\/resolve\\/attestations\\//, '');\n return this.call<ResolveAttestation>(`/v1/resolve/attestations/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n\n /** `GET /health` — liveness of the Resolve service. */\n health(opts: CallOpts = {}): Promise<ResolveHealth> {\n return this.call<ResolveHealth>('/health', { signal: opts.signal });\n }\n\n /** `GET /v1/resolve/balance` — fix credits (t7 only), intro availability and wallet balance. */\n balance(opts: CallOpts = {}): Promise<ResolveBalance> {\n return this.call<ResolveBalance>('/v1/resolve/balance', { signal: opts.signal });\n }\n\n /** `GET /v1/resolve/keys` — public keys that sign attestations (no auth needed server-side). */\n keys(opts: CallOpts = {}): Promise<ResolveKeys> {\n return this.call<ResolveKeys>('/v1/resolve/keys', { signal: opts.signal });\n }\n\n /**\n * Verify an attestation's signature and that the signed statement matches\n * its fields. Fetches `keys()` unless `opts.keys` is given (pin them to\n * avoid trusting the network). `{ ok: false, reason: 'UNSIGNED' }` for\n * attestations created before signing (2026-09-27). Server-side only.\n */\n async verifyAttestation(\n att: ResolveAttestation,\n opts: { keys?: ResolveKeys; signal?: AbortSignal } = {},\n ): Promise<ResolveAttestationVerifyResult> {\n if (!att.signature) return { ok: false, reason: 'UNSIGNED' };\n const keys = opts.keys ?? (await this.keys({ signal: opts.signal }));\n return verifyAttestationWithKeys(att, keys);\n }\n\n /**\n * Poll `get(id)` until the job reaches a terminal status (`resolved`,\n * `failed`, `declined`, `error`) or one of `opts.until`. A `quoted` job\n * does not move until you `accept()` it.\n */\n async waitFor(id: string, opts: ResolveWaitOptions = {}): Promise<ResolveJob> {\n const intervalMs = opts.intervalMs ?? 5_000;\n const timeoutMs = opts.timeoutMs ?? 1_800_000;\n const until = new Set(opts.until ?? RESOLVE_TERMINAL_STATUSES);\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const job = await this.get(id, { signal: opts.signal });\n opts.onPoll?.(job);\n if (until.has(job.status)) return job;\n const left = deadline - Date.now();\n if (left <= 0)\n throw new ResolveError(\n `codai-resolve job ${id} still ${job.status} after ${timeoutMs} ms`,\n 0,\n job,\n );\n await abortableSleep(Math.min(intervalMs, left), opts.signal);\n }\n }\n\n private async call<T>(path: string, init: RequestOptions): Promise<T> {\n try {\n return await this.http.json<T>(path, init);\n } catch (err) {\n throw toResolveError(path, err);\n }\n }\n}\n\nfunction extractDetail(body: unknown): string | ResolveValidationDetails | null {\n if (body && typeof body === 'object' && 'error' in body) {\n const e = (body as { error: unknown }).error;\n if (typeof e === 'string') return e;\n if (e && typeof e === 'object') return e as ResolveValidationDetails;\n }\n return null;\n}\n\nfunction isInsufficientFunds(body: unknown): body is ResolveInsufficientFunds {\n return (\n !!body &&\n typeof body === 'object' &&\n (body as { error?: unknown }).error === 'insufficient_funds' &&\n typeof (body as { topup_url?: unknown }).topup_url === 'string'\n );\n}\n\n/** Re-type a `CodaiError` from the shared HTTP layer into the Resolve hierarchy. */\nfunction toResolveError(path: string, err: unknown): unknown {\n if (!(err instanceof CodaiError) || err instanceof ResolveError) return err;\n if (err.status === 0) return err; // network/timeout — nothing Resolve-specific\n const meta = { requestId: err.requestId, retryAfter: err.retryAfter };\n if (err.status === 402 && isInsufficientFunds(err.body)) {\n const b = err.body;\n return new ResolveInsufficientFundsError(\n `codai-resolve ${path} → 402: insufficient funds (balance ${b.balance}, required ${b.required} ${b.currency}); top up at ${b.topup_url}${b.bundle_url ? ` or buy 10 t7 fixes for €49 at ${b.bundle_url}` : ''}`,\n b,\n meta,\n );\n }\n const detail = extractDetail(err.body);\n const text =\n detail === null ? '' : `: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`;\n return new ResolveError(\n `codai-resolve ${path} → ${err.status}${text}`,\n err.status,\n err.body,\n meta,\n );\n}\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason);\n };\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/** `POST /v1/responses` — OpenAI Responses API compatibility (JSON + named-event SSE). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient, readSse } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type ResponsesRequest = Mutable<Body<'createResponse'>>;\nexport type ResponsesResponse = Reply<'createResponse'>;\n/** Request body as accepted by the SDK: `stream` is set by the method and `model` defaults to `codai`. */\nexport type ResponsesInput = Omit<ResponsesRequest, 'stream' | 'model'> & { model?: string };\n\nexport interface ResponsesCallOptions {\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface ResponsesResult {\n /** `output_text` of the response. */\n outputText: string;\n raw: ResponsesResponse;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers;\n}\n\n/** One Responses streaming event; `type` mirrors the SSE `event:` name. */\nexport interface ResponsesStreamEvent {\n type:\n | 'response.created'\n | 'response.output_text.delta'\n | 'response.output_item.done'\n | 'response.output_text.done'\n | 'response.completed'\n | (string & {});\n sequence_number?: number;\n [key: string]: unknown;\n}\n\nexport interface ResponsesStreamResult {\n outputText: string;\n /** The full `response` object from `response.completed`, when received. */\n response: ResponsesResponse | null;\n requestId: string | null;\n routedTo: string | null;\n headers: Headers | null;\n}\n\nexport interface ResponsesStream extends AsyncIterable<ResponsesStreamEvent> {\n readonly final: Promise<ResponsesStreamResult>;\n /** Text deltas only. */\n text(): AsyncIterable<string>;\n}\n\nexport class Responses {\n constructor(private readonly http: HttpClient) {}\n\n async create(body: ResponsesInput, opts: ResponsesCallOptions = {}): Promise<ResponsesResult> {\n const res = await this.http.request('/v1/responses', {\n body: { ...body, model: body.model ?? 'codai', stream: false },\n ext: opts.ext,\n signal: opts.signal,\n });\n const raw = (await res.json()) as ResponsesResponse;\n return {\n outputText: typeof raw.output_text === 'string' ? raw.output_text : '',\n raw,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id'),\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n };\n }\n\n stream(body: ResponsesInput, opts: ResponsesCallOptions = {}): ResponsesStream {\n const requestPromise = this.http.request('/v1/responses', {\n body: { ...body, model: body.model ?? 'codai', stream: true },\n ext: opts.ext,\n signal: opts.signal,\n timeoutMs: 0,\n noRetry: true,\n });\n\n let resolveFinal!: (r: ResponsesStreamResult) => void;\n let rejectFinal!: (e: unknown) => void;\n const final = new Promise<ResponsesStreamResult>((resolve, reject) => {\n resolveFinal = resolve;\n rejectFinal = reject;\n });\n final.catch(() => {});\n\n let outputText = '';\n let response: ResponsesResponse | null = null;\n let res: Response | null = null;\n\n async function* events(): AsyncGenerator<ResponsesStreamEvent, void, undefined> {\n try {\n res = await requestPromise;\n for await (const frame of readSse(res, opts.signal)) {\n const ev = frameJson<ResponsesStreamEvent>(frame);\n if (!ev) continue;\n if (typeof ev.type !== 'string') ev.type = frame.event;\n if (ev.type === 'response.output_text.delta' && typeof ev.delta === 'string') {\n outputText += ev.delta;\n } else if (ev.type === 'response.completed' && ev.response) {\n response = ev.response as ResponsesResponse;\n }\n yield ev;\n if (ev.type === 'response.completed') break;\n }\n resolveFinal({\n outputText,\n response,\n requestId: res.headers.get('x-codai-trace-id') ?? res.headers.get('x-request-id') ?? null,\n routedTo: res.headers.get('x-codai-routed-to'),\n headers: res.headers,\n });\n } catch (err) {\n rejectFinal(err);\n throw err;\n }\n }\n\n async function* textOnly(): AsyncGenerator<string, void, undefined> {\n for await (const ev of events()) {\n if (ev.type === 'response.output_text.delta' && typeof ev.delta === 'string')\n yield ev.delta;\n }\n }\n\n return {\n [Symbol.asyncIterator]: () => events(),\n text: () => ({ [Symbol.asyncIterator]: () => textOnly() }),\n final,\n };\n }\n}\n","/**\n * `/v1/sessions/*` — shared-sessions protocol v2 (events, controls, lease,\n * dispatch, SSE stream) plus the per-session shares under `/shares`.\n *\n * Every call needs the `x-codai-device` header: set it once via\n * `new Codai({ device: '<uuid>' })` or per call through `ext.device`.\n */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Session = Schema<'Session'>;\nexport type SessionListItem = Schema<'SessionListItem'>;\nexport type SessionDetail = Reply<'getSession'>;\nexport type SessionCreateRequest = Mutable<Body<'createSession'>>;\nexport type SessionPatchRequest = Mutable<Body<'updateSession'>>;\nexport type SessionEvent = Schema<'SessionEvent'>;\nexport type SessionIncomingEvent = Mutable<Schema<'SessionIncomingEvent'>>;\nexport type SessionEventsAppendRequest = Mutable<Body<'appendSessionEvents'>>;\nexport type SessionEventsAppendResponse = Reply<'appendSessionEvents'>;\nexport type SessionEventsPage = Reply<'listSessionEvents'>;\nexport type SessionControl = Schema<'SessionControl'>;\nexport type SessionControlRequest = Mutable<Body<'submitSessionControl'>>;\nexport type SessionControlAccepted = Reply<'submitSessionControl', 202>;\ntype SessionDispatchBase = Omit<Mutable<Body<'dispatchToDevice'>>, 'mode' | 'text' | 'turn_id'>;\n/**\n * `POST …/dispatch` body. `send` (the default) needs `text` and runs it as a new turn on the\n * target; `open` is a handoff — the target only opens the session, so it takes no text/turn.\n */\nexport type SessionDispatchRequest =\n | (SessionDispatchBase & { mode?: 'send'; text: string; turn_id?: string })\n | (SessionDispatchBase & { mode: 'open'; text?: never; turn_id?: never });\nexport type SessionDispatchMode = NonNullable<Body<'dispatchToDevice'>['mode']>;\nexport type SessionDispatchResponse = Reply<'dispatchToDevice', 202>;\nexport type SessionLeaseClaimRequest = Mutable<Body<'claimSessionLease'>>;\nexport type SessionLeaseResponse = Reply<'claimSessionLease'>;\nexport type SessionShare = Schema<'OrgSessionShare'>;\nexport type SessionShareCreateRequest = Mutable<Body<'createSessionShare'>>;\nexport type SessionShareCreated = Reply<'createSessionShare', 201>;\nexport type SharedSession = Schema<'OrgSharedSession'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\n/** Frames of `GET /v1/sessions/{id}/stream`; every payload carries `v: 1`. */\nexport type SessionStreamEvent =\n | { event: 'event'; data: { v: 1; seq: number } & Record<string, unknown> }\n | {\n event: 'control';\n data: { v: 1; id: string; kind: string; seq: number | null; applied: boolean } & Record<\n string,\n unknown\n >;\n }\n | { event: 'lease'; data: { v: 1; holder_device_id: string | null; expires_at: string | null } }\n | {\n event: 'presence';\n data: {\n v: 1;\n device_id: string;\n user_id: string;\n role: string;\n executor: boolean;\n last_seen: string;\n driving: boolean;\n online: boolean;\n };\n }\n | { event: string; data: Record<string, unknown> };\n\nconst enc = encodeURIComponent;\n\nexport class SessionLease {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/sessions/{id}/lease` — CAS claim; `force: true` takes over a live lease. */\n acquire(\n sessionId: string,\n body: SessionLeaseClaimRequest = {},\n opts: CallOpts = {},\n ): Promise<SessionLeaseResponse> {\n return this.http.json<SessionLeaseResponse>(`/v1/sessions/${enc(sessionId)}/lease`, {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PUT /v1/sessions/{id}/lease` — heartbeat every 10 s (TTL 30 s). */\n renew(sessionId: string, opts: CallOpts = {}): Promise<SessionLeaseResponse> {\n return this.http.json<SessionLeaseResponse>(`/v1/sessions/${enc(sessionId)}/lease`, {\n method: 'PUT',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sessions/{id}/lease` */\n release(sessionId: string, opts: CallOpts = {}): Promise<Reply<'releaseSessionLease'>> {\n return this.http.json<Reply<'releaseSessionLease'>>(`/v1/sessions/${enc(sessionId)}/lease`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class SessionEvents {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/sessions/{id}/events?after=&limit=` */\n list(\n sessionId: string,\n query: Mutable<QueryOf<'listSessionEvents'>> = {},\n opts: CallOpts = {},\n ): Promise<SessionEventsPage> {\n return this.http.json<SessionEventsPage>(`/v1/sessions/${enc(sessionId)}/events`, {\n query: { after: query.after, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sessions/{id}/events` — executor only (needs the live lease). */\n append(\n sessionId: string,\n body: SessionEventsAppendRequest,\n opts: CallOpts = {},\n ): Promise<SessionEventsAppendResponse> {\n return this.http.json<SessionEventsAppendResponse>(`/v1/sessions/${enc(sessionId)}/events`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class SessionControls {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/sessions/{id}/controls?applied=&target=` — drain the control queue. */\n async list(\n sessionId: string,\n query: { applied?: boolean; target?: 'me' | string } = {},\n opts: CallOpts = {},\n ): Promise<SessionControl[]> {\n const raw = await this.http.json<Reply<'listSessionControls'>>(\n `/v1/sessions/${enc(sessionId)}/controls`,\n {\n query: { applied: query.applied, target: query.target },\n ext: opts.ext,\n signal: opts.signal,\n },\n );\n return [...(raw.controls ?? [])];\n }\n\n /** `POST /v1/sessions/{id}/control` — send a control to the executor (editor+). */\n submit(\n sessionId: string,\n body: SessionControlRequest,\n opts: CallOpts = {},\n ): Promise<SessionControlAccepted> {\n return this.http.json<SessionControlAccepted>(`/v1/sessions/${enc(sessionId)}/control`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sessions/{id}/control/{cid}/applied` — executor only. */\n markApplied(\n sessionId: string,\n controlId: string,\n opts: CallOpts = {},\n ): Promise<Reply<'markSessionControlApplied'>> {\n return this.http.json<Reply<'markSessionControlApplied'>>(\n `/v1/sessions/${enc(sessionId)}/control/${enc(controlId)}/applied`,\n { method: 'POST', ext: opts.ext, signal: opts.signal },\n );\n }\n}\n\nexport class SessionShares {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/sessions/{id}/shares` — owner only. */\n async list(sessionId: string, opts: CallOpts = {}): Promise<SessionShare[]> {\n const raw = await this.http.json<Reply<'listSessionShares'>>(\n `/v1/sessions/${enc(sessionId)}/shares`,\n { ext: opts.ext, signal: opts.signal },\n );\n return [...(raw.shares ?? [])];\n }\n\n /** `POST /v1/sessions/{id}/shares` — `token` is returned once for link shares. */\n create(\n sessionId: string,\n body: SessionShareCreateRequest,\n opts: CallOpts = {},\n ): Promise<SessionShareCreated> {\n return this.http.json<SessionShareCreated>(`/v1/sessions/${enc(sessionId)}/shares`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sessions/{id}/shares/{shareId}` */\n delete(\n sessionId: string,\n shareId: string,\n opts: CallOpts = {},\n ): Promise<Reply<'deleteSessionShare'>> {\n return this.http.json<Reply<'deleteSessionShare'>>(\n `/v1/sessions/${enc(sessionId)}/shares/${enc(shareId)}`,\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `GET /v1/sessions/shared-with-me` */\n async sharedWithMe(\n query: { archived?: boolean } = {},\n opts: CallOpts = {},\n ): Promise<SharedSession[]> {\n const raw = await this.http.json<Reply<'listSessionsSharedWithMe'>>(\n '/v1/sessions/shared-with-me',\n {\n query: { archived: query.archived ? '1' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n },\n );\n return [...(raw.sessions ?? [])];\n }\n}\n\nexport class Sessions {\n readonly events: SessionEvents;\n readonly controls: SessionControls;\n readonly lease: SessionLease;\n readonly shares: SessionShares;\n\n constructor(private readonly http: HttpClient) {\n this.events = new SessionEvents(http);\n this.controls = new SessionControls(http);\n this.lease = new SessionLease(http);\n this.shares = new SessionShares(http);\n }\n\n /** `POST /v1/sessions` — idempotent on `session_key` (200 existing / 201 created). */\n async create(\n body: SessionCreateRequest = {},\n opts: CallOpts = {},\n ): Promise<Session & { created: boolean }> {\n const res = await this.http.request('/v1/sessions', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n const session = (await res.json()) as Session;\n return { ...session, created: res.status === 201 };\n }\n\n /** `GET /v1/sessions?limit=&archived=` — own sessions first, then shared. */\n async list(\n query: { limit?: number; archived?: boolean } = {},\n opts: CallOpts = {},\n ): Promise<SessionListItem[]> {\n const raw = await this.http.json<Reply<'listSessions'>>('/v1/sessions', {\n query: { limit: query.limit, archived: query.archived ? '1' : undefined, v: '2' },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.sessions ?? [])];\n }\n\n /** `GET /v1/sessions/{id}` — detail with members, lease and presence. */\n get(\n sessionId: string,\n query: { share?: string } = {},\n opts: CallOpts = {},\n ): Promise<SessionDetail> {\n return this.http.json<SessionDetail>(`/v1/sessions/${enc(sessionId)}`, {\n query: { share: query.share, v: '2' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/sessions/{id}` — rename / archive (owner). */\n update(sessionId: string, body: SessionPatchRequest, opts: CallOpts = {}): Promise<Session> {\n return this.http.json<Session>(`/v1/sessions/${enc(sessionId)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sessions/{id}` — irreversible (owner). */\n delete(sessionId: string, opts: CallOpts = {}): Promise<Reply<'deleteSession'>> {\n return this.http.json<Reply<'deleteSession'>>(`/v1/sessions/${enc(sessionId)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sessions/{id}/dispatch` — queue a `send` for one device and wake it over FCM.\n * `{ mode: 'open' }` hands the session off instead: the target just opens it (no user turn).\n */\n dispatch(\n sessionId: string,\n body: SessionDispatchRequest,\n opts: CallOpts = {},\n ): Promise<SessionDispatchResponse> {\n return this.http.json<SessionDispatchResponse>(`/v1/sessions/${enc(sessionId)}/dispatch`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `GET /v1/sessions/{id}/stream?after=` — live SSE of `event` / `control` /\n * `lease` / `presence` frames. `: ping` heartbeats are skipped. The server\n * closes after 30 min; reconnect with `after` = highest `seq` seen.\n */\n async *stream(\n sessionId: string,\n query: { after?: number; share?: string } = {},\n opts: CallOpts = {},\n ): AsyncGenerator<SessionStreamEvent, void, undefined> {\n const frames = this.http.sse(`/v1/sessions/${enc(sessionId)}/stream`, {\n query: { after: query.after, share: query.share },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<Record<string, unknown>>(frame);\n if (!data) continue;\n yield { event: frame.event, data } as SessionStreamEvent;\n }\n }\n}\n","/**\n * `/v1/settings` — account-level settings shared by every device of the account (per user, not per key). Reads\n * always return the full object with defaults applied; writes deep-merge a partial and are validated strictly.\n *\n * Optimistic concurrency: pass `{ version }` from the last read to `update()`. On a mismatch the gateway answers 409\n * `version_conflict` and nothing is written; the thrown `CodaiError` carries the current state in\n * `(err.body as SettingsConflict).current` (see {@link settingsConflictCurrent}).\n */\nimport { CodaiError, type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type SettingsResponse = Reply<'getSettings'>;\nexport type UserSettings = Schema<'UserSettings'>;\nexport type TranscriptsSettings = Schema<'TranscriptsSettings'>;\nexport type SettingsConflict = Schema<'SettingsConflict'>;\n\n/** A deep partial of {@link UserSettings}: only the fields to change (`language: null` = auto-detect). */\nexport type SettingsPatch = {\n transcripts?: { -readonly [K in keyof TranscriptsSettings]?: TranscriptsSettings[K] };\n};\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\ntype UpdateOpts = CallOpts & { version?: number };\n\n/** The `current` state of a 409 `version_conflict` thrown by `settings.update`, else null. */\nexport function settingsConflictCurrent(err: unknown): SettingsResponse | null {\n if (!(err instanceof CodaiError) || err.status !== 409 || err.code !== 'version_conflict')\n return null;\n const current = (err.body as Partial<SettingsConflict> | null)?.current;\n return current ?? null;\n}\n\nexport class Settings {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/settings` — full settings with defaults; `version` 0 / `updatedAt` null until the first write. */\n get(opts: CallOpts = {}): Promise<SettingsResponse> {\n return this.http.json<SettingsResponse>('/v1/settings', { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `PATCH /v1/settings` — deep-merge `partial` into the stored settings. With `opts.version` the write is\n * conditional (409 `version_conflict` on a mismatch). Unknown keys / invalid values throw a 400 `CodaiError`.\n */\n update(partial: SettingsPatch, opts: UpdateOpts = {}): Promise<SettingsResponse> {\n return this.http.json<SettingsResponse>('/v1/settings', {\n method: 'PATCH',\n body: { settings: partial, ...(opts.version !== undefined ? { version: opts.version } : {}) },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * OS protection gate (spec `packages/agent-core/spec/os-gate.json`).\n *\n * `GET /v1/policy` — effective client policy; `os_gate.allow_override` is false when ANY org of the\n * caller forbids overrides. Cache it (the gateway sends `max-age=300`) and keep the\n * last value offline; a 503 `policy_unavailable` means \"keep the cached value\".\n * `POST /v1/os-gate/events` — audit an override granted/revoked on a device (check ids + surface + app version +\n * time only; detection details never leave the device). Answers 202 `{ ok: true }`.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply, type Schema } from './_shared';\n\nexport type PolicyResponse = Reply<'getPolicy'>;\nexport type OsGateEvent = Schema<'OsGateEvent'>;\nexport type OsGateCheckId = OsGateEvent['checks'][number];\nexport type OsGateSurface = OsGateEvent['surface'];\nexport type OsGateEventAccepted = Schema<'OsGateEventAccepted'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class OsGate {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/policy` — `{ os_gate: { allow_override } }` folded over every org of the caller (strictest wins). */\n policy(opts: CallOpts = {}): Promise<PolicyResponse> {\n return this.http.json<PolicyResponse>('/v1/policy', { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `POST /v1/os-gate/events` — record that the user granted or revoked an override of `checks` on `surface`.\n * The body is strict: unknown keys, unknown check ids or an empty `checks` list throw a 400 `CodaiError`.\n */\n recordEvent(event: OsGateEvent, opts: CallOpts = {}): Promise<OsGateEventAccepted> {\n return this.http.json<OsGateEventAccepted>('/v1/os-gate/events', {\n method: 'POST',\n body: event,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/studio/sfx` — the codai Studio sound-effects library (`codai-sfx`): curated CC0 sounds (Kenney packs) plus a\n * Freesound CC0-only fallback when the gateway has one configured. Searching and importing are free; an imported\n * sound becomes a studio asset (`kind: 'sfx'`) usable as `asset:<asset_id>` in `renders.create`.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type AssetDto } from './assets';\nimport { type QueryOf, type Reply, type Schema } from './_shared';\n\n/** One sound (always `license: 'CC0-1.0'`). */\nexport type SfxDto = Schema<'SfxDto'>;\nexport type SfxCategory = Schema<'SfxCategory'>;\nexport type SfxList = Reply<'searchSfx'>;\n/** `GET /v1/studio/sfx` query; `tags` may also be passed as an array (joined with commas). */\nexport type SfxSearchParams = Omit<QueryOf<'searchSfx'>, 'tags'> & {\n tags?: string | readonly string[];\n};\n/** Search result plus whether the Freesound fallback failed (`x-codai-sfx-fallback: unavailable`). */\nexport type SfxSearchResult = SfxList & { fallbackUnavailable: boolean };\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Sfx {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/studio/sfx` — best match first; `limit` 1–50 (default 20). */\n async search(params: SfxSearchParams = {}, opts: CallOpts = {}): Promise<SfxSearchResult> {\n const tags = Array.isArray(params.tags)\n ? params.tags.join(',')\n : (params.tags as string | undefined);\n const res = await this.http.request('/v1/studio/sfx', {\n query: {\n q: params.q,\n category: params.category,\n tags: tags || undefined,\n max_duration: params.max_duration,\n limit: params.limit,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n const body = (await res.json()) as SfxList;\n return {\n ...body,\n fallbackUnavailable: res.headers.get('x-codai-sfx-fallback') === 'unavailable',\n };\n }\n\n /**\n * `POST /v1/studio/sfx/{sfx_id}/import` — copies the sound into your assets (`kind: 'sfx'`, free). Freesound items\n * whose licence is not CC0 are refused with 400 `license_not_allowed`; an unknown id is 404.\n */\n import(sfxId: string, opts: CallOpts = {}): Promise<AssetDto> {\n return this.http.json<AssetDto>(`/v1/studio/sfx/${encodeURIComponent(sfxId)}/import`, {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `POST /v1/systemone` — typed decisions from codai-s1 (Choice / Score / Noul). */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type SystemOneRequest = Mutable<Body<'createSystemOne'>>;\nexport type SystemOneResponse = Reply<'createSystemOne'>;\ntype SystemOneState = NonNullable<SystemOneRequest['state']>;\nexport type SystemOneAnswers = NonNullable<SystemOneResponse['answers']>;\n\n/** Single-state call: `answers` is always present. */\nexport type SystemOneSingleRequest = Omit<SystemOneRequest, 'items'> & { state: SystemOneState };\nexport type SystemOneSingleResponse = SystemOneResponse & { answers: SystemOneAnswers };\n\n/** Batch call (1-16 items, same questions, run concurrently). */\nexport type SystemOneBatchRequest = Omit<SystemOneRequest, 'state' | 'items'> & {\n items: Array<{ id: string; state: SystemOneState }>;\n};\nexport type SystemOneBatchResponse = SystemOneResponse & {\n items: Array<{ id: string; answers: SystemOneAnswers }>;\n};\n\nexport class SystemOne {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Ask one or more typed questions about `state` (or about each of `items`). Throws on 503\n * `s1_unavailable` like any other error — keep a local fallback and catch it. The gateway\n * substitutes a generative model ONLY when you pass `fallback: 'codai-fast'`, and then the\n * response says `fallback_used: true`. `timeout_ms` (100-5000) bounds the s1 call.\n */\n async create(\n body: SystemOneSingleRequest,\n opts?: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<SystemOneSingleResponse>;\n async create(\n body: SystemOneBatchRequest,\n opts?: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<SystemOneBatchResponse>;\n async create(\n body: SystemOneRequest,\n opts?: { ext?: CodaiRequestExtensions; signal?: AbortSignal },\n ): Promise<SystemOneResponse>;\n async create(\n body: SystemOneRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SystemOneResponse> {\n const res = await this.http.request('/v1/systemone', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n return (await res.json()) as SystemOneResponse;\n }\n\n /** Same questions about up to 16 states in one call; results come back in `items` order. */\n batch(\n body: SystemOneBatchRequest,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<SystemOneBatchResponse> {\n return this.create(body, opts);\n }\n}\n","/** `/v1/tasks/*` — outcome-billing task lifecycle. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Task = Schema<'Task'>;\nexport type TaskOutcome = Schema<'TaskOutcome'>;\nexport type TaskStats = Reply<'getTaskStats'>;\nexport type TaskListPage = Reply<'listTasks'>;\nexport type TaskConfirmRequest = Mutable<Body<'confirmTask'>>;\nexport type TaskConfirmResponse = Reply<'confirmTask'>;\nexport type TaskListQuery = Mutable<QueryOf<'listTasks'>>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Tasks {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/tasks` — newest first; page with `cursor` = previous `next_cursor`. */\n list(query: TaskListQuery = {}, opts: CallOpts = {}): Promise<TaskListPage> {\n return this.http.json<TaskListPage>('/v1/tasks', {\n query: { outcome: query.outcome, limit: query.limit, cursor: query.cursor },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/tasks/pending` — tasks awaiting your confirmation (max 100). */\n async pending(opts: CallOpts = {}): Promise<Task[]> {\n const raw = await this.http.json<Reply<'listPendingTasks'>>('/v1/tasks/pending', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...(raw.tasks ?? [])];\n }\n\n /** `GET /v1/tasks/stats?since=` */\n stats(since?: string | Date, opts: CallOpts = {}): Promise<TaskStats> {\n return this.http.json<TaskStats>('/v1/tasks/stats', {\n query: { since: since instanceof Date ? since.toISOString() : since },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/tasks/{id}` */\n get(id: string, opts: CallOpts = {}): Promise<Task> {\n return this.http.json<Task>(`/v1/tasks/${encodeURIComponent(id)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/tasks/{id}/confirm` — answer \"Did codai solve it?\". */\n confirm(id: string, body: TaskConfirmRequest, opts: CallOpts = {}): Promise<TaskConfirmResponse> {\n return this.http.json<TaskConfirmResponse>(`/v1/tasks/${encodeURIComponent(id)}/confirm`, {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `/v1/triggers/*` + `/v1/notifications/*` — event triggers (webhooks → agent sessions) and the inbox. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type TriggerList = Reply<'listTriggers'>;\nexport type TriggerCreateRequest = Mutable<Body<'createTrigger'>>;\nexport type TriggerCreated = Reply<'createTrigger'>;\nexport type TriggerPatch = Mutable<Body<'updateTrigger'>>;\nexport type TriggerUpdated = Reply<'updateTrigger'>;\nexport type TriggerTestRequest = Mutable<Body<'testTrigger'>>;\nexport type TriggerTestResult = Reply<'testTrigger'>;\nexport type TriggerEvents = Reply<'listTriggerEvents'>;\nexport type NotificationList = Reply<'listNotifications'>;\nexport type NotificationsRead = Reply<'markNotificationsRead'>;\n/** Reply of `DELETE /v1/notifications/:id` and `POST /v1/notifications/delete`. */\nexport type NotificationsDeleted = { readonly deleted: number };\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Triggers {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/triggers` — never includes the signing secret. */\n list(opts: CallOpts = {}): Promise<TriggerList> {\n return this.http.json<TriggerList>('/v1/triggers', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/triggers` — the response carries the signing `secret` ONCE. */\n create(body: TriggerCreateRequest, opts: CallOpts = {}): Promise<TriggerCreated> {\n return this.http.json<TriggerCreated>('/v1/triggers', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/triggers/{id}` — name / enabled / policy. */\n update(id: string, body: TriggerPatch, opts: CallOpts = {}): Promise<TriggerUpdated> {\n return this.http.json<TriggerUpdated>(`/v1/triggers/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/triggers/{id}` — its hook URL stops working immediately. */\n delete(id: string, opts: CallOpts = {}): Promise<Reply<'deleteTrigger'>> {\n return this.http.json<Reply<'deleteTrigger'>>(`/v1/triggers/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/triggers/{id}/rotate-secret` — new secret, shown once. */\n rotateSecret(id: string, opts: CallOpts = {}): Promise<Reply<'rotateTriggerSecret'>> {\n return this.http.json<Reply<'rotateTriggerSecret'>>(\n `/v1/triggers/${encodeURIComponent(id)}/rotate-secret`,\n { method: 'POST', body: {}, ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `POST /v1/triggers/{id}/test` — manual fire through the full pipeline; returns the decision + reason. */\n /** `PUT /v1/triggers/{id}/secret` — store a secret issued by the source (e.g. a Sentry integration's client secret). */\n setSecret(id: string, secret: string, opts: CallOpts = {}): Promise<Reply<'setTriggerSecret'>> {\n return this.http.json<Reply<'setTriggerSecret'>>(\n `/v1/triggers/${encodeURIComponent(id)}/secret`,\n { method: 'PUT', body: { secret }, ext: opts.ext, signal: opts.signal, noRetry: true },\n );\n }\n\n /** `POST /v1/triggers/{id}/test` — manual fire through the full pipeline; returns the decision + reason. */\n test(id: string, body: TriggerTestRequest = {}, opts: CallOpts = {}): Promise<TriggerTestResult> {\n return this.http.json<TriggerTestResult>(`/v1/triggers/${encodeURIComponent(id)}/test`, {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/triggers/{id}/events?limit=` — recent deliveries with decisions. */\n events(id: string, limit?: number, opts: CallOpts = {}): Promise<TriggerEvents> {\n return this.http.json<TriggerEvents>(`/v1/triggers/${encodeURIComponent(id)}/events`, {\n query: { limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/hooks/{id}` — send an event to a `generic` / `form` trigger from your own code. Signs the body\n * (`X-Codai-Signature: t=<unix>,v1=HMAC_SHA256(secret, \"<t>.<body>\")`, WebCrypto — Node 20+, browsers, Deno,\n * Workers). `deliveryId` makes retries idempotent. The hook needs no API key (the signature is the auth).\n */\n async fireHook(\n id: string,\n secret: string,\n event: {\n title: string;\n message?: string;\n severity?: 'info' | 'low' | 'medium' | 'high' | 'critical';\n url?: string;\n subject?: string;\n labels?: string[];\n dedupe_key?: string;\n resolved?: boolean;\n },\n opts: CallOpts & { deliveryId?: string } = {},\n ): Promise<Reply<'receiveTriggerHook'>> {\n const raw = JSON.stringify(event);\n const t = Math.floor(Date.now() / 1000);\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const mac = new Uint8Array(\n await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${t}.${raw}`)),\n );\n const v1 = Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n return this.http.json<Reply<'receiveTriggerHook'>>(`/v1/hooks/${encodeURIComponent(id)}`, {\n method: 'POST',\n rawBody: raw,\n ext: {\n ...opts.ext,\n headers: {\n ...opts.ext?.headers,\n 'Content-Type': 'application/json',\n 'x-codai-signature': `t=${t},v1=${v1}`,\n ...(opts.deliveryId ? { 'x-codai-delivery': opts.deliveryId } : {}),\n },\n },\n signal: opts.signal,\n });\n }\n}\n\nexport class Notifications {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/notifications?unread=1&limit=` — newest first. */\n list(\n query: { unread?: boolean; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<NotificationList> {\n return this.http.json<NotificationList>('/v1/notifications', {\n query: { unread: query.unread ? '1' : undefined, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/notifications/read` — `ids` omitted = every unread one. */\n markRead(ids?: number[], opts: CallOpts = {}): Promise<NotificationsRead> {\n return this.http.json<NotificationsRead>('/v1/notifications/read', {\n method: 'POST',\n body: ids ? { ids } : {},\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/notifications/:id` — `{ deleted: 0 }` when the id is missing or not yours. */\n delete(id: number, opts: CallOpts = {}): Promise<NotificationsDeleted> {\n return this.http.json<NotificationsDeleted>(\n `/v1/notifications/${encodeURIComponent(String(id))}`,\n { method: 'DELETE', ext: opts.ext, signal: opts.signal },\n );\n }\n\n /** `POST /v1/notifications/delete` — 1..200 ids; ids of other users are skipped. */\n deleteMany(ids: number[], opts: CallOpts = {}): Promise<NotificationsDeleted> {\n return this.http.json<NotificationsDeleted>('/v1/notifications/delete', {\n method: 'POST',\n body: { ids },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/** `/v1/prompts/*` — pending prompts: ready-to-paste prompts left for a future chat (handoffs, follow-ups). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\n/** PR-07 recurrence: repeat every day/week/month (at HH:MM UTC), or reopen when the run session ends. */\nexport type PromptRecurrence = Mutable<Schema<'PromptRecurrence'>>;\n/** PR-07 launch preset applied when the prompt is started. */\nexport type PromptLaunchConfig = Mutable<Schema<'PromptLaunchConfig'>>;\n\nexport type Prompt = Schema<'Prompt'>;\n/** PR-04 / PR-07 organise fields (present on every prompt row). */\nexport type PromptOrganizeFields = Pick<\n Prompt,\n 'tags' | 'priority' | 'recurrence' | 'next_prompt_id' | 'launch' | 'is_template'\n>;\nexport type PromptStatus = Schema<'PromptStatus'>;\nexport type PromptSource = Schema<'PromptSource'>;\nexport type PromptList = Reply<'listPrompts'>;\n/** PR-04 list / export filters; `tag` also accepts one string (a single tag or a comma list). AND semantics. */\nexport type PromptListFilters = Omit<\n Mutable<QueryOf<'listPrompts'>>,\n 'tag' | 'status' | 'limit'\n> & { tag?: string | string[] };\nexport type PromptListQuery = Omit<Mutable<QueryOf<'listPrompts'>>, 'tag'> & PromptListFilters;\nexport type PromptCreateRequest = Mutable<Body<'createPrompt'>>;\nexport type PromptCreated = Reply<'createPrompt'>;\nexport type PromptPatch = Mutable<Body<'updatePrompt'>>;\nexport type PromptLaunched = Reply<'launchPrompt'>;\nexport type PromptDeleted = Reply<'deletePrompt'>;\nexport type PromptReport = Schema<'PromptReport'>;\nexport type PromptMatchRequest = Mutable<Body<'matchPrompt'>>;\nexport type PromptMatched = Reply<'matchPrompt'>;\nexport type PromptVerifyRequest = Mutable<Body<'verifyPrompt'>>;\nexport type PromptVerified = Reply<'verifyPrompt'>;\nexport type PromptVerifyManyRequest = Mutable<Body<'verifyPrompts'>>;\nexport type PromptVerifyManyResult = Reply<'verifyPrompts'>;\n\n/** PR-05 `POST /v1/prompts/bulk`. */\nexport type PromptBulkRequest = Mutable<Body<'bulkPrompts'>>;\nexport type PromptBulkResult = Reply<'bulkPrompts'>;\nexport type PromptHistoryEvent = Schema<'PromptEvent'>;\nexport type PromptEventKind = PromptHistoryEvent['kind'];\nexport type PromptEventList = Reply<'listPromptEvents'>;\nexport type PromptExportQuery = Omit<Mutable<QueryOf<'exportPrompts'>>, 'tag'> & PromptListFilters;\n\n/** One `event: prompt` frame of `GET /v1/prompts/stream`. */\nexport interface PromptStreamEvent {\n op: 'upsert' | 'delete';\n id: string;\n status: PromptStatus | 'deleted';\n /** Full prompt on `upsert`. */\n prompt?: Prompt;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/prompts/${encodeURIComponent(id)}${suffix}`;\n\nfunction filterQuery(q: PromptListFilters & { status?: string; limit?: number }) {\n const tag = Array.isArray(q.tag) ? q.tag.join(',') : q.tag;\n return {\n status: q.status,\n limit: q.limit,\n tag: tag || undefined,\n priority_min: q.priority_min,\n q: q.q,\n templates: q.templates,\n sort: q.sort,\n order: q.order,\n };\n}\n\nexport class Prompts {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `GET /v1/prompts?status=&limit=&tag=&priority_min=&q=&templates=&sort=&order=` — default `open`, templates\n * excluded; `due` = open and `not_before` empty or passed; several tags = AND.\n */\n list(query: PromptListQuery = {}, opts: CallOpts = {}): Promise<PromptList> {\n return this.http.json<PromptList>('/v1/prompts', {\n query: filterQuery(query),\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/prompts` — idempotent on the text (`created: false` for a duplicate); `goal_key` supersedes older open ones. */\n create(body: PromptCreateRequest, opts: CallOpts = {}): Promise<PromptCreated> {\n return this.http.json<PromptCreated>('/v1/prompts', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/prompts/{id}`. */\n get(id: string, opts: CallOpts = {}): Promise<Prompt> {\n return this.http.json<Prompt>(one(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/prompts/{id}` — edit, snooze (`not_before`), close (`status: 'done' | 'dismissed'`). */\n update(id: string, body: PromptPatch, opts: CallOpts = {}): Promise<Prompt> {\n return this.http.json<Prompt>(one(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/prompts/{id}` — `{ deleted: 0 }` when the id is missing or not yours. */\n delete(id: string, opts: CallOpts = {}): Promise<PromptDeleted> {\n return this.http.json<PromptDeleted>(one(id), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/prompts/{id}/launch` — new shared session + `send` control on a device; the prompt becomes `launched`. */\n launch(id: string, deviceId?: string, opts: CallOpts = {}): Promise<PromptLaunched> {\n return this.http.json<PromptLaunched>(one(id, '/launch'), {\n method: 'POST',\n body: deviceId ? { device_id: deviceId } : {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/prompts/{id}/match` — the prompt was sent in a chat → `sent` (or `answered`); never downgrades. */\n match(id: string, body: PromptMatchRequest, opts: CallOpts = {}): Promise<PromptMatched> {\n return this.http.json<PromptMatched>(one(id, '/match'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/prompts/{id}/verify` — LLM report over the transcript (sent, or the matched session's stored\n * events) and an optional diff; verdict `done` → `verified`. 502 when the model call fails.\n */\n verify(id: string, body: PromptVerifyRequest = {}, opts: CallOpts = {}): Promise<PromptVerified> {\n return this.http.json<PromptVerified>(one(id, '/verify'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/prompts/verify` — transcript-only verification of up to 20 prompts, sequentially. */\n verifyMany(body: PromptVerifyManyRequest, opts: CallOpts = {}): Promise<PromptVerifyManyResult> {\n return this.http.json<PromptVerifyManyResult>('/v1/prompts/verify', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/prompts/bulk` — one action over up to 200 of your prompts → `{ updated }`. */\n bulk(body: PromptBulkRequest, opts: CallOpts = {}): Promise<PromptBulkResult> {\n return this.http.json<PromptBulkResult>('/v1/prompts/bulk', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/prompts/{id}/events` — history, newest first (max 200). */\n events(id: string, opts: CallOpts = {}): Promise<PromptEventList> {\n return this.http.json<PromptEventList>(one(id, '/events'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/prompts/{id}/instantiate` — open copy of a template (201). */\n instantiate(id: string, opts: CallOpts = {}): Promise<Prompt> {\n return this.http.json<Prompt>(one(id, '/instantiate'), {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/prompts/export?format=csv|md` — list filters apply (status defaults to `all`); returns the document text. */\n async exportPrompts(query: PromptExportQuery = {}, opts: CallOpts = {}): Promise<string> {\n const res = await this.http.request('/v1/prompts/export', {\n query: { ...filterQuery(query), format: query.format ?? 'csv' },\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /** `GET /v1/prompts/stream` — live `prompt` events (keepalive comments are skipped). Closed by the server after 6 h. */\n async *stream(opts: CallOpts = {}): AsyncGenerator<PromptStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/prompts/stream', { ext: opts.ext, signal: opts.signal });\n for await (const frame of frames) {\n if (frame.event !== 'prompt') continue;\n const data = frameJson<PromptStreamEvent>(frame);\n if (data) yield data;\n }\n }\n}\n","/** `/v1/schedules/*`, `/v1/schedule-runs/*`, `/v1/scheduler/*` — the codai Scheduler (ADR 0006). */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Schedule = Schema<'Schedule'>;\nexport type ScheduleInput = Mutable<Schema<'ScheduleInput'>>;\nexport type ScheduleRun = Schema<'ScheduleRun'>;\nexport type SchedulerHost = Schema<'SchedulerHost'>;\nexport type SchedulePreviewRequest = Mutable<Body<'previewSchedule'>>;\nexport type SchedulePreview = Reply<'previewSchedule'>;\nexport type SchedulerHostPatch = Mutable<Body<'updateSchedulerHost'>>;\nexport type ScheduleRunResult = Mutable<Body<'reportScheduleRunResult'>>;\nexport type ScheduleClaim = Reply<'claimScheduleRun'>;\nexport type HeartbeatMonitor = Schema<'HeartbeatMonitor'>;\nexport type HeartbeatCreateRequest = Mutable<Body<'createHeartbeat'>>;\nexport type HeartbeatPatch = Mutable<Body<'updateHeartbeat'>>;\nexport type ScheduleAuditEntry = Schema<'ScheduleAuditEntry'>;\n\n/** One `event: schedule` frame of `GET /v1/schedules/stream`. */\nexport interface ScheduleStreamEvent {\n op: 'schedule' | 'run';\n id: string;\n schedule_id?: string;\n state?: string;\n device_id?: string | null;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/schedules/${encodeURIComponent(id)}${suffix}`;\nconst run = (id: string, suffix: string) => `/v1/schedule-runs/${encodeURIComponent(id)}${suffix}`;\n\n/** Host-side executor protocol: claim → heartbeat → result. Needs a device header (`device` client option). */\nexport class ScheduleExecutor {\n constructor(private readonly http: HttpClient) {}\n\n /** `POST /v1/scheduler/claim` — the next run this device may execute, or `null` (204). Lease 60 s. */\n async claim(opts: CallOpts = {}): Promise<ScheduleClaim | null> {\n const res = await this.http.request('/v1/scheduler/claim', {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n if (res.status === 204) return null;\n return (await res.json()) as ScheduleClaim;\n }\n\n /** `POST /v1/schedule-runs/{id}/heartbeat` — extend the lease, append log. Throws 409 when the lease was lost. */\n async heartbeat(\n runId: string,\n body: { attempt: number; log?: string },\n opts: CallOpts = {},\n ): Promise<void> {\n await this.http.request(run(runId, '/heartbeat'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/schedule-runs/{id}/result` — finish the run (retries / chains are decided server-side). */\n result(runId: string, body: ScheduleRunResult, opts: CallOpts = {}): Promise<ScheduleRun> {\n return this.http.json<ScheduleRun>(run(runId, '/result'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/schedules/{id}/approve-command` — this host approves the exact shell command hash it showed the user. */\n approveCommand(\n scheduleId: string,\n commandHash: string,\n opts: CallOpts = {},\n ): Promise<Reply<'approveScheduleCommand'>> {\n return this.http.json(one(scheduleId, '/approve-command'), {\n method: 'POST',\n body: { command_hash: commandHash },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** Scheduler hosts (your devices as executors). */\nexport class SchedulerHosts {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/scheduler/hosts`. */\n async list(opts: CallOpts = {}): Promise<SchedulerHost[]> {\n const r = await this.http.json<Reply<'listSchedulerHosts'>>('/v1/scheduler/hosts', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.hosts];\n }\n\n /** `PATCH /v1/scheduler/hosts/{id}` — name, tags, kind, os, arch. */\n update(\n id: string,\n body: SchedulerHostPatch,\n opts: CallOpts = {},\n ): Promise<Reply<'updateSchedulerHost'>> {\n return this.http.json(`/v1/scheduler/hosts/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** Heartbeat monitors: dead-man switches for jobs codai does not run (`/ping/<token>`). */\nexport class Heartbeats {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/heartbeats`. */\n async list(opts: CallOpts = {}): Promise<HeartbeatMonitor[]> {\n const r = await this.http.json<Reply<'listHeartbeats'>>('/v1/heartbeats', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.heartbeats];\n }\n\n /** `POST /v1/heartbeats` — the response carries `ping_url` once. */\n create(body: HeartbeatCreateRequest, opts: CallOpts = {}): Promise<HeartbeatMonitor> {\n return this.http.json<HeartbeatMonitor>('/v1/heartbeats', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [201],\n });\n }\n\n /** `PATCH /v1/heartbeats/{id}` — name, period_s, grace_s, paused. */\n update(id: string, body: HeartbeatPatch, opts: CallOpts = {}): Promise<HeartbeatMonitor> {\n return this.http.json<HeartbeatMonitor>(`/v1/heartbeats/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/heartbeats/{id}`. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(`/v1/heartbeats/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Schedules {\n readonly hosts: SchedulerHosts;\n readonly executor: ScheduleExecutor;\n\n constructor(private readonly http: HttpClient) {\n this.hosts = new SchedulerHosts(http);\n this.executor = new ScheduleExecutor(http);\n }\n\n /** `GET /v1/schedules`. */\n async list(opts: CallOpts = {}): Promise<Schedule[]> {\n const r = await this.http.json<Reply<'listSchedules'>>('/v1/schedules', {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.schedules];\n }\n\n /** `POST /v1/schedules`. */\n create(body: ScheduleInput, opts: CallOpts = {}): Promise<Schedule> {\n return this.http.json<Schedule>('/v1/schedules', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [201],\n });\n }\n\n /** `POST /v1/schedules/preview` — cron or plain words (RO/EN) → trigger + next runs + DST warning. */\n preview(body: SchedulePreviewRequest, opts: CallOpts = {}): Promise<SchedulePreview> {\n return this.http.json<SchedulePreview>('/v1/schedules/preview', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/schedules/{id}`. */\n get(id: string, opts: CallOpts = {}): Promise<Schedule> {\n return this.http.json<Schedule>(one(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/schedules/{id}` — partial; a changed shell command clears host approvals. */\n update(id: string, body: Partial<ScheduleInput>, opts: CallOpts = {}): Promise<Schedule> {\n return this.http.json<Schedule>(one(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/schedules/{id}`. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/schedules/{id}/run` — run now (policy still applies). */\n runNow(id: string, opts: CallOpts = {}): Promise<Reply<'runSchedule', 202>> {\n return this.http.json(one(id, '/run'), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [202],\n noRetry: true,\n });\n }\n\n /** `GET /v1/schedules/{id}/runs`. */\n async runs(id: string, opts: CallOpts = {}): Promise<ScheduleRun[]> {\n const r = await this.http.json<Reply<'listScheduleRuns'>>(one(id, '/runs'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.runs];\n }\n\n /** `GET /v1/schedule-runs?limit=` — recent runs of every schedule. */\n async recentRuns(limit = 50, opts: CallOpts = {}): Promise<ScheduleRun[]> {\n const r = await this.http.json<Reply<'listRecentScheduleRuns'>>('/v1/schedule-runs', {\n query: { limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.runs];\n }\n\n /** `POST /v1/schedule-runs/{id}/decision` — approve or skip a run waiting for you. */\n decide(runId: string, approve: boolean, opts: CallOpts = {}): Promise<ScheduleRun> {\n return this.http.json<ScheduleRun>(run(runId, '/decision'), {\n method: 'POST',\n body: { approve },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/schedules/pause` — vacation mode until `until` (or until resumed). */\n pause(\n body: { until?: string | null; resume_policy?: 'skip' | 'backfill' } = {},\n opts: CallOpts = {},\n ): Promise<Reply<'pauseSchedules'>> {\n return this.http.json('/v1/schedules/pause', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/schedules/resume` — `backfill: true` runs each missed schedule once. */\n resume(\n body: { backfill?: boolean } = {},\n opts: CallOpts = {},\n ): Promise<Reply<'resumeSchedules'>> {\n return this.http.json('/v1/schedules/resume', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/schedules/audit` — append-only scheduler history, newest first (optionally one schedule). */\n async audit(\n params: { schedule_id?: string; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<ScheduleAuditEntry[]> {\n const r = await this.http.json<Reply<'listScheduleAudit'>>('/v1/schedules/audit', {\n query: { schedule_id: params.schedule_id, limit: params.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.audit];\n }\n\n /** `GET /v1/schedules/templates`. */\n templates(opts: CallOpts = {}): Promise<Reply<'listScheduleTemplates'>> {\n return this.http.json('/v1/schedules/templates', { ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/schedules/templates` — canonical prompt + draft create body (no write). */\n renderTemplate(\n template: string,\n params: Record<string, unknown> = {},\n opts: CallOpts = {},\n ): Promise<Reply<'renderScheduleTemplate'>> {\n return this.http.json('/v1/schedules/templates', {\n method: 'POST',\n body: { template, params },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/schedules/stream` — live `schedule` events (keepalives skipped). */\n async *stream(opts: CallOpts = {}): AsyncGenerator<ScheduleStreamEvent, void, undefined> {\n for await (const frame of this.http.sse('/v1/schedules/stream', {\n ext: opts.ext,\n signal: opts.signal,\n })) {\n if (frame.event !== 'schedule') continue;\n const data = frameJson<ScheduleStreamEvent>(frame);\n if (data) yield data;\n }\n }\n}\n","/** `/v1/lists/*`, `/v1/share` — lists and the share-sheet entry point. */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type List = Schema<'List'>;\nexport type ListItem = Schema<'ListItem'>;\nexport type ListCreateInput = Mutable<Schema<'ListCreateInput'>>;\nexport type ListPatchInput = Mutable<Schema<'ListPatchInput'>>;\nexport type ListItemInput = Mutable<Schema<'ListItemInput'>>;\nexport type ListItemPatchInput = Mutable<Schema<'ListItemPatchInput'>>;\nexport type ListItemCreated = Schema<'ListItemCreated'>;\nexport type ListOk = Schema<'ListOk'>;\nexport type ShareRequest = Mutable<Body<'shareToList'>>;\nexport type ShareResponse = Schema<'ShareResponse'>;\n\n/** One `event: list` frame of `GET /v1/lists/stream`. */\nexport interface ListStreamEvent {\n op: 'lists' | 'item' | 'item_delete';\n listId?: string;\n itemId?: string;\n}\n\n/** An item image (`GET /v1/lists/items/{itemId}/image`). */\nexport interface ListItemImage {\n bytes: Uint8Array;\n contentType: string;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/lists/${encodeURIComponent(id)}${suffix}`;\nconst item = (id: string, suffix = '') => `/v1/lists/items/${encodeURIComponent(id)}${suffix}`;\n\nexport class Lists {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/lists` — share-sheet order; presets are created on the first call. */\n async list(params: { archived?: boolean } = {}, opts: CallOpts = {}): Promise<List[]> {\n const r = await this.http.json<Reply<'listLists'>>('/v1/lists', {\n query: { archived: params.archived ? '1' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.lists];\n }\n\n /** `POST /v1/lists` — a custom list. */\n async create(body: ListCreateInput, opts: CallOpts = {}): Promise<List> {\n const r = await this.http.json<Reply<'createList', 201>>('/v1/lists', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [201],\n });\n return r.list;\n }\n\n /** `PATCH /v1/lists/order` — the order of your lists (and of the share-sheet targets). */\n reorder(ids: string[], opts: CallOpts = {}): Promise<ListOk> {\n return this.http.json<ListOk>('/v1/lists/order', {\n method: 'PATCH',\n body: { ids },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/lists/stream` — live `list` events (keepalives skipped). */\n async *stream(opts: CallOpts = {}): AsyncGenerator<ListStreamEvent, void, undefined> {\n for await (const frame of this.http.sse('/v1/lists/stream', {\n ext: opts.ext,\n signal: opts.signal,\n })) {\n if (frame.event !== 'list') continue;\n const data = frameJson<ListStreamEvent>(frame);\n if (data) yield data;\n }\n }\n\n /** `PATCH /v1/lists/{id}` — name, icon, color, share-sheet visibility, price watch, archived. */\n async update(id: string, patch: ListPatchInput, opts: CallOpts = {}): Promise<List> {\n const r = await this.http.json<Reply<'updateList'>>(one(id), {\n method: 'PATCH',\n body: patch,\n ext: opts.ext,\n signal: opts.signal,\n });\n return r.list;\n }\n\n /** `DELETE /v1/lists/{id}` — custom lists only (presets → 409 `preset_list`). */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /** `GET /v1/lists/{id}/items` — pinned first, then newest; done items only with `done: true`. */\n async items(\n id: string,\n params: { done?: boolean; limit?: number } = {},\n opts: CallOpts = {},\n ): Promise<ListItem[]> {\n const r = await this.http.json<Reply<'listListItems'>>(one(id, '/items'), {\n query: { done: params.done ? '1' : undefined, limit: params.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n return [...r.items];\n }\n\n /** `POST /v1/lists/{id}/items` — 201 created, or 200 with the existing item (`created: false`). */\n add(id: string, body: ListItemInput, opts: CallOpts = {}): Promise<ListItemCreated> {\n return this.http.json<ListItemCreated>(one(id, '/items'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [200, 201],\n });\n }\n\n /** `PATCH /v1/lists/items/{itemId}` — title, body, done, pinned, reminder; `list_id` moves it. */\n async updateItem(\n itemId: string,\n patch: ListItemPatchInput,\n opts: CallOpts = {},\n ): Promise<ListItem> {\n const r = await this.http.json<Reply<'updateListItem'>>(item(itemId), {\n method: 'PATCH',\n body: patch,\n ext: opts.ext,\n signal: opts.signal,\n });\n return r.item;\n }\n\n /** `DELETE /v1/lists/items/{itemId}` — also deletes its uploaded media. */\n async deleteItem(itemId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(item(itemId), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/lists/items/{itemId}/image` — the uploaded image or the unfurled preview image. */\n async image(itemId: string, opts: CallOpts = {}): Promise<ListItemImage> {\n const res = await this.http.request(item(itemId, '/image'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n contentType: res.headers.get('content-type') ?? 'application/octet-stream',\n };\n }\n\n /** `GET /v1/lists/{id}/export.md` — the whole list as GitHub-flavoured Markdown. */\n async exportMarkdown(id: string, opts: CallOpts = {}): Promise<string> {\n const res = await this.http.request(one(id, '/export.md'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return res.text();\n }\n\n /** `POST /v1/share` — share-sheet entry point (`list_id`, `preset`, or auto → Inbox + suggestion). */\n share(body: ShareRequest, opts: CallOpts = {}): Promise<ShareResponse> {\n return this.http.json<ShareResponse>('/v1/share', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [200, 201],\n });\n }\n}\n","/** `/v1/memory` — your persistent memory (same store as the MCP memory tools). */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type MemoryItem = Schema<'MemoryItem'>;\nexport type MemoryHit = Schema<'MemoryHit'>;\nexport type MemoryTier = MemoryItem['tier'];\nexport type MemoryList = Reply<'listMemories'>;\nexport type MemorySearchResult = Reply<'searchMemories'>;\nexport type MemoryListQuery = Mutable<QueryOf<'listMemories'>>;\nexport type MemorySearchQuery = Mutable<QueryOf<'searchMemories'>>;\nexport type MemoryCreateInput = Mutable<Body<'createMemory'>>;\nexport type MemoryCreated = Reply<'createMemory', 201>;\nexport type MemoryDeleted = Reply<'deleteMemory'>;\nexport type MemoryDeletedAll = Reply<'deleteAllMemories'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Memory {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/memory` — newest first; `limit` 1–100 (20), optional `tier`. Not metered. */\n list(query: MemoryListQuery = {}, opts: CallOpts = {}): Promise<MemoryList> {\n return this.http.json<MemoryList>('/v1/memory', {\n query: { tier: query.tier, limit: query.limit, offset: query.offset },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/memory/search` — semantic recall, most relevant first; `limit` 1–10 (5). One embedding. */\n search(query: MemorySearchQuery, opts: CallOpts = {}): Promise<MemorySearchResult> {\n return this.http.json<MemorySearchResult>('/v1/memory/search', {\n query: { q: query.q, limit: query.limit },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/memory` — store one semantic memory (`content` ≤ 4000 chars, `importance` 0–1, default 0.6). */\n create(input: MemoryCreateInput, opts: CallOpts = {}): Promise<MemoryCreated> {\n return this.http.json<MemoryCreated>('/v1/memory', {\n method: 'POST',\n body: input,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/memory/{id}` — 404 when the id is unknown or not yours. */\n delete(id: string, opts: CallOpts = {}): Promise<MemoryDeleted> {\n return this.http.json<MemoryDeleted>(`/v1/memory/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `DELETE /v1/memory?confirm=all` — erase EVERY memory of your account (all tiers). Irreversible; returns the\n * counts per tier and the total. Allowed on every plan.\n */\n deleteAll(opts: CallOpts = {}): Promise<MemoryDeletedAll> {\n return this.http.json<MemoryDeletedAll>('/v1/memory', {\n method: 'DELETE',\n query: { confirm: 'all' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/sandboxes` — agent sandboxes: isolated gVisor containers with a persistent `/workspace`, no network\n * by default, artifacts from `/workspace/out` as scanned, signed links. Backend `v2` (default) = long-lived\n * GKE pod with pause/resume, fork, a persistent kernel and preview URLs; `v1` = Cloud Run, on request.\n */\nimport { type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type Sandbox = Schema<'Sandbox'>;\nexport type SandboxEgress = Mutable<Schema<'SandboxEgress'>>;\nexport type SandboxCreateInput = Mutable<Schema<'SandboxCreate'>>;\nexport type SandboxExecInput = Mutable<Schema<'SandboxExecRequest'>>;\nexport type SandboxRunInput = Mutable<Schema<'SandboxRunRequest'>>;\nexport type SandboxExecResult = Schema<'SandboxExecResult'>;\nexport type SandboxExecEvent = Schema<'SandboxExecEvent'>;\nexport type SandboxArtifact = Schema<'SandboxArtifact'>;\nexport type SandboxReceipt = Schema<'SandboxReceipt'>;\nexport type SandboxInput = Mutable<Schema<'SandboxInput'>>;\nexport type SandboxList = Reply<'listSandboxes'>;\nexport type SandboxArtifactList = Reply<'listSandboxArtifacts'>;\nexport type SandboxFileList = Reply<'listSandboxFiles'>;\nexport type SandboxFileWritten = Reply<'putSandboxFile'>;\nexport type SandboxSnapshot = Reply<'snapshotSandbox'>;\nexport type SandboxStatus = Sandbox['status'];\nexport type SandboxSnapshotInput = Mutable<NonNullable<Body<'snapshotSandbox'>>>;\nexport type SandboxBackend = NonNullable<SandboxCreateInput['backend']>;\nexport type SandboxTemplate = NonNullable<SandboxCreateInput['template']>;\nexport type SandboxRunCodeResult = Schema<'SandboxRunCodeResult'>;\nexport type SandboxResumed = Reply<'resumeSandbox'>;\nexport type SandboxForkResult = Reply<'forkSandbox'>;\nexport type SandboxPreview = Reply<'previewSandbox'>;\n\n/** Input of {@link Sandboxes.runCode}. */\nexport interface SandboxRunCodeInput {\n code: string;\n /** Seconds before the kernel is restarted (1–900, server default 60). */\n timeoutSeconds?: number;\n}\n\n/** Input of {@link Sandboxes.fork}. */\nexport interface SandboxForkInput {\n /** Children to start (1–5). */\n count: number;\n /** Lifetime of each child; default what is left of the parent. */\n ttlSeconds?: number;\n}\n\n/** Input of {@link Sandboxes.preview}. */\nexport interface SandboxPreviewInput {\n /** Port inside the sandbox (1024–65535, not 8080). */\n port: number;\n /** URL validity in seconds (60–3600, server default 900). */\n ttlSeconds?: number;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\ntype IdemOpts = CallOpts & { idempotencyKey?: string };\n\n/** A downloaded workspace file: raw bytes plus the server's SHA-256. */\nexport interface SandboxFile {\n bytes: Uint8Array;\n sha256: string | null;\n contentType: string | null;\n}\n\nconst base = (id: string) => `/v1/sandboxes/${encodeURIComponent(id)}`;\n/** Encode each segment of a workspace path, keeping the slashes. */\nconst filePath = (p: string) =>\n p\n .replace(/^\\/+/, '')\n .split('/')\n .map((s) => encodeURIComponent(s))\n .join('/');\nconst idem = (key?: string) => (key ? { 'Idempotency-Key': key } : undefined);\n\nexport class SandboxFiles {\n constructor(private readonly http: HttpClient) {}\n\n /** `PUT /v1/sandboxes/{id}/files/{path}` — write raw bytes (≤ 100 MB) to `/workspace/<path>`. */\n put(\n id: string,\n path: string,\n content: string | Uint8Array | ArrayBuffer | Blob,\n opts: CallOpts = {},\n ): Promise<SandboxFileWritten> {\n const body = (typeof content === 'string'\n ? new TextEncoder().encode(content)\n : content) as unknown as BodyInit;\n return this.http.json<SandboxFileWritten>(`${base(id)}/files/${filePath(path)}`, {\n method: 'PUT',\n rawBody: body,\n headers: { 'Content-Type': 'application/octet-stream' },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/sandboxes/{id}/files/{path}` — raw bytes of `/workspace/<path>` (`sha256` from `x-sha256`). */\n async get(id: string, path: string, opts: CallOpts = {}): Promise<SandboxFile> {\n const res = await this.http.request(`${base(id)}/files/${filePath(path)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n return {\n bytes: new Uint8Array(await res.arrayBuffer()),\n sha256: res.headers.get('x-sha256'),\n contentType: res.headers.get('content-type'),\n };\n }\n\n /** `GET /v1/sandboxes/{id}/files?path=` — entries under a directory (default the workspace root). */\n list(id: string, path?: string, opts: CallOpts = {}): Promise<SandboxFileList> {\n return this.http.json<SandboxFileList>(`${base(id)}/files`, {\n query: { path },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Sandboxes {\n readonly files: SandboxFiles;\n\n constructor(private readonly http: HttpClient) {\n this.files = new SandboxFiles(http);\n }\n\n /**\n * `POST /v1/sandboxes` — start a sandbox (`ttl_seconds` default 3600, max 86400 on v1 / 604800 on v2;\n * `egress` none by default, or a `pypi`/`npm` preset / allowlist on both backends).\n * `backend` defaults to `'v2'`: a long-lived pod with memory snapshots, Node 24 + npm, `template`\n * `codai-base` | `brivio-acte` | `desktop`; its reply may carry `restored`. When `backend` is omitted and v2\n * is unavailable for the key the gateway falls back to `'v1'` (check `backend` on the reply).\n * Errors: 429 `sandbox_concurrency_limit` (3 per key, 5 running v2 per user), 503 `sandbox_capacity` (retry).\n */\n create(input: SandboxCreateInput = {}, opts: CallOpts = {}): Promise<Sandbox> {\n return this.http.json<Sandbox>('/v1/sandboxes', {\n method: 'POST',\n body: input,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/sandboxes` — your sandboxes, newest first, optionally one `status`. */\n list(query: { status?: SandboxStatus } = {}, opts: CallOpts = {}): Promise<SandboxList> {\n return this.http.json<SandboxList>('/v1/sandboxes', {\n query: { status: query.status },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/sandboxes/{id}` */\n retrieve(id: string, opts: CallOpts = {}): Promise<Sandbox> {\n return this.http.json<Sandbox>(base(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/exec` — run one command and wait for it (≤ 900 s). Use\n * {@link execStream} to receive stdout / stderr as they are produced.\n */\n exec(id: string, input: SandboxExecInput, opts: IdemOpts = {}): Promise<SandboxExecResult> {\n return this.http.json<SandboxExecResult>(`${base(id)}/exec`, {\n method: 'POST',\n body: input,\n headers: idem(opts.idempotencyKey),\n timeoutMs: execTimeoutMs(input.timeout_seconds),\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/exec` with `Accept: text/event-stream` — yields `start`, `stdout`,\n * `stderr`, `truncated` and finally `exit` (or `error`) events.\n */\n async *execStream(\n id: string,\n input: SandboxExecInput,\n opts: IdemOpts = {},\n ): AsyncGenerator<SandboxExecEvent, void, undefined> {\n const frames = this.http.sse(`${base(id)}/exec`, {\n method: 'POST',\n body: input,\n headers: { Accept: 'text/event-stream', ...idem(opts.idempotencyKey) },\n ext: opts.ext,\n signal: opts.signal,\n });\n for await (const frame of frames) {\n const data = frameJson<SandboxExecEvent>(frame);\n if (!data || typeof data !== 'object' || !('type' in data)) continue;\n yield data;\n if (data.type === 'exit' || data.type === 'error') return;\n }\n }\n\n /** `GET /v1/sandboxes/{id}/artifacts` — collect `/workspace/out` (scanned, signed 1 h links). */\n artifacts(id: string, opts: CallOpts = {}): Promise<SandboxArtifactList> {\n return this.http.json<SandboxArtifactList>(`${base(id)}/artifacts`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/snapshot` (v1 only; v2 answers 409 `not_supported_on_v2`) — store a compressed copy of the workspace. */\n snapshot(\n id: string,\n input: SandboxSnapshotInput = {},\n opts: CallOpts = {},\n ): Promise<SandboxSnapshot> {\n return this.http.json<SandboxSnapshot>(`${base(id)}/snapshot`, {\n method: 'POST',\n body: input,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/run_code` (v2) — run Python in the persistent kernel; globals survive between\n * calls, pause/resume and forks. The last expression comes back as `result`.\n */\n runCode(id: string, input: SandboxRunCodeInput, opts: CallOpts = {}): Promise<SandboxRunCodeResult> {\n return this.http.json<SandboxRunCodeResult>(`${base(id)}/run_code`, {\n method: 'POST',\n body: {\n code: input.code,\n ...(input.timeoutSeconds !== undefined ? { timeout_seconds: input.timeoutSeconds } : {}),\n },\n timeoutMs: execTimeoutMs(input.timeoutSeconds),\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/kernel/reset` (v2) — restart the kernel; globals are lost, files kept. */\n async resetKernel(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.json<{ ok: boolean }>(`${base(id)}/kernel/reset`, {\n method: 'POST',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/sandboxes/{id}/pause` (v2) — memory snapshot, then stop the pod (status `paused`).\n * At most 10 paused v2 sandboxes per user (429 `sandbox_paused_limit`).\n */\n pause(id: string, opts: CallOpts = {}): Promise<Sandbox> {\n return this.http.json<Sandbox>(`${base(id)}/pause`, {\n method: 'POST',\n timeoutMs: LIFECYCLE_TIMEOUT_MS,\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/resume` (v2) — restore a paused sandbox; `restored: false` = cold start. */\n resume(id: string, opts: CallOpts = {}): Promise<SandboxResumed> {\n return this.http.json<SandboxResumed>(`${base(id)}/resume`, {\n method: 'POST',\n timeoutMs: LIFECYCLE_TIMEOUT_MS,\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/fork` (v2) — start 1–5 copies of a running sandbox from a memory snapshot. */\n fork(id: string, input: SandboxForkInput, opts: CallOpts = {}): Promise<SandboxForkResult> {\n return this.http.json<SandboxForkResult>(`${base(id)}/fork`, {\n method: 'POST',\n body: {\n count: input.count,\n ...(input.ttlSeconds !== undefined ? { ttl_seconds: input.ttlSeconds } : {}),\n },\n timeoutMs: LIFECYCLE_TIMEOUT_MS,\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/sandboxes/{id}/preview` (v2) — signed HTTPS URL on `*.sbx.codai.ro` for a port (≤ 1 h). */\n preview(id: string, input: SandboxPreviewInput, opts: CallOpts = {}): Promise<SandboxPreview> {\n return this.http.json<SandboxPreview>(`${base(id)}/preview`, {\n method: 'POST',\n body: {\n port: input.port,\n ...(input.ttlSeconds !== undefined ? { ttl_seconds: input.ttlSeconds } : {}),\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/sandboxes/{id}` — destroy the sandbox and its workspace (204). */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(base(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * `POST /v1/sandboxes/run` — one shot: create, write `inputs` under `/workspace/in`, run,\n * collect artifacts, destroy. Pass `idempotencyKey` to make retries safe.\n */\n run(input: SandboxRunInput, opts: IdemOpts = {}): Promise<SandboxExecResult> {\n return this.http.json<SandboxExecResult>('/v1/sandboxes/run', {\n method: 'POST',\n body: input,\n headers: idem(opts.idempotencyKey),\n timeoutMs: execTimeoutMs(input.timeout_seconds),\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\n/** Pause / resume / fork wait for a snapshot or a pod start (server caps: 180 s snapshot, 240 s start). */\nconst LIFECYCLE_TIMEOUT_MS = 8 * 60 * 1000;\n\n/** Client timeout for a blocking exec: the server limit plus a margin for restore and upload. */\nfunction execTimeoutMs(timeoutSeconds: number | undefined): number {\n return ((timeoutSeconds ?? 120) + 60) * 1000;\n}\n","/**\n * `/v1/transcripts/*` + `/v1/transcript-folders` + `/v1/transcript-vocabulary` + tus `/v1/uploads` — voice\n * recordings → diarized RO/EN transcripts → insights (summary, key points, actions, suggested agent prompts).\n * Feature-flagged per account (404 until enabled). Bodies are snake_case.\n */\nimport { CodaiError, type CodaiRequestExtensions, frameJson, type HttpClient } from '../http';\nimport { type Body, type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type Transcript = Schema<'Transcript'>;\nexport type TranscriptDetail = Schema<'TranscriptDetail'>;\nexport type TranscriptStatus = Schema<'TranscriptStatus'>;\nexport type TranscriptFolder = Schema<'TranscriptFolder'>;\nexport type TranscriptList = Reply<'listTranscripts'>;\nexport type TranscriptListQuery = Mutable<QueryOf<'listTranscripts'>>;\nexport type TranscriptCreateRequest = Mutable<Body<'createTranscript'>>;\nexport type TranscriptPatch = Mutable<Body<'updateTranscript'>>;\nexport type TranscriptFinalizeRequest = Mutable<Body<'finalizeTranscript'>>;\nexport type TranscriptUsage = Reply<'getTranscriptUsage'>;\nexport type TranscriptSearchQuery = Mutable<QueryOf<'searchTranscripts'>>;\nexport type TranscriptSearchResult = Reply<'searchTranscripts'>;\nexport type TranscriptAskRequest = Mutable<Body<'askTranscripts'>>;\nexport type TranscriptAskResult = Reply<'askTranscripts'>;\nexport type TranscriptAudio = Reply<'getTranscriptAudio'>;\nexport type TranscriptBookmarkRequest = Mutable<Body<'addTranscriptBookmark'>>;\nexport type TranscriptSpeakerPatch = Mutable<Body<'updateTranscriptSpeaker'>>;\nexport type TranscriptExportFormat = 'md' | 'txt' | 'srt' | 'vtt' | 'json' | 'pdf' | 'docx';\nexport type TranscriptBinaryExportFormat = 'pdf' | 'docx';\nexport type TranscriptShareCreateRequest = Mutable<Schema<'TranscriptShareCreateRequest'>>;\nexport type TranscriptShareCreated = Schema<'TranscriptShareCreated'>;\nexport type TranscriptShare = Schema<'TranscriptShare'>;\nexport type PublicTranscript = Schema<'PublicTranscript'>;\n\n/** A text export (`md` / `txt` / `srt` / `vtt` / `json`). */\nexport interface TranscriptTextExport {\n text: string;\n filename: string | null;\n contentType: string | null;\n}\n\n/** A binary export (`pdf` / `docx`): raw bytes, save them as-is. */\nexport interface TranscriptBinaryExport {\n bytes: Uint8Array;\n filename: string | null;\n contentType: string | null;\n}\n\n/** One `event: transcript` frame of `GET /v1/transcripts/stream`. */\nexport interface TranscriptStreamEvent {\n op: 'upsert' | 'delete' | 'progress' | 'live';\n id: string;\n status?: TranscriptStatus;\n /** 0..1 on `progress`. */\n progress?: number;\n title?: string;\n /** `live`: rolling caption from the recording device (committed tail + partial); never persisted. */\n finals?: string;\n partial?: string;\n /** `live`: 0..1 input level. */\n level?: number;\n /** `live`: phone | wear | desktop. */\n device?: string;\n elapsed_ms?: number;\n paused?: boolean;\n}\n\n/** Body of `POST /v1/transcripts/{id}/live` (the recording device's caption, ~1/s). */\nexport interface TranscriptLiveCaption {\n finals?: string;\n partial?: string;\n level?: number;\n device: 'phone' | 'wear' | 'desktop';\n elapsed_ms: number;\n paused?: boolean;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nconst one = (id: string, suffix = '') => `/v1/transcripts/${encodeURIComponent(id)}${suffix}`;\n\nconst TUS = { 'Tus-Resumable': '1.0.0' } as const;\nexport const TUS_CHUNK_BYTES = 8 * 1024 * 1024;\n\n/** base64 of a UTF-8 string, without Buffer (browser + node). */\nfunction b64(s: string): string {\n const bytes = new TextEncoder().encode(s);\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin);\n}\n\n/** Last path segment of a tus `Location` (absolute or relative). Exported for tests. */\nexport function uploadIdFromLocation(location: string): string {\n const path = location.replace(/[?#].*$/, '').replace(/\\/+$/, '');\n const id = decodeURIComponent(path.slice(path.lastIndexOf('/') + 1));\n if (!id) throw new CodaiError(`tus: no upload id in Location ${location}`, 0, null);\n return id;\n}\n\nexport interface UploadAudioOptions extends CallOpts {\n track?: 'mic' | 'system' | 'mixed';\n transcriptId?: string;\n durationMs?: number;\n chunkSize?: number;\n /** Resume a previous upload (its id) instead of creating one. */\n uploadId?: string;\n onProgress?: (sent: number, total: number) => void;\n}\n\nclass TranscriptFolders {\n constructor(private readonly http: HttpClient) {}\n /** `GET /v1/transcript-folders`. */\n list(opts: CallOpts = {}): Promise<Reply<'listTranscriptFolders'>> {\n return this.http.json('/v1/transcript-folders', { ext: opts.ext, signal: opts.signal });\n }\n /** `POST /v1/transcript-folders` — upsert on `name`. */\n create(\n body: Mutable<Body<'createTranscriptFolder'>>,\n opts: CallOpts = {},\n ): Promise<TranscriptFolder> {\n return this.http.json('/v1/transcript-folders', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n /** `PATCH /v1/transcript-folders/{id}`. */\n update(\n id: string,\n body: Mutable<Body<'updateTranscriptFolder'>>,\n opts: CallOpts = {},\n ): Promise<TranscriptFolder> {\n return this.http.json(`/v1/transcript-folders/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n /** `DELETE /v1/transcript-folders/{id}` — transcripts stay, `folder_id` cleared. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(`/v1/transcript-folders/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nclass TranscriptVocabulary {\n constructor(private readonly http: HttpClient) {}\n /** `GET /v1/transcript-vocabulary`. */\n get(opts: CallOpts = {}): Promise<Reply<'getTranscriptVocabulary'>> {\n return this.http.json('/v1/transcript-vocabulary', { ext: opts.ext, signal: opts.signal });\n }\n /** `PUT /v1/transcript-vocabulary` — replaces the whole list. */\n put(terms: string[], opts: CallOpts = {}): Promise<Reply<'putTranscriptVocabulary'>> {\n return this.http.json('/v1/transcript-vocabulary', {\n method: 'PUT',\n body: { terms },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nclass TranscriptShares {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/transcripts/{id}/shares` — read-only public link (`https://hub.codai.ro/t/<token>`). The token/url\n * are returned ONCE (only a hash is stored). Omit `expiresInDays` for a link that never expires.\n */\n create(\n id: string,\n body: TranscriptShareCreateRequest = {},\n opts: CallOpts = {},\n ): Promise<TranscriptShareCreated> {\n return this.http.json<TranscriptShareCreated>(one(id, '/shares'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/transcripts/{id}/shares` — active links; `url` is always null (token not recoverable). */\n async list(id: string, opts: CallOpts = {}): Promise<TranscriptShare[]> {\n const r = await this.http.json<{ data: TranscriptShare[] }>(one(id, '/shares'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n return r.data;\n }\n\n /** `DELETE /v1/transcripts/{id}/shares/{shareId}` — the public URL answers 404 from then on. */\n async revoke(id: string, shareId: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id, `/shares/${encodeURIComponent(shareId)}`), {\n method: 'DELETE',\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nclass Uploads {\n constructor(private readonly http: HttpClient) {}\n\n /** `OPTIONS /v1/uploads` — tus capabilities (headers). */\n async capabilities(\n opts: CallOpts = {},\n ): Promise<{ version: string | null; extensions: string[]; maxSize: number | null }> {\n const res = await this.http.request('/v1/uploads', {\n method: 'OPTIONS',\n headers: TUS,\n ext: opts.ext,\n signal: opts.signal,\n });\n const max = res.headers.get('tus-max-size');\n return {\n version: res.headers.get('tus-version'),\n extensions: (res.headers.get('tus-extension') ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean),\n maxSize: max ? Number(max) : null,\n };\n }\n\n /** `POST /v1/uploads` — tus creation; returns the upload id. */\n async create(\n length: number | null,\n metadata: Record<string, string>,\n opts: CallOpts = {},\n ): Promise<string> {\n const md = Object.entries(metadata)\n .map(([k, v]) => `${k} ${b64(v)}`)\n .join(',');\n const res = await this.http.request('/v1/uploads', {\n method: 'POST',\n headers: {\n ...TUS,\n ...(length === null ? { 'Upload-Defer-Length': '1' } : { 'Upload-Length': String(length) }),\n ...(md ? { 'Upload-Metadata': md } : {}),\n },\n noRetry: true,\n ext: opts.ext,\n signal: opts.signal,\n });\n const loc = res.headers.get('location');\n if (!loc) throw new CodaiError('tus: create response has no Location header', res.status, null);\n return uploadIdFromLocation(loc);\n }\n\n /** tus HEAD `/v1/uploads/{id}` — bytes the server holds (resume point). */\n async offset(\n id: string,\n opts: CallOpts = {},\n ): Promise<{ offset: number; length: number | null }> {\n const res = await this.http.request(`/v1/uploads/${encodeURIComponent(id)}`, {\n method: 'HEAD',\n headers: TUS,\n ext: opts.ext,\n signal: opts.signal,\n });\n const len = res.headers.get('upload-length');\n return {\n offset: Number(res.headers.get('upload-offset') ?? 0),\n length: len ? Number(len) : null,\n };\n }\n\n /** tus PATCH `/v1/uploads/{id}` — append one chunk at `offset`; returns the new offset. */\n async append(\n id: string,\n offset: number,\n chunk: Uint8Array,\n opts: CallOpts & { length?: number } = {},\n ): Promise<number> {\n const res = await this.http.request(`/v1/uploads/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: {\n ...TUS,\n 'Upload-Offset': String(offset),\n 'Content-Type': 'application/offset+octet-stream',\n ...(opts.length !== undefined ? { 'Upload-Length': String(opts.length) } : {}),\n },\n rawBody: chunk as unknown as BodyInit,\n ext: opts.ext,\n signal: opts.signal,\n });\n const next = Number(res.headers.get('upload-offset') ?? -1);\n if (!(next > offset))\n throw new CodaiError(\n `tus: server offset ${next} did not advance past ${offset}`,\n res.status,\n null,\n );\n return next;\n }\n}\n\nexport class Transcripts {\n readonly folders: TranscriptFolders;\n readonly vocabulary: TranscriptVocabulary;\n readonly uploads: Uploads;\n readonly shares: TranscriptShares;\n\n constructor(private readonly http: HttpClient) {\n this.folders = new TranscriptFolders(http);\n this.vocabulary = new TranscriptVocabulary(http);\n this.uploads = new Uploads(http);\n this.shares = new TranscriptShares(http);\n }\n\n /** `GET /v1/transcripts` — pinned first, newest next; page with `next_cursor`. */\n list(query: TranscriptListQuery = {}, opts: CallOpts = {}): Promise<TranscriptList> {\n return this.http.json<TranscriptList>('/v1/transcripts', {\n query: query as Record<string, string | number | boolean | undefined>,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/transcripts` — status `recording`; idempotent on `client_id`. */\n create(body: TranscriptCreateRequest, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>('/v1/transcripts', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/{id}` — speakers, utterances (word timings), bookmarks, latest insights. */\n get(id: string, opts: CallOpts = {}): Promise<TranscriptDetail> {\n return this.http.json<TranscriptDetail>(one(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /** `PATCH /v1/transcripts/{id}` — setting `title` locks it. */\n update(id: string, body: TranscriptPatch, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `DELETE /v1/transcripts/{id}` — row + audio objects. */\n async delete(id: string, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id), { method: 'DELETE', ext: opts.ext, signal: opts.signal });\n }\n\n /** `POST /v1/transcripts/{id}/finalize` — attach tus uploads + bookmarks → `queued`. */\n finalize(id: string, body: TranscriptFinalizeRequest, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id, '/finalize'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n acceptStatus: [202],\n });\n }\n\n /** `POST /v1/transcripts/{id}/retranscribe`. */\n retranscribe(id: string, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id, '/retranscribe'), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/transcripts/{id}/reanalyze` — new insights version. */\n reanalyze(id: string, opts: CallOpts = {}): Promise<Transcript> {\n return this.http.json<Transcript>(one(id, '/reanalyze'), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /**\n * `POST /v1/transcripts/{id}/live` — publish the recording device's live caption to every viewer of the transcript\n * (`stream()` / hub live view). Only while `recording`; frames closer than 250 ms are dropped. Returns nothing (204).\n */\n async publishLive(id: string, body: TranscriptLiveCaption, opts: CallOpts = {}): Promise<void> {\n await this.http.request(one(id, '/live'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `POST /v1/transcripts/{id}/bookmarks`. */\n addBookmark(\n id: string,\n body: TranscriptBookmarkRequest,\n opts: CallOpts = {},\n ): Promise<Reply<'addTranscriptBookmark', 201>> {\n return this.http.json(one(id, '/bookmarks'), {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/transcripts/{id}/speakers/{label}` — name a speaker / mark yourself (`is_owner`). */\n renameSpeaker(\n id: string,\n label: string,\n body: TranscriptSpeakerPatch,\n opts: CallOpts = {},\n ): Promise<Reply<'updateTranscriptSpeaker'>> {\n return this.http.json(one(id, `/speakers/${encodeURIComponent(label)}`), {\n method: 'PATCH',\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/transcripts/{id}/utterances/{seq}` — correct one utterance. */\n editUtterance(\n id: string,\n seq: number,\n text: string,\n opts: CallOpts = {},\n ): Promise<Reply<'updateTranscriptUtterance'>> {\n return this.http.json(one(id, `/utterances/${seq}`), {\n method: 'PATCH',\n body: { text },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/{id}/audio` — signed playback URLs per track (empty after the 30-day retention). */\n audio(id: string, opts: CallOpts = {}): Promise<TranscriptAudio> {\n return this.http.json<TranscriptAudio>(one(id, '/audio'), {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/{id}/export?format=` — text for md/txt/srt/vtt/json, bytes for pdf/docx. */\n export(\n id: string,\n format: TranscriptBinaryExportFormat,\n opts?: CallOpts,\n ): Promise<TranscriptBinaryExport>;\n export(\n id: string,\n format?: Exclude<TranscriptExportFormat, TranscriptBinaryExportFormat>,\n opts?: CallOpts,\n ): Promise<TranscriptTextExport>;\n async export(\n id: string,\n format: TranscriptExportFormat = 'md',\n opts: CallOpts = {},\n ): Promise<TranscriptTextExport | TranscriptBinaryExport> {\n const res = await this.http.request(one(id, '/export'), {\n query: { format },\n ext: opts.ext,\n signal: opts.signal,\n });\n const cd = res.headers.get('content-disposition') ?? '';\n const m = /filename\\*=UTF-8''([^;]+)/i.exec(cd);\n const filename = m ? decodeURIComponent(m[1]!) : null;\n const contentType = res.headers.get('content-type');\n if (format === 'pdf' || format === 'docx')\n return { bytes: new Uint8Array(await res.arrayBuffer()), filename, contentType };\n return { text: await res.text(), filename, contentType };\n }\n\n /**\n * `GET /v1/public/transcripts/{token}` — the read-only view behind a share link (no API key needed; the\n * client's key is sent but ignored). 404 for unknown / expired / revoked links.\n */\n publicView(token: string, opts: CallOpts = {}): Promise<PublicTranscript> {\n return this.http.json<PublicTranscript>(`/v1/public/transcripts/${encodeURIComponent(token)}`, {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/transcripts/{id}/prompts/{index}/accept` — suggested agent prompt → pending prompt. */\n acceptPrompt(\n id: string,\n index: number,\n opts: CallOpts = {},\n ): Promise<Reply<'acceptTranscriptPrompt', 201>> {\n return this.http.json(one(id, `/prompts/${index}/accept`), {\n method: 'POST',\n body: {},\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/transcripts/usage` — this month's allowance. */\n usage(opts: CallOpts = {}): Promise<TranscriptUsage> {\n return this.http.json<TranscriptUsage>('/v1/transcripts/usage', {\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/transcripts/search` — full-text (+ semantic in `hybrid`). */\n search(query: TranscriptSearchQuery, opts: CallOpts = {}): Promise<TranscriptSearchResult> {\n return this.http.json<TranscriptSearchResult>('/v1/transcripts/search', {\n query: query as Record<string, string | number | undefined>,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/transcripts/ask` — answer across your recordings with `[n]` citations. */\n ask(body: TranscriptAskRequest, opts: CallOpts = {}): Promise<TranscriptAskResult> {\n return this.http.json<TranscriptAskResult>('/v1/transcripts/ask', {\n method: 'POST',\n body,\n ext: opts.ext,\n signal: opts.signal,\n noRetry: true,\n });\n }\n\n /** `GET /v1/transcripts/stream` — live `transcript` events (keepalives skipped). Server closes after 55 min. */\n async *stream(opts: CallOpts = {}): AsyncGenerator<TranscriptStreamEvent, void, undefined> {\n const frames = this.http.sse('/v1/transcripts/stream', { ext: opts.ext, signal: opts.signal });\n for await (const frame of frames) {\n if (frame.event !== 'transcript') continue;\n const data = frameJson<TranscriptStreamEvent>(frame);\n if (data) yield data;\n }\n }\n\n /**\n * Upload one audio track with tus 1.0 (resumable): creates the upload (or resumes `uploadId` from the server's\n * offset), PATCHes ≤ 8 MB chunks and returns the upload id to pass to `finalize`.\n */\n async uploadAudio(\n data: Uint8Array | ArrayBuffer | Blob,\n opts: UploadAudioOptions = {},\n ): Promise<string> {\n const bytes =\n data instanceof Uint8Array\n ? data\n : data instanceof ArrayBuffer\n ? new Uint8Array(data)\n : new Uint8Array(await data.arrayBuffer());\n const total = bytes.byteLength;\n const chunk = Math.max(1, Math.min(opts.chunkSize ?? TUS_CHUNK_BYTES, TUS_CHUNK_BYTES));\n let id = opts.uploadId;\n let offset = 0;\n if (id) offset = (await this.uploads.offset(id, opts)).offset;\n else {\n const md: Record<string, string> = { track: opts.track ?? 'mic' };\n if (opts.transcriptId) md.transcript = opts.transcriptId;\n if (opts.durationMs !== undefined) md.durationMs = String(opts.durationMs);\n id = await this.uploads.create(total, md, opts);\n }\n opts.onProgress?.(offset, total);\n while (offset < total) {\n offset = await this.uploads.append(\n id,\n offset,\n bytes.subarray(offset, Math.min(total, offset + chunk)),\n opts,\n );\n opts.onProgress?.(offset, total);\n }\n return id;\n }\n}\n","/** `POST /v1/tokens` — ephemeral scoped tokens for browsers / webviews. */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Reply } from './_shared';\n\n/** `live` = realtime + audio in one token (a live co-host's speech-to-text and text-to-speech). */\nexport type EphemeralScope = 'realtime' | 'audio' | 'embeddings' | 'live';\nexport type EphemeralTokenResponse = Reply<'createEphemeralToken'>;\n\nexport interface EphemeralToken {\n token: string;\n expiresAt: string;\n scope: EphemeralScope;\n raw: EphemeralTokenResponse;\n}\n\nexport class Tokens {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * Mint a short-lived token (60–3600 s, default 600) bound to one surface.\n * Only a real `codai_` key may mint.\n */\n async create(\n scope: EphemeralScope,\n ttlSeconds?: number,\n opts: { ext?: CodaiRequestExtensions; signal?: AbortSignal } = {},\n ): Promise<EphemeralToken> {\n const raw = await this.http.json<EphemeralTokenResponse>('/v1/tokens', {\n body: { scope, ...(ttlSeconds !== undefined ? { ttl_seconds: ttlSeconds } : {}) },\n ext: opts.ext,\n signal: opts.signal,\n });\n return { token: raw.token, expiresAt: raw.expires_at, scope: raw.scope, raw };\n }\n}\n","/**\n * `/v1/tools/*` — verified web search, server-side page fetch and GUI grounding.\n *\n * Same contract as every codai agent surface (packages/agent-core/spec/tools-web.json). Metered per call: $3 / 1k\n * fast searches, $8 / 1k deep, $0.50 / 1k fetches; first 1,000 calls per month free, free inside a codai agent turn.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply } from './_shared';\n\nexport type ToolSearchRequest = Mutable<Body<'toolsSearch'>>;\nexport type ToolSearchResponse = Reply<'toolsSearch'>;\nexport type ToolFetchRequest = Mutable<Body<'toolsFetch'>>;\nexport type ToolFetchResponse = Reply<'toolsFetch'>;\nexport type ToolGroundRequest = Mutable<Body<'toolsGround'>>;\nexport type ToolGroundResponse = Reply<'toolsGround'>;\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Tools {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/tools/search` — verified web search (never falls back to an unverified provider). Filters:\n * `include_domains` / `exclude_domains`, `freshness` or `published_after` / `published_before` (undated pages are\n * dropped), `content_chars` for a verified excerpt per result. Each result carries `published_at` (null when\n * unknown, never the crawl date) and `crawled_at`.\n */\n search(body: ToolSearchRequest, opts: CallOpts = {}): Promise<ToolSearchResponse> {\n return this.http.json<ToolSearchResponse>('/v1/tools/search', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `POST /v1/tools/fetch` — fetch + extract a public page (SSRF-guarded; `max_chars` default 8000, max 40 000). */\n fetch(body: ToolFetchRequest, opts: CallOpts = {}): Promise<ToolFetchResponse> {\n return this.http.json<ToolFetchResponse>('/v1/tools/fetch', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /**\n * `POST /v1/tools/ground` — find a described UI element on an inline screenshot (`data:image/...;base64`).\n * Returns `x_norm`/`y_norm` in 0..1 (plus `x`/`y` pixels when `width`/`height` are sent); `found: false` = not on it.\n */\n ground(body: ToolGroundRequest, opts: CallOpts = {}): Promise<ToolGroundResponse> {\n return this.http.json<ToolGroundResponse>('/v1/tools/ground', {\n body,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/research` — asynchronous deep research.\n *\n * `POST /v1/research` — start a job (`create`); 200 when it finished within `wait_s`, else 202 `{id, status}`\n * `GET /v1/research/{id}` — the job (`retrieve`); `report` / `answer` + `sources` once `done`, `error` if `failed`\n *\n * `wait(id)` polls `retrieve` until the job is `done` or `failed`; `run(body)` = `create` + `wait`.\n * Price: $0.20 per job plus its model tokens (free inside the monthly allowance / a codai agent turn). Polling is free.\n */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Body, type Mutable, type Schema } from './_shared';\n\nexport type ResearchRequest = Mutable<Body<'createResearch'>>;\nexport type ResearchJob = Schema<'ResearchJob'>;\nexport type ResearchSource = Schema<'ResearchSource'>;\nexport type ResearchStatus = ResearchJob['status'];\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport interface ResearchCreateOptions extends CallOpts {\n /** `Idempotency-Key`: the same key returns the job created earlier instead of starting another one. */\n idempotencyKey?: string;\n}\n\nexport interface ResearchWaitOptions extends CallOpts {\n /** Delay between polls (default 3000 ms). */\n intervalMs?: number;\n /** Give up after this long (default 360 000 ms = 6 min; the longest job budget is 300 s). */\n timeoutMs?: number;\n}\n\nconst path = (id: string) => `/v1/research/${encodeURIComponent(id)}`;\n\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason ?? new Error('Aborted'));\n const t = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(t);\n reject(signal?.reason ?? new Error('Aborted'));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport const isResearchFinished = (job: Pick<ResearchJob, 'status'>): boolean =>\n job.status === 'done' || job.status === 'failed';\n\nexport class Research {\n constructor(private readonly http: HttpClient) {}\n\n /**\n * `POST /v1/research` — start a deep-research job. With `wait_s` (0..55) the call waits that long and returns the\n * finished job; otherwise (or when it is still running) the job comes back `queued` / `running`.\n */\n create(body: ResearchRequest, opts: ResearchCreateOptions = {}): Promise<ResearchJob> {\n return this.http.json<ResearchJob>('/v1/research', {\n method: 'POST',\n body,\n headers: opts.idempotencyKey ? { 'Idempotency-Key': opts.idempotencyKey } : undefined,\n noRetry: !opts.idempotencyKey,\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `GET /v1/research/{id}` — one of your jobs (another account's id is a 404). Free. */\n retrieve(id: string, opts: CallOpts = {}): Promise<ResearchJob> {\n return this.http.json<ResearchJob>(path(id), { ext: opts.ext, signal: opts.signal });\n }\n\n /**\n * Poll `retrieve` every `intervalMs` (default 3 s) until the job is `done` or `failed` and resolve with it (a\n * `failed` job resolves too — check `status` / `error`). Throws when it is not finished within `timeoutMs`\n * (default 6 min) or when `signal` aborts.\n */\n async wait(id: string, opts: ResearchWaitOptions = {}): Promise<ResearchJob> {\n const { intervalMs = 3000, timeoutMs = 360_000, signal, ext } = opts;\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const job = await this.retrieve(id, { ext, signal });\n if (isResearchFinished(job)) return job;\n if (Date.now() + intervalMs > deadline) {\n throw new Error(`codai research job ${id} did not finish within ${timeoutMs} ms`);\n }\n await abortableSleep(intervalMs, signal);\n }\n }\n\n /** `create` then `wait` until the job finishes. */\n async run(\n body: ResearchRequest,\n opts: ResearchCreateOptions & Omit<ResearchWaitOptions, keyof CallOpts> = {},\n ): Promise<ResearchJob> {\n const { intervalMs, timeoutMs, ...createOpts } = opts;\n const job = await this.create(body, createOpts);\n if (isResearchFinished(job)) return job;\n return this.wait(job.id, {\n ext: opts.ext,\n signal: opts.signal,\n ...(intervalMs !== undefined ? { intervalMs } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n });\n }\n}\n","/** `/v1/usage` + `/v1/keys` — the caller's own usage breakdown and API keys (device attribution, tags). */\nimport { type CodaiRequestExtensions, type HttpClient } from '../http';\nimport { type Mutable, type QueryOf, type Reply, type Schema } from './_shared';\n\nexport type UsageReport = Schema<'UsageReport'>;\nexport type UsageRow = Schema<'UsageRow'>;\nexport type UsageGroupBy = UsageReport['group_by'];\n/** `from` / `to` are inclusive `YYYY-MM-DD` UTC dates; `cost_micro_usd` in the reply is USD micros as a string. */\nexport type UsageQuery = Mutable<QueryOf<'getUsage'>>;\nexport type ApiKeyInfo = Schema<'ApiKeyInfo'>;\nexport type ApiKeyList = Reply<'listKeys'>;\nexport type ApiKeyTags = Reply<'setKeyTags'>;\n\nexport interface ApiKeyListQuery {\n /** Also return revoked keys. */\n include_revoked?: boolean;\n}\n\ntype CallOpts = { ext?: CodaiRequestExtensions; signal?: AbortSignal };\n\nexport class Usage {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/usage` — default: last 30 days grouped by `day`; at most 400 days per call. */\n get(query: UsageQuery = {}, opts: CallOpts = {}): Promise<UsageReport> {\n return this.http.json<UsageReport>('/v1/usage', {\n query: {\n from: query.from,\n to: query.to,\n group_by: query.group_by,\n key: query.key,\n device: query.device,\n app: query.app,\n platform: query.platform,\n model: query.model,\n tag: query.tag,\n },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n\nexport class Keys {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/keys` — your keys (never the secret); `current: true` marks the calling key. */\n list(query: ApiKeyListQuery = {}, opts: CallOpts = {}): Promise<ApiKeyList> {\n return this.http.json<ApiKeyList>('/v1/keys', {\n query: { include_revoked: query.include_revoked ? 'true' : undefined },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n\n /** `PATCH /v1/keys/{id}` — replace the key's tags (≤ 16, each ≤ 32 chars; `[]` clears). */\n setTags(id: string, tags: string[], opts: CallOpts = {}): Promise<ApiKeyTags> {\n return this.http.json<ApiKeyTags>(`/v1/keys/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n body: { tags },\n ext: opts.ext,\n signal: opts.signal,\n });\n }\n}\n","/**\n * `/v1/verify/agent-output*` — EXPERIMENTAL, unaudited (HIDE protocol) verification of\n * signed agent outputs. Provenance only, never authentication. Unauthenticated endpoints.\n */\nimport { type HttpClient } from '../http';\nimport { type Body, type Mutable, type Reply, type Schema } from './_shared';\n\nexport type EnvironmentTaskOutputSignature = Schema<'EnvironmentTaskOutputSignature'>;\nexport type AgentOutputKey = Reply<'getAgentOutputKey'>;\nexport type AgentOutputVerifyBody = Mutable<Body<'verifyAgentOutput'>>;\nexport type AgentOutputVerifyResult = Reply<'verifyAgentOutput'>;\n\ntype CallOpts = { signal?: AbortSignal };\n\nexport class Verify {\n constructor(private readonly http: HttpClient) {}\n\n /** `GET /v1/verify/agent-output/key` — `{ enabled: false }` when signing is off. */\n agentOutputKey(opts: CallOpts = {}): Promise<AgentOutputKey> {\n return this.http.json<AgentOutputKey>('/v1/verify/agent-output/key', { signal: opts.signal });\n }\n\n /** `POST /v1/verify/agent-output` — 503 `signing_disabled` when signing is off. */\n agentOutput(body: AgentOutputVerifyBody, opts: CallOpts = {}): Promise<AgentOutputVerifyResult> {\n return this.http.json<AgentOutputVerifyResult>('/v1/verify/agent-output', {\n method: 'POST',\n body,\n signal: opts.signal,\n // 503 here means `signing_disabled`, not a transient outage.\n noRetry: true,\n });\n }\n}\n","/**\n * Single source of truth for OpenAPI parity: every `operationId` in\n * `apps/docs/openapi/en/gateway.yaml` maps to exactly one dotted method path\n * on the `Codai` client. `operations.test.ts` parses the YAML and fails when\n * an operation is missing, mapped to a non-function, or when this table\n * carries a key the YAML does not have.\n */\nexport const OPERATION_METHODS: Record<string, string> = {\n // Chat & Completions\n createChatCompletion: 'chat.completions.create',\n createResponse: 'responses.create',\n createMessage: 'messages.create',\n // Embeddings & Audio\n createEmbeddings: 'embeddings.create',\n createImage: 'images.generate',\n editImage: 'images.edit',\n createMusic: 'music.generate',\n createVideo: 'videos.create',\n getVideo: 'videos.retrieve',\n createRender: 'renders.create',\n getRender: 'renders.retrieve',\n listRenders: 'renders.list',\n createTimeline: 'renders.createTimeline',\n regenerateRenderScene: 'renders.regenerateScene',\n listAssets: 'assets.list',\n getAsset: 'assets.retrieve',\n getAssetContent: 'assets.contentUrl',\n deleteAsset: 'assets.delete',\n searchSfx: 'sfx.search',\n importSfx: 'sfx.import',\n // Cards (typed card data)\n cardsWeather: 'cards.weather',\n cardsPlaces: 'cards.places',\n cardsGeocode: 'cards.geocode',\n cardsStaticMap: 'cards.staticMap',\n cardsFx: 'cards.fx',\n cardsRoute: 'cards.route',\n cardsTrack: 'cards.track',\n cardsEfactura: 'cards.efactura',\n cardsUnfurl: 'cards.unfurl',\n cardsProduct: 'cards.product',\n cardsRender: 'cards.render',\n createDocument: 'documents.create',\n retrieveDocument: 'documents.retrieve',\n createDocumentPreview: 'documents.preview',\n retrievePreview: 'documents.retrievePreview',\n createDocumentVideo: 'documents.video',\n // Studio creatives (editable creative documents)\n listCreatives: 'creatives.list',\n createCreative: 'creatives.create',\n getCreative: 'creatives.retrieve',\n deleteCreative: 'creatives.delete',\n getCreativeOutline: 'creatives.outline',\n findCreativeNodes: 'creatives.find',\n getCreativeSubtree: 'creatives.subtree',\n applyCreativeOps: 'creatives.edit',\n listCreativeVersions: 'creatives.versions',\n revertCreative: 'creatives.revert',\n forkCreative: 'creatives.fork',\n lintCreative: 'creatives.lint',\n getCreativeCompiled: 'creatives.compiled',\n renderCreative: 'creatives.render',\n createCreativeFrame: 'creatives.frame',\n getCreativeFrameJob: 'creatives.frameJob',\n commentCreative: 'creatives.comment',\n createCreativeVariants: 'creatives.variants',\n listCreativeVariants: 'creatives.listVariants',\n pickCreativeVariant: 'creatives.pickVariant',\n extractBrandKit: 'brandKits.extract',\n listBrandKits: 'brandKits.list',\n getBrandKit: 'brandKits.retrieve',\n deleteBrandKit: 'brandKits.delete',\n createBrandKit: 'brandKits.create',\n updateBrandKit: 'brandKits.update',\n exportBrandKitDtcg: 'brandKits.exportDtcg',\n restyleCreative: 'creatives.restyle',\n captionCreative: 'creatives.captions',\n getCreativeCaptionsSrt: 'creatives.captionsSrt',\n getCreativeCaptionsVtt: 'creatives.captionsVtt',\n adaptCreative: 'creatives.adapt',\n fixCreativeLint: 'creatives.lintFix',\n getCreativeControls: 'creatives.controls',\n getCreativeLocales: 'creatives.locales',\n localizeCreative: 'creatives.localize',\n forkCreativeLocale: 'creatives.forkLocale',\n createCreativeShare: 'creatives.createShare',\n listCreativeShares: 'creatives.listShares',\n revokeCreativeShare: 'creatives.revokeShare',\n getCreativeReview: 'creatives.review',\n updateCreativeReview: 'creatives.requestReview',\n listCreativeReviewThreads: 'creatives.reviewThreads',\n createCreativeReviewThread: 'creatives.createReviewThread',\n replyCreativeReviewThread: 'creatives.replyReviewThread',\n resolveCreativeReviewThread: 'creatives.resolveReviewThread',\n reopenCreativeReviewThread: 'creatives.reopenReviewThread',\n deleteCreativeReviewComment: 'creatives.deleteReviewComment',\n remixStudioShare: 'shares.remix',\n getPublicStudioShare: 'shares.get',\n createPublicReviewThread: 'shares.comment',\n replyPublicReviewThread: 'shares.reply',\n resolvePublicReviewThread: 'shares.resolve',\n reopenPublicReviewThread: 'shares.reopen',\n decidePublicReview: 'shares.decide',\n createVoiceRevocation: 'voiceRevocations.create',\n getVaultAccount: 'vault.account',\n putVaultAccount: 'vault.putAccount',\n patchVaultSettings: 'vault.updateSettings',\n lockVault: 'vault.lock',\n createVaultUnlockChallenge: 'vault.unlockChallenge',\n unlockVault: 'vault.unlock',\n listVaultLimits: 'vault.limits',\n setVaultItemLimits: 'vault.setLimits',\n revokeVaultTaskGrants: 'vault.revokeTaskGrants',\n listVaults: 'vault.vaults',\n createVault: 'vault.createVault',\n listVaultItems: 'vault.items',\n putVaultItem: 'vault.putItem',\n deleteVaultItem: 'vault.deleteItem',\n setVaultItemCloud: 'vault.setItemCloud',\n listVaultRules: 'vault.rules',\n createVaultRule: 'vault.createRule',\n deleteVaultRule: 'vault.deleteRule',\n listVaultGrants: 'vault.grants',\n revokeVaultGrant: 'vault.revokeGrant',\n listVaultEvents: 'vault.events',\n listVaultApprovals: 'vault.approvals',\n getVaultApproval: 'vault.approval',\n decideVaultApproval: 'vault.decide',\n createVaultDeviceChallenge: 'vault.devices.challenge',\n enrollVaultDevice: 'vault.devices.enroll',\n listVaultDevices: 'vault.devices.list',\n renameVaultDevice: 'vault.devices.rename',\n revokeVaultDevice: 'vault.devices.revoke',\n vaultCatalog: 'vault.catalog',\n vaultUse: 'vault.use',\n vaultHttp: 'vault.httpCall',\n vaultResolve: 'vault.resolve',\n createStudioAbuseReport: 'abuseReports.create',\n checkProvenance: 'provenance.check',\n createStudioBatch: 'batches.create',\n listStudioBatches: 'batches.list',\n getStudioBatch: 'batches.get',\n cancelStudioBatch: 'batches.cancel',\n retryStudioBatch: 'batches.retry',\n exportStudioBatchCsv: 'batches.exportCsv',\n zipStudioBatch: 'batches.zip',\n saveCreativeTemplate: 'creatives.saveTemplate',\n listCreativeTemplates: 'templates.list',\n createStudioProduction: 'productions.create',\n getStudioProduction: 'productions.retrieve',\n listStudioMediaOps: 'mediaOps.list',\n quoteStudioMediaOp: 'mediaOps.quote',\n runStudioMediaOp: 'mediaOps.run',\n getStudioMediaOpJob: 'mediaOps.job',\n writeStudioLyrics: 'lyrics.write',\n alignStudioLyrics: 'lyrics.align',\n getCreativeTemplate: 'templates.retrieve',\n deleteCreativeTemplate: 'templates.delete',\n exportCreativeFcpxml: 'creatives.exportFcpxml',\n exportCreativeLottie: 'creatives.exportLottie',\n getStudioExport: 'exports.retrieve',\n createCreativeFromDocument: 'creatives.fromDocument',\n buildCreative: 'creatives.build',\n writeCreativePostCopy: 'creatives.postCopy',\n transcriptCutCreative: 'creatives.transcriptCut',\n regenerateCreativeNode: 'creatives.regenerateNode',\n createSystemOne: 'systemOne.create',\n createTranscription: 'audio.transcribe',\n createSpeech: 'audio.speech',\n createSpeechStream: 'audio.speechStream',\n createEphemeralToken: 'tokens.create',\n // Models\n listModels: 'models.list',\n // Health\n getHealth: 'health.get',\n getHealthReady: 'health.ready',\n getStatus: 'health.status',\n // Agents\n runAgentSync: 'agents.run',\n createAgentRun: 'agents.runs.create',\n getAgentRunStats: 'agents.runs.stats',\n getAgentRun: 'agents.runs.get',\n listAgentRunSteps: 'agents.runs.steps',\n streamAgentRun: 'agents.runs.stream',\n cancelAgentRun: 'agents.runs.cancel',\n // Tools\n toolsSearch: 'tools.search',\n toolsFetch: 'tools.fetch',\n toolsGround: 'tools.ground',\n createResearch: 'research.create',\n getResearch: 'research.retrieve',\n // Tasks\n listTasks: 'tasks.list',\n listPendingTasks: 'tasks.pending',\n getTaskStats: 'tasks.stats',\n getTask: 'tasks.get',\n confirmTask: 'tasks.confirm',\n // Event triggers + inbox\n listTriggers: 'triggers.list',\n createTrigger: 'triggers.create',\n updateTrigger: 'triggers.update',\n deleteTrigger: 'triggers.delete',\n rotateTriggerSecret: 'triggers.rotateSecret',\n setTriggerSecret: 'triggers.setSecret',\n testTrigger: 'triggers.test',\n listTriggerEvents: 'triggers.events',\n receiveTriggerHook: 'triggers.fireHook',\n listNotifications: 'notifications.list',\n markNotificationsRead: 'notifications.markRead',\n deleteNotification: 'notifications.delete',\n deleteNotifications: 'notifications.deleteMany',\n // Pending prompts\n listPrompts: 'prompts.list',\n createPrompt: 'prompts.create',\n getPrompt: 'prompts.get',\n updatePrompt: 'prompts.update',\n deletePrompt: 'prompts.delete',\n launchPrompt: 'prompts.launch',\n matchPrompt: 'prompts.match',\n verifyPrompt: 'prompts.verify',\n verifyPrompts: 'prompts.verifyMany',\n streamPrompts: 'prompts.stream',\n exportPrompts: 'prompts.exportPrompts',\n bulkPrompts: 'prompts.bulk',\n listPromptEvents: 'prompts.events',\n instantiatePrompt: 'prompts.instantiate',\n // Transcripts\n listTranscripts: 'transcripts.list',\n createTranscript: 'transcripts.create',\n getTranscriptUsage: 'transcripts.usage',\n streamTranscripts: 'transcripts.stream',\n searchTranscripts: 'transcripts.search',\n askTranscripts: 'transcripts.ask',\n getTranscript: 'transcripts.get',\n updateTranscript: 'transcripts.update',\n deleteTranscript: 'transcripts.delete',\n finalizeTranscript: 'transcripts.finalize',\n retranscribeTranscript: 'transcripts.retranscribe',\n reanalyzeTranscript: 'transcripts.reanalyze',\n addTranscriptBookmark: 'transcripts.addBookmark',\n updateTranscriptSpeaker: 'transcripts.renameSpeaker',\n updateTranscriptUtterance: 'transcripts.editUtterance',\n getTranscriptAudio: 'transcripts.audio',\n exportTranscript: 'transcripts.export',\n acceptTranscriptPrompt: 'transcripts.acceptPrompt',\n createTranscriptShare: 'transcripts.shares.create',\n listTranscriptShares: 'transcripts.shares.list',\n revokeTranscriptShare: 'transcripts.shares.revoke',\n getPublicTranscript: 'transcripts.publicView',\n listTranscriptFolders: 'transcripts.folders.list',\n createTranscriptFolder: 'transcripts.folders.create',\n updateTranscriptFolder: 'transcripts.folders.update',\n deleteTranscriptFolder: 'transcripts.folders.delete',\n getTranscriptVocabulary: 'transcripts.vocabulary.get',\n putTranscriptVocabulary: 'transcripts.vocabulary.put',\n getUploadCapabilities: 'transcripts.uploads.capabilities',\n createUpload: 'transcripts.uploads.create',\n getUploadOffset: 'transcripts.uploads.offset',\n appendUpload: 'transcripts.uploads.append',\n publishTranscriptLive: 'transcripts.publishLive',\n // Scheduler\n listSchedules: 'schedules.list',\n createSchedule: 'schedules.create',\n previewSchedule: 'schedules.preview',\n streamSchedules: 'schedules.stream',\n getSchedule: 'schedules.get',\n updateSchedule: 'schedules.update',\n deleteSchedule: 'schedules.delete',\n runSchedule: 'schedules.runNow',\n listScheduleRuns: 'schedules.runs',\n listRecentScheduleRuns: 'schedules.recentRuns',\n decideScheduleRun: 'schedules.decide',\n approveScheduleCommand: 'schedules.executor.approveCommand',\n claimScheduleRun: 'schedules.executor.claim',\n heartbeatScheduleRun: 'schedules.executor.heartbeat',\n reportScheduleRunResult: 'schedules.executor.result',\n listSchedulerHosts: 'schedules.hosts.list',\n updateSchedulerHost: 'schedules.hosts.update',\n pauseSchedules: 'schedules.pause',\n resumeSchedules: 'schedules.resume',\n listScheduleTemplates: 'schedules.templates',\n renderScheduleTemplate: 'schedules.renderTemplate',\n listScheduleAudit: 'schedules.audit',\n listHeartbeats: 'heartbeats.list',\n createHeartbeat: 'heartbeats.create',\n updateHeartbeat: 'heartbeats.update',\n deleteHeartbeat: 'heartbeats.delete',\n // Lists & share sheet\n listLists: 'lists.list',\n createList: 'lists.create',\n reorderLists: 'lists.reorder',\n streamLists: 'lists.stream',\n updateList: 'lists.update',\n deleteList: 'lists.delete',\n listListItems: 'lists.items',\n addListItem: 'lists.add',\n updateListItem: 'lists.updateItem',\n deleteListItem: 'lists.deleteItem',\n getListItemImage: 'lists.image',\n exportListMarkdown: 'lists.exportMarkdown',\n shareToList: 'lists.share',\n // Usage & keys\n getUsage: 'usage.get',\n listKeys: 'keys.list',\n setKeyTags: 'keys.setTags',\n // Memory\n listMemories: 'memory.list',\n searchMemories: 'memory.search',\n createMemory: 'memory.create',\n deleteMemory: 'memory.delete',\n deleteAllMemories: 'memory.deleteAll',\n // Sandboxes\n createSandbox: 'sandboxes.create',\n listSandboxes: 'sandboxes.list',\n getSandbox: 'sandboxes.retrieve',\n execSandbox: 'sandboxes.exec',\n putSandboxFile: 'sandboxes.files.put',\n getSandboxFile: 'sandboxes.files.get',\n listSandboxFiles: 'sandboxes.files.list',\n listSandboxArtifacts: 'sandboxes.artifacts',\n snapshotSandbox: 'sandboxes.snapshot',\n deleteSandbox: 'sandboxes.delete',\n runSandbox: 'sandboxes.run',\n runSandboxCode: 'sandboxes.runCode',\n resetSandboxKernel: 'sandboxes.resetKernel',\n pauseSandbox: 'sandboxes.pause',\n resumeSandbox: 'sandboxes.resume',\n forkSandbox: 'sandboxes.fork',\n previewSandbox: 'sandboxes.preview',\n // Sessions\n createSession: 'sessions.create',\n listSessions: 'sessions.list',\n getSession: 'sessions.get',\n updateSession: 'sessions.update',\n deleteSession: 'sessions.delete',\n listSessionEvents: 'sessions.events.list',\n appendSessionEvents: 'sessions.events.append',\n listSessionControls: 'sessions.controls.list',\n submitSessionControl: 'sessions.controls.submit',\n markSessionControlApplied: 'sessions.controls.markApplied',\n dispatchToDevice: 'sessions.dispatch',\n claimSessionLease: 'sessions.lease.acquire',\n heartbeatSessionLease: 'sessions.lease.renew',\n releaseSessionLease: 'sessions.lease.release',\n streamSession: 'sessions.stream',\n // Devices\n getMyDispatchInbox: 'devices.dispatchInbox',\n listDevices: 'devices.list',\n updateDevice: 'devices.update',\n deleteDevice: 'devices.delete',\n revokeSelfKey: 'devices.revokeSelfKey',\n // Hosts\n listHosts: 'hosts.list',\n streamHost: 'hosts.stream',\n execOnHost: 'hosts.exec',\n postHostExecResult: 'hosts.postResult',\n // Orgs & Sharing\n listSessionsSharedWithMe: 'sessions.shares.sharedWithMe',\n listSessionShares: 'sessions.shares.list',\n createSessionShare: 'sessions.shares.create',\n deleteSessionShare: 'sessions.shares.delete',\n createOrg: 'orgs.create',\n listOrgs: 'orgs.list',\n listOrgMembers: 'orgs.members.list',\n addOrgMember: 'orgs.members.add',\n removeOrgMember: 'orgs.members.remove',\n // Projects\n listProjects: 'projects.list',\n createProject: 'projects.create',\n getProject: 'projects.get',\n updateProject: 'projects.update',\n deleteProject: 'projects.delete',\n // Environments\n listEnvironments: 'environments.list',\n createEnvironment: 'environments.create',\n enrollEnvironment: 'environments.enroll',\n getEnvironment: 'environments.get',\n updateEnvironment: 'environments.update',\n startEnvironment: 'environments.start',\n stopEnvironment: 'environments.stop',\n archiveEnvironment: 'environments.archive',\n destroyEnvironment: 'environments.destroy',\n createEnvironmentEnrollToken: 'environments.enrollToken',\n listEnvironmentMembers: 'environments.members.list',\n addEnvironmentMember: 'environments.members.add',\n setMyEnvironmentSshKey: 'environments.members.setSshKey',\n setEnvironmentMemberRole: 'environments.members.setRole',\n removeEnvironmentMember: 'environments.members.remove',\n issueMyEnvironmentSshCert: 'environments.members.sshCert',\n getEnvironmentSshCa: 'environments.sshCa',\n listEnvironmentTasks: 'environments.tasks.list',\n createEnvironmentTask: 'environments.tasks.create',\n getEnvironmentTask: 'environments.tasks.get',\n execEnvironment: 'environments.exec',\n listEnvironmentFiles: 'environments.files.list',\n getEnvironmentFile: 'environments.files.get',\n putEnvironmentFile: 'environments.files.put',\n startEnvironmentJob: 'environments.jobs.start',\n getEnvironmentJob: 'environments.jobs.get',\n // Agent-output signatures (EXPERIMENTAL, HIDE)\n getAgentOutputKey: 'verify.agentOutputKey',\n verifyAgentOutput: 'verify.agentOutput',\n listEnvironmentPorts: 'environments.ports.list',\n setEnvironmentPort: 'environments.ports.set',\n removeEnvironmentPort: 'environments.ports.remove',\n listEnvironmentSecrets: 'environments.secrets.list',\n setEnvironmentSecret: 'environments.secrets.set',\n removeEnvironmentSecret: 'environments.secrets.remove',\n // Account\n getAccount: 'account.get',\n patchAccount: 'account.update',\n getBilling: 'billing.get',\n listBillingInvoices: 'billing.invoices',\n getStudioQuote: 'billing.studioQuote',\n getReferrals: 'referrals.get',\n getSettings: 'settings.get',\n patchSettings: 'settings.update',\n getPolicy: 'osGate.policy',\n recordOsGateEvent: 'osGate.recordEvent',\n getReceipt: 'receipt.get',\n submitFeedback: 'feedback.submit',\n listPhoneModels: 'phoneModels.list',\n};\n\n/** Operations whose SDK method is an async iterator (SSE-only endpoints). */\nexport const STREAMING_OPERATIONS: ReadonlySet<string> = new Set([\n 'streamAgentRun',\n 'streamSession',\n 'streamHost',\n 'createSpeechStream',\n 'streamPrompts',\n 'streamTranscripts',\n 'streamSchedules',\n 'streamLists',\n]);\n\n/**\n * Same parity contract for the separate Resolve service\n * (`apps/docs/openapi/en/resolve.yaml`, host `resolveBaseUrl`) —\n * checked by `operations.resolve.test.ts`.\n */\nexport const RESOLVE_OPERATION_METHODS: Record<string, string> = {\n resolveHealth: 'resolve.health',\n createResolveJob: 'resolve.submit',\n getResolveJob: 'resolve.get',\n listResolveJobs: 'resolve.list',\n acceptResolveJob: 'resolve.accept',\n getResolveAttestation: 'resolve.attestation',\n getResolveKeys: 'resolve.keys',\n getResolveBalance: 'resolve.balance',\n};\n","/**\n * `CodaiApps` — management client for host apps (studiai.ro, …) that resell\n * codai to their own end users. It talks to the mgmt API (`api.codai.ro`),\n * not the gateway, and authenticates with an app connection token\n * (`codai_app_…`, created at codai.ro/console/apps/<app>), never a user key.\n *\n * keys.mint / list / update / revoke / usage → `/apps/keys*`\n * users.getOverride / setOverride / clearOverride → `/apps/users/:externalId/overrides`\n * subscriptions.sync → `/apps/subscriptions/sync`\n * validateKey → `/internal/keys/validate` (separate shared secret)\n *\n * Every call unwraps the `{ ok, data }` envelope and throws `CodaiError` on\n * a non-2xx reply (`error.code` such as `missing_scope:keys.mint`,\n * `no_key_for_external_id`, `not_owned_by_app`).\n */\n\nimport { CodaiError, HttpClient, type RequestOptions } from '../http';\n\nexport interface CodaiAppsOptions {\n /** App connection token (`codai_app_…`). Required for everything except `validateKey`. */\n appToken?: string;\n /** Shared secret for `POST /internal/keys/validate` (CODAI_VALIDATE_SHARED_SECRET on codai's side). */\n validateToken?: string;\n /** Defaults to https://api.codai.ro */\n baseUrl?: string;\n /** Default request timeout (ms). Default 20_000. */\n timeoutMs?: number;\n /** Retries on 429/5xx for idempotent calls. Default 1. `keys.mint` is never retried. */\n maxRetries?: number;\n fetch?: typeof fetch;\n}\n\nexport interface AppKeyMintInput {\n /** End user email; codai upserts its user by email so subscription syncs land on the same user. */\n email: string;\n /** The app's own stable id for the end user (≤ 200 chars). */\n endUserExternalId: string;\n label?: string;\n /** Tier slug within the app (defaults to the app's `default_tier_slug`). */\n tierSlug?: string;\n /** Attach to an existing subscription of this app + user. */\n subscriptionId?: string;\n /** Accepted for back-compat and ignored (euro caps were removed product-wide). */\n budgetEurPerDay?: number;\n /** Intersected with the app's own allowlist. */\n allowedModels?: string[];\n ratePerMinute?: number;\n ratePerHour?: number;\n maxInputTokens?: number;\n maxOutputTokens?: number;\n /** ISO 8601 with offset, in the future. Omit = never expires. */\n expiresAt?: string;\n /**\n * The end user confirmed being 18 or older in your app. Stored on the codai user when it is\n * CREATED by this call (`users.adult_confirmed_at`, version `host:<app slug>`).\n */\n adultConfirmed?: boolean;\n}\n\nexport interface AppKeyMinted {\n id: string;\n /** Plaintext key — returned exactly once. */\n key: string;\n prefix: string;\n subscriptionId: string | null;\n expiresAt: string | null;\n}\n\nexport interface AppKeyListQuery {\n endUserExternalId?: string;\n /** 1..200, default 50. */\n limit?: number;\n offset?: number;\n}\n\nexport interface AppKey {\n id: string;\n label: string;\n prefix: string;\n enabled: boolean;\n subscriptionId: string | null;\n endUserExternalId: string | null;\n lastUsedAt: string | null;\n createdAt: string;\n revokedAt: string | null;\n expiresAt?: string | null;\n}\n\nexport interface AppKeyUpdate {\n label?: string;\n enabled?: boolean;\n}\n\nexport interface AppKeyUsageWindow {\n requests: number;\n tasks: number;\n costUsd: number;\n}\n\nexport interface AppKeyUsage {\n key: { id: string; prefix: string; label: string; createdAt: string };\n usage: {\n total: AppKeyUsageWindow & {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n };\n today: AppKeyUsageWindow;\n month: AppKeyUsageWindow;\n tokensPerMinute?: {\n inputUsed: number;\n outputUsed: number;\n lastActiveInput?: number;\n lastActiveOutput?: number;\n lastActiveAt?: string | null;\n inputPeak?: number;\n inputPeakAt?: string | null;\n inputLimit: number;\n isDefaultLimit: boolean;\n };\n daily: Array<\n AppKeyUsageWindow & { date: string; promptTokens: number; completionTokens: number }\n >;\n };\n limits: {\n tierSlug: string | null;\n tierLabel: string | null;\n tasksPerDay: number | null;\n tasksPerMonth: number | null;\n ratePerMinute: number | null;\n ratePerHour: number | null;\n inputTokensPerMinute?: number | null;\n budgetEurPerDay: number | null;\n budgetEurPerMonth?: number | null;\n hasActiveSubscription: boolean;\n };\n}\n\n/** Per-(app, end user) override fields; `null` clears a field back to the tier value. */\nexport interface AppOverrideInput {\n forceTierSlug?: string | null;\n allowedModels?: string[] | null;\n ratePerMinute?: number | null;\n ratePerHour?: number | null;\n budgetEurPerDay?: number | null;\n budgetEurPerMonth?: number | null;\n tasksPerDay?: number | null;\n tasksPerMonth?: number | null;\n /** ISO 8601; null = never expires. */\n expiresAt?: string | null;\n note?: string | null;\n /** Restart task counting from now (usage history is kept). */\n resetUsage?: boolean | null;\n}\n\nexport interface AppOverrideRow {\n id: string;\n forceTierSlug: string | null;\n allowedModels: string[] | null;\n ratePerMinute: number | null;\n ratePerHour: number | null;\n budgetEurPerDay: string | number | null;\n budgetEurPerMonth?: string | number | null;\n tasksPerDay: number | null;\n tasksPerMonth: number | null;\n expiresAt: string | null;\n note: string | null;\n}\n\n/** Effective limits after merging the override on top of the subscription tier. */\nexport interface AppEffectiveLimits {\n tierSlug: string | null;\n tierLabel: string | null;\n allowedModels: string[] | null;\n ratePerMinute: number | null;\n ratePerDay?: number | null;\n budgetEurPerDay: number | null;\n budgetEurPerMonth?: number | null;\n tasksPerDay: number | null;\n tasksPerMonth: number | null;\n maxRoutingTier?: 'small' | 'medium' | 'large' | null;\n hasActiveSubscription: boolean;\n [extra: string]: unknown;\n}\n\nexport interface AppOverride {\n override: AppOverrideRow | null;\n effectiveLimits: AppEffectiveLimits;\n /** Present on reads: whether overrides are enabled for the app at all. */\n allowOverride?: boolean;\n}\n\nexport interface AppSubscriptionSyncInput {\n /** Email of the subscribing end user. */\n email: string;\n /** The Stripe event verbatim; codai re-shapes it server-side. */\n event: { id: string; type: string; data?: { object?: unknown } };\n /** The end user confirmed being 18 or older (stored when the codai user is created by this sync). */\n adultConfirmed?: boolean;\n}\n\nexport interface AppKeyValidation {\n ok: boolean;\n valid: boolean;\n key?: {\n id: string;\n prefix: string;\n label: string;\n appId: string;\n subscriptionId: string | null;\n endUserExternalId: string | null;\n };\n user?: { id: string };\n entitlements?: {\n tierSlug: string | null;\n hasActiveSubscription: boolean;\n allowedModels: string[] | null;\n ratePerMinute: number | null;\n ratePerHour: number | null;\n maxInputTokens: number | null;\n maxOutputTokens: number | null;\n budgetEurPerDay: number | null;\n supportsSubagents: boolean;\n supportsByok: boolean;\n };\n /** Set when `valid` is false (`key_not_found_or_disabled`). */\n reason?: string;\n}\n\ntype CallOpts = { signal?: AbortSignal };\ntype Envelope<T> = { ok: boolean; data?: T; error?: unknown };\n\nconst enc = encodeURIComponent;\n\nclass AppKeys {\n constructor(private readonly apps: CodaiApps) {}\n\n /** `POST /apps/keys` — mint a key for one of the app's end users (scope `keys.mint`). Never retried. */\n mint(input: AppKeyMintInput, o: CallOpts = {}): Promise<AppKeyMinted> {\n return this.apps.call('/apps/keys', { method: 'POST', body: input, noRetry: true, ...o });\n }\n\n /** `GET /apps/keys` — keys minted by this app, newest first (scope `usage.read`). */\n list(query: AppKeyListQuery = {}, o: CallOpts = {}): Promise<AppKey[]> {\n return this.apps.call('/apps/keys', {\n query: {\n endUserExternalId: query.endUserExternalId,\n limit: query.limit,\n offset: query.offset,\n },\n ...o,\n });\n }\n\n /** `PATCH /apps/keys/{id}` — change label / enabled (scope `keys.mint`). */\n update(\n id: string,\n patch: AppKeyUpdate,\n o: CallOpts = {},\n ): Promise<{ id: string } & AppKeyUpdate> {\n return this.apps.call(`/apps/keys/${enc(id)}`, { method: 'PATCH', body: patch, ...o });\n }\n\n /** `DELETE /apps/keys/{id}` — revoke (scope `keys.revoke`). */\n revoke(id: string, o: CallOpts = {}): Promise<{ id: string }> {\n return this.apps.call(`/apps/keys/${enc(id)}`, { method: 'DELETE', ...o });\n }\n\n /** `GET /apps/keys/{id}/usage?days=` — codai-side usage + effective limits; `days` clamps to 1..90. */\n usage(id: string, days = 30, o: CallOpts = {}): Promise<AppKeyUsage> {\n return this.apps.call(`/apps/keys/${enc(id)}/usage`, { query: { days }, ...o });\n }\n\n /** Revoke every non-revoked key minted for `endUserExternalId`; returns how many were revoked. */\n async revokeAllFor(endUserExternalId: string, o: CallOpts = {}): Promise<number> {\n const keys = await this.list({ endUserExternalId, limit: 200 }, o);\n let revoked = 0;\n for (const k of keys) {\n if (k.revokedAt) continue;\n await this.revoke(k.id, o);\n revoked++;\n }\n return revoked;\n }\n}\n\nclass AppUsers {\n constructor(private readonly apps: CodaiApps) {}\n\n /** `GET /apps/users/{externalId}/overrides` — current override + effective limits (scope `usage.read`). */\n getOverride(externalId: string, o: CallOpts = {}): Promise<AppOverride> {\n return this.apps.call(`/apps/users/${enc(externalId)}/overrides`, o);\n }\n\n /** `PUT /apps/users/{externalId}/overrides` — set / replace (scope `overrides.write`, app must allow overrides). */\n setOverride(externalId: string, input: AppOverrideInput, o: CallOpts = {}): Promise<AppOverride> {\n return this.apps.call(`/apps/users/${enc(externalId)}/overrides`, {\n method: 'PUT',\n body: input,\n ...o,\n });\n }\n\n /** `DELETE /apps/users/{externalId}/overrides` — clear (scope `overrides.write`). */\n clearOverride(externalId: string, o: CallOpts = {}): Promise<{ removed: boolean }> {\n return this.apps.call(`/apps/users/${enc(externalId)}/overrides`, { method: 'DELETE', ...o });\n }\n}\n\nclass AppSubscriptions {\n constructor(private readonly apps: CodaiApps) {}\n\n /** `POST /apps/subscriptions/sync` — forward a Stripe subscription event (scope `subscriptions.sync`; idempotent per subscription). */\n sync(\n input: AppSubscriptionSyncInput,\n o: CallOpts = {},\n ): Promise<{ subscriptionId: string | null }> {\n return this.apps.call('/apps/subscriptions/sync', { method: 'POST', body: input, ...o });\n }\n}\n\nexport class CodaiApps {\n readonly keys: AppKeys;\n readonly users: AppUsers;\n readonly subscriptions: AppSubscriptions;\n private readonly appHttp: HttpClient | null;\n private readonly validateHttp: HttpClient | null;\n\n constructor(opts: CodaiAppsOptions) {\n if (!opts.appToken && !opts.validateToken) {\n throw new Error('CodaiApps: appToken or validateToken is required');\n }\n const common = {\n baseUrl: opts.baseUrl ?? 'https://api.codai.ro',\n timeoutMs: opts.timeoutMs ?? 20_000,\n maxRetries: opts.maxRetries ?? 1,\n fetch: opts.fetch,\n };\n this.appHttp = opts.appToken ? new HttpClient({ apiKey: opts.appToken, ...common }) : null;\n this.validateHttp = opts.validateToken\n ? new HttpClient({ apiKey: opts.validateToken, ...common })\n : null;\n this.keys = new AppKeys(this);\n this.users = new AppUsers(this);\n this.subscriptions = new AppSubscriptions(this);\n }\n\n /**\n * `POST /internal/keys/validate` — does this plaintext key resolve to an\n * enabled codai key? Returns `{ valid: false, reason }` for unknown /\n * disabled keys; throws `CodaiError` for auth or transport failures.\n */\n async validateKey(key: string, o: CallOpts = {}): Promise<AppKeyValidation> {\n if (!this.validateHttp) throw new Error('CodaiApps: validateToken is required for validateKey');\n return this.validateHttp.json<AppKeyValidation>('/internal/keys/validate', {\n method: 'POST',\n body: { key },\n ...o,\n });\n }\n\n /** @internal Perform an app-token call and unwrap `{ ok, data }`. */\n async call<T>(path: string, init: RequestOptions = {}): Promise<T> {\n if (!this.appHttp) throw new Error('CodaiApps: appToken is required for /apps/* calls');\n const env = await this.appHttp.json<Envelope<T>>(path, init);\n if (!env || env.ok !== true || env.data === undefined) {\n throw new CodaiError(`codai ${path} → ok=false`, 200, env);\n }\n return env.data;\n }\n}\n","/**\n * codai-sdk — official TypeScript client for the codai AI gateway.\n *\n * Full parity with the public gateway OpenAPI (every `operationId` has one\n * method — see `OPERATION_METHODS`). Resources hang off the `Codai` client:\n *\n * client.chat.completions.create / .stream client.messages / client.responses\n * client.embeddings / client.images / client.audio / client.tokens / client.models / client.health\n * client.music.generate / client.videos.create / .retrieve / .generate (codai Studio, US-only)\n * client.renders.create / .retrieve / .render (codai Studio HyperFrames → MP4, codai-render)\n * client.assets.list / .retrieve / .contentUrl / .delete (stored codai Studio assets)\n * client.sfx.search / .import (codai Studio CC0 sound-effects library, codai-sfx)\n * client.documents.create / .retrieve / .preview / .retrievePreview / .video / .createPreviewAndWait / .videoAndWait\n * (codai Studio decks / docs / sheets → PPTX / DOCX / XLSX, codai-docs; previews codai-docs-preview)\n * client.creatives.create / .retrieve / .outline / .find / .subtree / .edit / .versions / .revert / .fork / .lint\n * / .compiled / .render / .frame / .frameJob / .comment / .variants / .listVariants / .pickVariant\n * / .saveTemplate / .exportFcpxml / .exportLottie / .downloadLottie / .fromDocument / .build / .restyle / .captions / .captionsSrt / .captionsVtt\n * / .adapt / .lintFix / .controls / .locales / .localize / .forkLocale / .createShare / .listShares\n * / .revokeShare / .review / .requestReview / .resetReview / .reviewThreads / .createReviewThread\n * / .replyReviewThread / .resolveReviewThread / .reopenReviewThread / .deleteReviewComment / .delete\n * (codai Studio editable creative documents, ops + version history + A/B variants; free but render, comment,\n * variants and frames beyond the daily quota)\n * client.brandKits.create / .update / .exportDtcg / .extract / .list / .retrieve / .delete (codai Studio brand\n * kits as DTCG tokens, from a web page or a logo; extract is\n * token-metered, the rest free; apply with creatives.create({ kind, brand_kit_id }))\n * client.templates.list / .retrieve / .delete (codai Studio templates saved with creatives.saveTemplate plus the 40\n * built-in starters; free; use with creatives.create({ kind, template, vars }))\n * client.productions.create / .retrieve / .wait / .run (codai Studio brief → promo video: storyboard, images,\n * voice-over, editable creative, draft render, one review + repair; billed as the parts are produced)\n * client.mediaOps.list / .quote / .run / .job / .wait / .runAndWait (codai Studio media operations on your assets:\n * background removal, upscale, inpaint / outpaint / erase, stems, denoise, MIDI, mastering, analysis, ACE-Step\n * music and sound effects; quote held, measured cost billed; async ops return a job)\n * client.lyrics.write / .align (codai Studio lyrics writer with syllable + rhyme checks; karaoke alignment to a clip\n * of an audio creative with LRC; token-metered / transcription billed)\n * client.creatives.renderAudio (mixdown + mastering of an audio creative: WAV / MP3 / FLAC, stems, LRC)\n * client.jam.connect (WebSocket live jam on Lyria RealTime; not an OpenAPI operation)\n * client.exports.retrieve / .wait (codai Studio FCPXML exports queued with creatives.exportFcpxml; only newly\n * rendered seconds are billed; Lottie exports from creatives.exportLottie are free and ready at once)\n * client.batches.create / .dryRun / .list / .get / .cancel / .retry / .exportCsv / .zip / .wait (codai Studio\n * batches: one creative per CSV / sheet row; free, row translations and renders billed as usual)\n * client.shares.get / .remix / .comment / .reply / .resolve / .reopen / .decide (codai Studio share links from the\n * outside: read a shared creative, remix a view link, comment and decide through a review link; free)\n * client.voiceRevocations.create (public takedown ticket for a voice cloned in codai Studio; no key needed)\n * client.vault.account / .items / .putItem / .rules / .approvals / .decide / .catalog / .use / .httpCall / .resolve\n * client.vault.devices.challenge / .enroll / .list / .rename / .revoke (device approval keys, V-27)\n * client.vault.updateSettings / .lock / .unlockChallenge / .unlock / .limits / .setLimits / .revokeTaskGrants (guards, v4)\n * (zero-knowledge credentials vault: ciphertext only; the broker calls never return secret values)\n * client.abuseReports.create (public DSA notice about a codai Studio share / review link; no key needed)\n * client.provenance.check (public: which codai AI-provenance marks a file carries; no key needed)\n * client.systemOne.create / .batch (typed decisions, codai-s1)\n * client.realtime.connect (WebSocket live STT / voice; not an OpenAPI operation)\n * client.agents.run + client.agents.runs.* client.tools.search / .fetch (metered web tools)\n * client.research.create / .retrieve / .wait / .run (async deep research, cited report)\n * client.cards.weather / .places / .geocode / .staticMap / .fx / .unfurl (typed card data, `{ block, provenance }`)\n * client.tasks.* client.sessions.* (events, controls, lease, shares, stream)\n * client.devices.* / client.hosts.* client.orgs.* / client.account / client.receipt\n * client.settings.get / .update (account-level settings shared by every device)\n * client.osGate.policy / .recordEvent (OS protection gate: org override policy + override audit events)\n * client.billing.get / .invoices / .watchBalance (READ-ONLY billing overview; never starts a payment)\n * client.referrals.get / .redeem / .setConsent (referral stats + invitees; mutations via PATCH /v1/account)\n * client.usage.get / client.keys.list / .setTags (own usage breakdown + API keys)\n * client.projects.* client.environments.* (members, ports, secrets)\n * client.sandboxes.create / .list / .retrieve / .exec / .execStream / .files.put / .files.get / .files.list\n * / .artifacts / .snapshot / .delete / .run (agent sandboxes: isolated gVisor workspaces, no network by default)\n * / .runCode / .resetKernel / .pause / .resume / .fork / .preview (backend v2, the default; .snapshot is v1 only)\n * client.verify.agentOutputKey / .agentOutput (EXPERIMENTAL HIDE-signed agent outputs)\n * client.feedback / client.phoneModels\n * client.resolve.* (verified bug fixes on https://resolve.codai.ro — resolve.yaml; .list / .iterate page your jobs)\n *\n * Top-level `chat()`, `chatStream()`, `embeddings()`, `models()`, `feedback()`,\n * `mintToken()` from 0.2.x are kept as thin aliases.\n *\n * Zero runtime dependencies; Node 18+ (global fetch) and modern edge runtimes.\n */\n\nimport { type CodaiRequestExtensions, HttpClient } from './http';\nimport { Account, Feedback, PhoneModels, Receipts } from './resources/account';\nimport { Agents } from './resources/agents';\nimport { Audio } from './resources/audio';\nimport { Billing } from './resources/billing';\nimport { Cards } from './resources/cards';\nimport {\n Chat,\n type ChatCompletionInput,\n type ChatCompletionRequest,\n type ChatMessage,\n type ChatResult,\n type ChatStream,\n} from './resources/chat';\nimport { Devices } from './resources/devices';\nimport { Embeddings } from './resources/embeddings';\nimport { Environments } from './resources/environments';\nimport { Health } from './resources/health';\nimport { Hosts } from './resources/hosts';\nimport { Assets } from './resources/assets';\nimport { Images } from './resources/images';\nimport { Music, Renders, Videos } from './resources/media';\nimport { Documents } from './resources/documents';\nimport { Creatives } from './resources/creatives';\nimport { BrandKits } from './resources/brand-kits';\nimport { Templates } from './resources/templates';\nimport { Productions } from './resources/productions';\nimport { MediaOps } from './resources/media-ops';\nimport { LyricsResource } from './resources/lyrics';\nimport { Jam } from './resources/jam';\nimport { Exports } from './resources/exports';\nimport { Batches } from './resources/batches';\nimport { Shares } from './resources/shares';\nimport { VoiceRevocations } from './resources/voice-revocations';\nimport { Vault } from './resources/vault';\nimport { AbuseReports } from './resources/abuse-reports';\nimport { Provenance } from './resources/provenance';\nimport { Messages } from './resources/messages';\nimport { Models } from './resources/models';\nimport { Orgs } from './resources/orgs';\nimport { Projects } from './resources/projects';\nimport { Realtime } from './resources/realtime';\nimport { Referrals } from './resources/referrals';\nimport { Resolve } from './resources/resolve';\nimport { Responses } from './resources/responses';\nimport { Sessions } from './resources/sessions';\nimport { Settings } from './resources/settings';\nimport { OsGate } from './resources/os-gate';\nimport { Sfx } from './resources/sfx';\nimport { SystemOne } from './resources/system-one';\nimport { Tasks } from './resources/tasks';\nimport { Notifications, Triggers } from './resources/triggers';\nimport { Prompts } from './resources/prompts';\nimport { Heartbeats, Schedules } from './resources/schedules';\nimport { Lists } from './resources/lists';\nimport { Memory } from './resources/memory';\nimport { Sandboxes } from './resources/sandboxes';\nimport { Transcripts } from './resources/transcripts';\nimport { type EphemeralScope, type EphemeralToken, Tokens } from './resources/tokens';\nimport { Tools } from './resources/tools';\nimport { Research } from './resources/research';\nimport { Keys, Usage } from './resources/usage-keys';\nimport { Verify } from './resources/verify';\n\nexport interface CodaiClientOptions {\n apiKey: string;\n /** Defaults to https://ai.codai.ro */\n baseUrl?: string;\n /** codai Resolve service host (`client.resolve`). Defaults to https://resolve.codai.ro */\n resolveBaseUrl?: string;\n /** Stable conversation/session id — sent as `x-codai-session-id` on every request. */\n sessionId?: string;\n /** Device UUID for shared-sessions / hosts — sent as `x-codai-device` on every request. */\n device?: string;\n /** Device name / platform recorded on first registration. */\n deviceName?: string;\n devicePlatform?: CodaiRequestExtensions['devicePlatform'];\n /** Client surface tag (`x-codai-client`). */\n client?: string;\n /** Any other default `X-Codai-*` extensions (per-call bags override). */\n defaults?: CodaiRequestExtensions;\n /** Default request timeout (ms). Default 120_000. Streams are not time-capped. */\n timeoutMs?: number;\n /** Retries on 429/5xx with exponential backoff. Default 2. */\n maxRetries?: number;\n /** Injectable fetch (tests / custom agents). */\n fetch?: typeof fetch;\n}\n\n/** 0.2.x-compatible chat options (thin alias over `chat.completions`). */\nexport interface ChatOptions {\n model?: string;\n messages: ChatMessage[];\n temperature?: number;\n maxTokens?: number;\n tools?: ChatCompletionRequest['tools'];\n /** codai extension: plan-and-execute agent mode (Pro+). */\n agentMode?: boolean;\n /** codai extension: server-side context compaction ('auto'). */\n compact?: 'auto';\n /** codai extension: best-of-N override (0 disables, 3 forces). */\n bestOf?: 0 | 3;\n /** Attribution id recorded on tool calls (agent fleets). */\n agentId?: string;\n /** Per-call session override. */\n sessionId?: string;\n /** Any other `X-Codai-*` extension. */\n ext?: CodaiRequestExtensions;\n signal?: AbortSignal;\n}\n\nexport interface EmbeddingsOptions {\n input: string | string[];\n model?: string;\n dimensions?: number;\n signal?: AbortSignal;\n}\n\nexport class Codai {\n readonly http: HttpClient;\n\n /** Resource group (`chat.completions.create/stream`) that is also callable with the 0.2.x `chat({ messages })` shape. */\n readonly chat: Chat & ((opts: ChatOptions) => Promise<ChatResult>);\n readonly messages: Messages;\n readonly responses: Responses;\n readonly embeddings: Embeddings &\n ((opts: EmbeddingsOptions) => Promise<{ embeddings: number[][]; raw: unknown }>);\n /** Image generation and editing (`images.generate({ prompt })`, `images.edit({ prompt, image })`; codai-image = gemini-3.1-flash-image, EU). */\n readonly images: Images;\n readonly audio: Audio;\n /** codai Studio music (`music.generate({ prompt, lyrics?, model? })`; Lyria 3 clip / pro with vocals, Lyria 2 legacy; US-only). */\n readonly music: Music;\n /** codai Studio video jobs (`videos.generate({ prompt })`; Veo 3.1 Fast, US-only, English prompts). */\n readonly videos: Videos;\n /** codai Studio renders (`renders.render({ html })`; HyperFrames HTML → MP4, codai-render, up to 180 s 1080p). */\n readonly renders: Renders;\n /** Stored codai Studio assets (`assets.list()`, `.retrieve(id)`, `.contentUrl(id)`, `.delete(id)`; 1 h signed URLs, kept 90 days). */\n readonly assets: Assets;\n /** codai Studio CC0 sound effects (`sfx.search({ q })`, `sfx.import(sfxId)` → asset `kind: 'sfx'`; free). */\n readonly sfx: Sfx;\n /** codai Studio documents (`documents.create({ type: 'deck', spec })` → PPTX / DOCX / XLSX, codai-docs, free; previews + deck → MP4). */\n readonly documents: Documents;\n /** codai Studio creatives (`creatives.create({ kind: 'video' })`, `.edit(id, { baseSeq, ops })`, `.render(id)`; editable documents with versions, free except renders). */\n readonly creatives: Creatives;\n /** codai Studio brand kits (`brandKits.extract({ url })` → palette + fonts + logo; apply with `creatives.create({ kind, brand_kit_id })`). */\n readonly brandKits: BrandKits;\n /** codai Studio templates (`creatives.saveTemplate(id, { vars })` saves one; `templates.list()`; create with `creatives.create({ kind, template, vars })`). */\n readonly templates: Templates;\n /** codai Studio productions (`productions.run({ brief, language: 'ro' })` → a finished promo video + editable creative). */\n readonly productions: Productions;\n /** codai Studio media operations (`mediaOps.run('audio.separate_stems', { assetIds })` → job; `mediaOps.wait(id)`). */\n readonly mediaOps: MediaOps;\n /** codai Studio lyrics (`lyrics.write({ brief, language: 'ro' })`, `lyrics.align({ creative_id, clip_id, lyrics_text })`). */\n readonly lyrics: LyricsResource;\n /** codai Studio live jam over WebSocket (`jam.connect({ token })` → PCM16 48 kHz stereo; `prompts`, `config`, `play`). */\n readonly jam: Jam;\n /** codai Studio FCPXML exports (`creatives.exportFcpxml(id)` queues one; `exports.wait(id)` polls until the zip is ready). */\n readonly exports: Exports;\n /** codai Studio batches (`batches.create({ source: { template_id }, csv })` → one creative per row; `batches.wait(id)`). */\n readonly batches: Batches;\n /** codai Studio share links from the outside (`shares.get(url)`, `shares.remix(url)`, `shares.comment(url, …)`). */\n readonly shares: Shares;\n /** Public takedown tickets for voices cloned in codai Studio (`voiceRevocations.create({ email, … })`; no key needed). */\n readonly voiceRevocations: VoiceRevocations;\n /** Zero-knowledge credentials vault (`vault.items()`, `vault.use({ handle, mode, action })`, `vault.decide(id, …)`). */\n readonly vault: Vault;\n /** Public abuse reports about codai Studio share / review links (`abuseReports.create({ share_token, … })`; no key needed). */\n readonly abuseReports: AbuseReports;\n /** Public AI-provenance checker (`provenance.check(file)` → C2PA / RIFF INFO / ID3 / MP4 / XMP marks; no key needed). */\n readonly provenance: Provenance;\n /** Typed decisions from codai-s1 (`systemOne.create({ state, questions })`). */\n readonly systemOne: SystemOne;\n readonly tokens: Tokens;\n /** WebSocket realtime sessions (`realtime.connect({ model, language, token })`) — live STT and voice. */\n readonly realtime: Realtime;\n readonly models: Models & (() => Promise<Array<{ id: string }>>);\n readonly health: Health;\n readonly agents: Agents;\n readonly tools: Tools;\n /** Async deep research (`research.run({ question })` → cited report + sources). */\n readonly research: Research;\n /** Typed card data (`cards.weather({ lat, lng })`, `.places({ q })`, `.fx()`, `.unfurl(url)` → `{ block, provenance }`). */\n readonly cards: Cards;\n readonly tasks: Tasks;\n /** Event triggers — webhooks that notify you or start agent sessions. */\n readonly triggers: Triggers;\n /** Inbox of trigger / cloud-task notifications. */\n readonly notifications: Notifications;\n /** Pending prompts — ready-to-paste prompts left for a future chat (handoffs, dated follow-ups). */\n readonly prompts: Prompts;\n /** codai Scheduler — cron / natural-language schedules run on any of your hosts or in the cloud (`schedules.create`, `.executor.claim`). */\n readonly schedules: Schedules;\n /** Lists and the share sheet — save links, text and media to Inbox / Wishlist / Notes or your own lists (`lists.share`). */\n readonly lists: Lists;\n /** Heartbeat monitors — dead-man switches for crons codai does not run (`heartbeats.create({ name, period_s })` → `ping_url`). */\n readonly heartbeats: Heartbeats;\n /** Transcripts — voice recordings → diarized transcripts + insights (feature-flagged per account). */\n readonly transcripts: Transcripts;\n /** Your own usage split by day / key / device / app / platform / model / client / tag. */\n readonly usage: Usage;\n /** Your API keys (device attribution, tags). */\n readonly keys: Keys;\n /** Your persistent memory — the same store as the MCP memory tools (`memory.list/search/create/delete`). */\n readonly memory: Memory;\n readonly sessions: Sessions;\n readonly devices: Devices;\n readonly hosts: Hosts;\n readonly orgs: Orgs;\n readonly projects: Projects;\n readonly environments: Environments;\n /** Agent sandboxes (backend v2 by default) — isolated gVisor workspaces: `sandboxes.create/exec/execStream/files/artifacts/run`. */\n readonly sandboxes: Sandboxes;\n /** EXPERIMENTAL (HIDE, unaudited): verify signed agent outputs. Provenance only. */\n readonly verify: Verify;\n readonly account: Account;\n /** Account-level settings shared by every device (`settings.get()`, `settings.update(partial, { version })`). */\n readonly settings: Settings;\n /** OS protection gate: `osGate.policy()` (org override policy) and `osGate.recordEvent(event)` (audit). */\n readonly osGate: OsGate;\n /** READ-ONLY billing: plan, wallet, invoices, `watchBalance` (pay via the returned links, never via the SDK). */\n readonly billing: Billing;\n /** Referral stats and invitees; `redeem(code)` / `setConsent(bool)` go through `PATCH /v1/account`. */\n readonly referrals: Referrals;\n readonly receipt: Receipts;\n readonly feedback: Feedback &\n ((requestId: string, rating: 1 | -1, comment?: string) => Promise<void>);\n readonly phoneModels: PhoneModels;\n /** codai Resolve — execution-verified bug fixes (separate host, `resolveBaseUrl`). */\n readonly resolve: Resolve;\n\n constructor(opts: CodaiClientOptions) {\n if (!opts.apiKey) throw new Error('Codai: apiKey is required');\n this.http = new HttpClient({\n apiKey: opts.apiKey,\n baseUrl: opts.baseUrl ?? 'https://ai.codai.ro',\n timeoutMs: opts.timeoutMs ?? 120_000,\n maxRetries: opts.maxRetries ?? 2,\n fetch: opts.fetch,\n defaults: {\n ...opts.defaults,\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.device ? { device: opts.device } : {}),\n ...(opts.deviceName ? { deviceName: opts.deviceName } : {}),\n ...(opts.devicePlatform ? { devicePlatform: opts.devicePlatform } : {}),\n ...(opts.client ? { client: opts.client } : {}),\n },\n });\n const http = this.http;\n\n this.messages = new Messages(http);\n this.responses = new Responses(http);\n this.images = new Images(http);\n this.audio = new Audio(http);\n this.music = new Music(http);\n this.videos = new Videos(http);\n this.renders = new Renders(http);\n this.assets = new Assets(http);\n this.sfx = new Sfx(http);\n this.documents = new Documents(http);\n this.creatives = new Creatives(http);\n this.brandKits = new BrandKits(http);\n this.templates = new Templates(http);\n this.productions = new Productions(http);\n this.mediaOps = new MediaOps(http);\n this.lyrics = new LyricsResource(http);\n this.jam = new Jam({ baseUrl: http.baseUrl, apiKey: opts.apiKey });\n this.exports = new Exports(http);\n this.batches = new Batches(http);\n this.shares = new Shares(http);\n this.voiceRevocations = new VoiceRevocations(http);\n this.vault = new Vault(http);\n this.abuseReports = new AbuseReports(http);\n this.provenance = new Provenance(http);\n this.systemOne = new SystemOne(http);\n this.tokens = new Tokens(http);\n this.realtime = new Realtime({ baseUrl: http.baseUrl, apiKey: opts.apiKey });\n this.health = new Health(http);\n this.agents = new Agents(http);\n this.tools = new Tools(http);\n this.research = new Research(http);\n this.cards = new Cards(http);\n this.tasks = new Tasks(http);\n this.triggers = new Triggers(http);\n this.notifications = new Notifications(http);\n this.prompts = new Prompts(http);\n this.schedules = new Schedules(http);\n this.lists = new Lists(http);\n this.heartbeats = new Heartbeats(http);\n this.transcripts = new Transcripts(http);\n this.usage = new Usage(http);\n this.keys = new Keys(http);\n this.memory = new Memory(http);\n this.sessions = new Sessions(http);\n this.devices = new Devices(http);\n this.hosts = new Hosts(http);\n this.orgs = new Orgs(http);\n this.projects = new Projects(http);\n this.environments = new Environments(http);\n this.sandboxes = new Sandboxes(http);\n this.verify = new Verify(http);\n this.account = new Account(http);\n this.settings = new Settings(http);\n this.osGate = new OsGate(http);\n this.billing = new Billing(http);\n this.referrals = new Referrals(http);\n this.receipt = new Receipts(http);\n this.phoneModels = new PhoneModels(http);\n this.resolve = new Resolve(\n new HttpClient({\n apiKey: opts.apiKey,\n baseUrl: opts.resolveBaseUrl ?? 'https://resolve.codai.ro',\n timeoutMs: opts.timeoutMs ?? 120_000,\n maxRetries: opts.maxRetries ?? 2,\n fetch: opts.fetch,\n defaults: opts.client ? { client: opts.client } : {},\n }),\n );\n\n // Callable resources keep the 0.2.x top-level signatures working\n // (`client.embeddings({...})`, `client.models()`, `client.feedback(id, 1)`)\n // while also exposing `.create()` / `.list()` / `.submit()`.\n this.chat = callable(new Chat(http), (o: ChatOptions) =>\n this.chat.completions.create(this.legacyBody(o), {\n ext: this.legacyExt(o),\n signal: o.signal,\n }),\n );\n this.embeddings = callable(new Embeddings(http), async (o: EmbeddingsOptions) => {\n const r = await this.embeddings.create(\n { input: o.input, model: o.model, dimensions: o.dimensions },\n { signal: o.signal },\n );\n return { embeddings: r.embeddings, raw: r.raw };\n });\n this.models = callable(new Models(http), async () =>\n (await this.models.list()).map((m) => ({ id: m.id })),\n );\n this.feedback = callable(\n new Feedback(http),\n async (requestId: string, rating: 1 | -1, comment?: string) => {\n await this.feedback.submit({\n event_id: requestId,\n rating,\n ...(comment ? { comment } : {}),\n });\n },\n );\n }\n\n // ------------------------------------------------- 0.2.x compatibility aliases\n\n /** Alias of `chat.completions.stream()` with the 0.2.x option names. */\n chatStream(opts: ChatOptions): ChatStream {\n return this.chat.completions.stream(this.legacyBody(opts), {\n ext: this.legacyExt(opts),\n signal: opts.signal,\n });\n }\n\n /** Alias of `tokens.create()`. */\n mintToken(scope: EphemeralScope, ttlSeconds?: number): Promise<EphemeralToken> {\n return this.tokens.create(scope, ttlSeconds);\n }\n\n private legacyBody(opts: ChatOptions): ChatCompletionInput {\n return {\n model: opts.model ?? 'codai',\n messages: opts.messages,\n ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),\n ...(opts.maxTokens !== undefined ? { max_tokens: opts.maxTokens } : {}),\n ...(opts.tools ? { tools: opts.tools } : {}),\n };\n }\n\n private legacyExt(opts: ChatOptions): CodaiRequestExtensions {\n return {\n ...opts.ext,\n ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),\n ...(opts.agentMode ? { mode: 'agent' as const } : {}),\n ...(opts.compact ? { compact: opts.compact } : {}),\n ...(opts.bestOf !== undefined ? { bestOf: opts.bestOf } : {}),\n ...(opts.agentId ? { agentId: opts.agentId } : {}),\n };\n }\n}\n\n/**\n * Make an object callable: returns a function that forwards calls to `fn`\n * and carries every own/prototype member of `target` (methods bound).\n */\nfunction callable<T extends object, F extends (...args: never[]) => unknown>(\n target: T,\n fn: F,\n): T & F {\n const f = ((...args: Parameters<F>) => fn(...args)) as T & F;\n for (const key of allKeys(target)) {\n const value = (target as Record<string, unknown>)[key];\n Object.defineProperty(f, key, {\n value:\n typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value,\n enumerable: true,\n writable: false,\n });\n }\n return f;\n}\n\nfunction allKeys(obj: object): string[] {\n const keys = new Set<string>();\n let cur: object | null = obj;\n while (cur && cur !== Object.prototype) {\n for (const k of Object.getOwnPropertyNames(cur)) if (k !== 'constructor') keys.add(k);\n cur = Object.getPrototypeOf(cur);\n }\n return [...keys];\n}\n\nexport default Codai;\n\n// ------------------------------------------------------------------ exports\nexport { CodaiError, HttpClient, extensionHeaders, readSse, frameJson } from './http';\nexport type { CodaiRequestExtensions, ErrorCode, SseFrame, RequestOptions } from './http';\nexport { OPERATION_METHODS, STREAMING_OPERATIONS, RESOLVE_OPERATION_METHODS } from './operations';\nexport type { paths, components, operations } from './generated/gateway';\nexport type {\n paths as ResolvePaths,\n components as ResolveComponents,\n operations as ResolveOperations,\n} from './generated/resolve';\n\nexport * from './resources/chat';\nexport * from './resources/messages';\nexport * from './resources/responses';\nexport * from './resources/embeddings';\nexport * from './resources/images';\nexport * from './resources/audio';\nexport * from './resources/media';\nexport * from './resources/assets';\nexport * from './resources/sfx';\nexport * from './resources/documents';\nexport * from './resources/creatives';\nexport * from './resources/brand-kits';\nexport * from './resources/templates';\nexport * from './resources/productions';\nexport * from './resources/media-ops';\nexport * from './resources/lyrics';\nexport * from './resources/jam';\nexport * from './resources/exports';\nexport * from './resources/batches';\nexport * from './resources/shares';\nexport * from './resources/voice-revocations';\nexport * from './resources/vault';\nexport * from './resources/abuse-reports';\nexport * from './resources/provenance';\nexport * from './resources/tokens';\nexport * from './resources/realtime';\nexport * from './resources/system-one';\nexport * from './resources/models';\nexport * from './resources/health';\nexport * from './resources/agents';\nexport * from './resources/tools';\nexport * from './resources/research';\nexport * from './resources/cards';\nexport * from './resources/tasks';\nexport * from './resources/triggers';\nexport * from './resources/prompts';\nexport * from './resources/schedules';\nexport * from './resources/lists';\nexport * from './resources/transcripts';\nexport * from './resources/usage-keys';\nexport * from './resources/memory';\nexport * from './resources/sessions';\nexport * from './resources/devices';\nexport * from './resources/hosts';\nexport * from './resources/orgs';\nexport * from './resources/projects';\nexport * from './resources/environments';\nexport * from './resources/sandboxes';\nexport * from './resources/verify';\nexport * from './resources/account';\nexport * from './resources/settings';\nexport * from './resources/os-gate';\nexport * from './resources/billing';\nexport * from './resources/referrals';\nexport * from './resources/resolve';\nexport * from './resources/apps';\n"],"mappings":";AAWA,IAAa,aAAb,cAAgC,MAAM;CAUlB;CACA;;CATlB,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YACE,SACA,AAAgB,QAChB,AAAgB,MAChB,OAA2F,CAAC,GAC5F;EACA,MAAM,OAAO;EAJG;EACA;EAIhB,KAAK,OAAO;EACZ,KAAK,OAAO,KAAK,QAAQ,YAAY,IAAI;EACzC,KAAK,YAAY,KAAK,aAAa;EACnC,KAAK,aAAa,KAAK,cAAc;CACvC;AACF;AAEA,SAAS,YAAY,MAAiC;CACpD,IAAI,QAAQ,OAAO,SAAS,UAAU;EACpC,MAAM,MAAO,KAAwC;EACrD,IAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,IAAI,SAAS,UACxD,OAAO,IAAI;CACf;CACA,OAAO;AACT;AAEA,SAAS,eAAe,MAA8B;CACpD,IAAI,QAAQ,OAAO,SAAS,UAAU;EACpC,MAAM,MAAO,KAA2C;EACxD,IAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,IAAI,YAAY,UAAU,OAAO,IAAI;CACpF;CACA,OAAO;AACT;AAEA,MAAM,4BAAY,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAmGnD,MAAM,oBAAsF;CAC1F,WAAW;CACX,WAAW;CACX,QAAQ;CACR,UAAU;CACV,gBAAgB;CAChB,aAAa;CACb,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,aAAa;CACb,cAAc;CACd,QAAQ;CACR,WAAW;CACX,UAAU;CACV,YAAY;CACZ,YAAY;CACZ,MAAM;CACN,SAAS;CACT,kBAAkB;CAClB,MAAM;CACN,aAAa;CACb,aAAa;CACb,SAAS;CACT,QAAQ;CACR,aAAa;CACb,SAAS;CACT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