@m8tes/sdk 0.1.0-alpha.2 → 0.1.0-alpha.4

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http.ts","../src/pagination.ts","../src/params.ts","../src/resources/agents.ts","../src/resources/apps.ts","../src/resources/account.ts","../src/resources/users.ts","../src/resources/billing.ts","../src/resources/memories.ts","../src/resources/models.ts","../src/resources/model-connections.ts","../src/resources/permissions.ts","../src/mime.ts","../src/polling.ts","../src/streaming.ts","../src/resources/runs.ts","../src/resources/settings.ts","../src/resources/tasks.ts","../src/resources/webhooks.ts","../src/index.ts"],"names":["now"],"mappings":";;;;;AAkCO,IAAM,gBAAA,GAAmB;AAEhC,IAAM,YAAA,GAAe,CAAA;AACrB,IAAM,kBAAA,GAAqB,GAAA;AAC3B,IAAM,gBAAA,uBAAuB,GAAA,CAAI,CAAC,KAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAG,CAAC,CAAA;AAC1D,IAAM,kBAAA,uBAAyB,GAAA,CAAI,CAAC,OAAO,MAAA,EAAQ,KAAA,EAAO,QAAA,EAAU,SAAS,CAAC,CAAA;AAGvE,IAAM,kBAAA,GAAqB,iBAAA;AAE3B,IAAM,aAAA,GAAgB,mBAAA;AAiB7B,IAAM,qBAAA,GAAwB;AAAA,EAC5B,aAAA;AAAA,EACA,yBAAA;AAAA,EACA,yBAAA;AAAA,EACA,qCAAA;AAAA,EACA;AACF,CAAA;AAEA,SAAS,kBAAkB,IAAA,EAAuB;AAChD,EAAA,MAAM,QAAQ,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AACpC,EAAA,OAAO,sBAAsB,IAAA,CAAK,CAAC,OAAO,EAAA,CAAG,IAAA,CAAK,KAAK,CAAC,CAAA;AAC1D;AAUA,SAAS,WAAA,CAAY,MAAA,EAAgB,IAAA,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OAAA,GAAU,qBAAA,CAAsB,IAAA,CAAK,IAAI,CAAA;AAC9C,IAAA,IAAA,CAAK,OAAA,GAAU,qBAAA,CAAsB,IAAA,CAAK,IAAI,CAAA;AAAA,EAChD;AACF","file":"index.js","sourcesContent":["/**\n * Server-side transport for the m8tes V2 API.\n *\n * SECURITY: this module holds the secret `m8_` API key and must NEVER reach a\n * browser bundle. Client-side rendering of an agent goes through\n * `@m8tes/react` + its server proxy, which keeps the key on the server. The\n * bundle-boundary test asserts `dist/protocol/index.js` contains none of this.\n *\n * Retry semantics mirror the Python SDK (`sdk/py/m8tes/_http.py`) exactly so the\n * two languages behave the same under load:\n * - 3 attempts total, 0.5s initial backoff, doubling\n * - retry only 429/500/502/503/504\n * - retry GET/HEAD/PUT/DELETE/OPTIONS always, and a POST only when it carries\n * an `Idempotency-Key`. Without one, a POST that timed out may already have\n * started a billable run, so re-sending it could double-charge; with one, the\n * server replays the run it already created, which is why the run-creating\n * calls mint a key on every request.\n * - honour `Retry-After` on 429\n */\n\nimport {\n APIError,\n errorClassForStatus,\n parseErrorEnvelope,\n parseRetryAfter,\n type ErrorFromResponseOptions,\n type M8tesApiError,\n type M8tesStreamEvent,\n type Normalizer,\n createNormalizer,\n createSseDecoder,\n} from \"./protocol/index\";\n\n/** Canonical hosted API. Includes the `/api/v2` prefix, like the Python SDK's DEFAULT_BASE_URL. */\nexport const DEFAULT_BASE_URL = \"https://api.m8tes.ai/api/v2\";\n\nconst MAX_ATTEMPTS = 3;\nconst INITIAL_BACKOFF_MS = 500;\nconst RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);\nconst IDEMPOTENT_METHODS = new Set([\"GET\", \"HEAD\", \"PUT\", \"DELETE\", \"OPTIONS\"]);\n\n/** Makes a POST safe to repeat: the server replays the run the first one created. */\nexport const IDEMPOTENCY_HEADER = \"idempotency-key\";\n/** Set by the API when a response is a replay rather than a fresh result. */\nexport const REPLAY_HEADER = \"idempotent-replay\";\n\n/**\n * The ONLY routes whose POST the server makes idempotent.\n *\n * Retry eligibility checks this as well as the header, because the header alone is\n * not evidence the server will honour it. `new M8tes({headers: {\"Idempotency-Key\":\n * …}})` sets it on EVERY request, which would make every POST retryable —\n * including `tasks.create`, which has no server-side idempotency, so a timed-out\n * create would be re-sent and duplicate the task. Found in review.\n *\n * Matched against the path RELATIVE to baseUrl, and fully anchored. An earlier\n * version matched suffixes, which also accepted `/foo/reply` and `/foo/runs` — and\n * `request()`/`raw()` are public, so an unsupported path could have been retried on\n * a route that ignores the key. Anchoring is the whole point of the check, so it\n * must not be approximate.\n */\nconst IDEMPOTENT_POST_PATHS = [\n /^\\/runs\\/?$/,\n /^\\/runs\\/with-files\\/?$/,\n /^\\/runs\\/\\d+\\/reply\\/?$/,\n /^\\/runs\\/\\d+\\/reply\\/with-files\\/?$/,\n /^\\/tasks\\/\\d+\\/runs\\/?$/,\n];\n\nfunction isIdempotentRoute(path: string): boolean {\n const clean = path.split(\"?\")[0] ?? \"\";\n return IDEMPOTENT_POST_PATHS.some((re) => re.test(clean));\n}\n\n/**\n * Whether this request may be re-sent after a timeout or 5xx.\n *\n * Mirrors `_is_retryable` in the Python SDK (`sdk/py/m8tes/_http.py`) so the two\n * languages behave identically under load. Header names are compared lowercased\n * because `mergeHeaders` normalises them — a caller writing `Idempotency-Key`\n * must get retries just like one writing `idempotency-key`.\n */\nfunction isRetryable(method: string, path: string, headers: Record<string, string>): boolean {\n if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;\n return IDEMPOTENCY_HEADER in headers && isIdempotentRoute(path);\n}\n\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\nexport interface ClientOptions {\n /** Your `m8_` key. Defaults to `process.env.M8TES_API_KEY`. */\n apiKey?: string;\n /** Override the API host. Must include the `/api/v2` prefix. */\n baseUrl?: string;\n /** Per-request timeout in ms. Default 300_000 (5 min), matching the Python SDK. */\n timeout?: number;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Pluggable fetch, for tests or a custom agent/proxy. Default `globalThis.fetch`. */\n fetch?: FetchLike;\n /** Reported (not thrown) when a stream frame is unparseable. */\n onMalformed?: (rawPayload: string, error: unknown) => void;\n}\n\nexport interface RequestOptions {\n body?: unknown;\n query?: string;\n signal?: AbortSignal;\n headers?: Record<string, string>;\n /**\n * Send as multipart/form-data instead of JSON. Used by the file-upload route.\n * `fetch` sets its own `content-type` with the boundary, so we must NOT set\n * one — a hand-written header omits the boundary and the server cannot parse\n * the body.\n */\n form?: FormData;\n}\n\nexport interface StreamRequestOptions extends RequestOptions {\n /** Reuse a normalizer across reconnects so its dedupe ledger persists. */\n normalizer?: Normalizer;\n /**\n * Called instead of decoding the body when the server answers a run-creating\n * POST with `Idempotent-Replay: true`.\n *\n * A replay is JSON (the run), not SSE — a run that already exists has no fresh\n * stream to emit — so the caller decides what to do with it, in practice\n * joining that run's own stream. It lives here rather than in the resource\n * because this is the only place the Response object exists; by the time\n * `stream()` yields, the headers are gone.\n */\n onReplay?: (run: { id: number; status: string }) => AsyncGenerator<M8tesStreamEvent, void, unknown>;\n}\n\n/**\n * Backoff that an abort cuts short. A plain `setTimeout` would keep a caller\n * waiting out the full delay after they cancelled — with `Retry-After: 3600` on\n * a 429, that is an hour of a request that nobody is waiting for any more.\n */\nfunction backoff(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n resolve();\n }\n signal?.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nfunction looksLikeHtml(res: Response, text: string): boolean {\n if ((res.headers.get(\"content-type\") ?? \"\").includes(\"text/html\")) return true;\n const head = text.trimStart().slice(0, 9).toLowerCase();\n return head.startsWith(\"<!doctype\") || head.startsWith(\"<html\");\n}\n\n/**\n * Replace the raw body with an actionable message when the response says\n * \"you are not talking to the m8tes API\" — the two mistakes that otherwise\n * surface as a baffling 404 or a wall of HTML. Ported from the Python SDK.\n */\nfunction diagnose(res: Response, text: string, body: unknown, url: string): string | undefined {\n if (looksLikeHtml(res, text)) {\n return (\n `Received an HTML page instead of an API response (HTTP ${res.status}) from ${url}. ` +\n `This usually means the host does not serve the m8tes API; check your baseUrl ` +\n `(the hosted API is ${DEFAULT_BASE_URL}).`\n );\n }\n const isBareNotFound =\n res.status === 404 &&\n body !== null &&\n typeof body === \"object\" &&\n !(\"error\" in body) &&\n (body as { detail?: unknown }).detail === \"Not Found\";\n if (isBareNotFound) {\n return (\n `HTTP 404 from ${url} with no API error envelope — the path matched no route. ` +\n `Check your baseUrl includes the /api/v2 prefix (the hosted API is ${DEFAULT_BASE_URL}).`\n );\n }\n return undefined;\n}\n\nexport interface Http {\n baseUrl: string;\n request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;\n /** The OK `Response` itself — for binary bodies (file downloads). Retries and\n * typed errors still apply; the caller owns reading the body. */\n raw(method: string, path: string, opts?: RequestOptions): Promise<Response>;\n stream(\n method: string,\n path: string,\n opts?: StreamRequestOptions,\n ): AsyncGenerator<M8tesStreamEvent, void, unknown>;\n}\n\nexport function createHttp(options: ClientOptions = {}): Http {\n // A secret `m8_` key in a browser is readable by every visitor. Bundlers do not\n // stop you importing this entry into client code, so fail loudly the moment it\n // runs there rather than shipping a leaked key quietly. (Edge/worker runtimes\n // have no `document`, so they are unaffected.)\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new Error(\n \"@m8tes/sdk is server-only: it holds your secret m8_ API key, which anyone \" +\n \"could read out of a browser bundle. To render an agent in the browser use \" +\n \"@m8tes/react, which talks to a server proxy that keeps the key on your server. \" +\n \"See https://www.m8tes.ai/docs/embed-a-ui\",\n );\n }\n const apiKey = options.apiKey ?? globalThis.process?.env?.[\"M8TES_API_KEY\"];\n if (!apiKey) {\n throw new Error(\n \"@m8tes/sdk: no API key. Pass `new M8tes({ apiKey })` or set M8TES_API_KEY. \" +\n \"Create a key at https://m8tes.ai/developer.\",\n );\n }\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const timeout = options.timeout ?? 300_000;\n const maybeFetch = options.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!maybeFetch) {\n throw new Error(\n \"@m8tes/sdk: no global fetch. Use Node 18+ or pass `fetch` in the client options.\",\n );\n }\n const fetchImpl: FetchLike = maybeFetch; // narrowed; safe to capture in closures\n\n async function toError(\n res: Response,\n url: string,\n errOpts: ErrorFromResponseOptions,\n ): Promise<M8tesApiError> {\n const text = await res.text().catch(() => \"\");\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n const parsed = parseErrorEnvelope(res.status, body, res.headers);\n const message = diagnose(res, text, body, url) ?? (body ? parsed.message : text || parsed.message);\n return new (errorClassForStatus(res.status, errOpts))(message, parsed.fields);\n }\n\n /**\n * Merge header maps case-insensitively.\n *\n * HTTP header names are case-insensitive, but a plain object is not: a caller\n * passing `Content-Type` and the SDK setting `content-type` produced BOTH, and\n * fetch joins duplicates into `application/json, application/json`, which the\n * server cannot parse. Everything is lowercased so last-writer-wins actually\n * wins.\n */\n function mergeHeaders(...sources: Array<Record<string, string> | undefined>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const src of sources) {\n for (const [k, v] of Object.entries(src ?? {})) out[k.toLowerCase()] = v;\n }\n return out;\n }\n\n /** One attempt. Layers the client timeout onto any caller-supplied signal. */\n async function attempt(method: string, url: string, opts: RequestOptions): Promise<Response> {\n // Auth LAST: a server proxy that forwards inbound request headers into\n // `headers` would otherwise silently replace the SDK's credential with a\n // client-supplied one. The key you constructed the client with always wins.\n const headers = mergeHeaders(options.headers, opts.headers, {\n authorization: `Bearer ${apiKey}`,\n });\n const init: RequestInit = { method, headers };\n if (opts.form !== undefined) {\n // Deliberately no content-type: fetch adds it WITH the multipart boundary.\n // A content-type configured globally (or per-request) would suppress that\n // header, leaving the server unable to parse the body. Keys are lowercased\n // by mergeHeaders, so one delete covers every casing the caller used.\n delete headers[\"content-type\"];\n init.body = opts.form;\n } else if (opts.body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n init.body = JSON.stringify(opts.body);\n }\n const timer = AbortSignal.timeout(timeout);\n init.signal = opts.signal ? AbortSignal.any([opts.signal, timer]) : timer;\n return fetchImpl(url, init);\n }\n\n /**\n * Retry loop shared by `request` and `stream`. Returns the OK response; throws\n * a typed error once the attempts are spent or the status is not retryable.\n */\n async function send(\n method: string,\n path: string,\n opts: RequestOptions,\n errOpts: ErrorFromResponseOptions = {},\n ): Promise<Response> {\n const url = `${baseUrl}${path}${opts.query ?? \"\"}`;\n // Same merge (and lowercasing) `attempt` applies, so this sees exactly the\n // headers that go on the wire — a key set globally on the client counts too.\n const idempotent = isRetryable(method, path, mergeHeaders(options.headers, opts.headers));\n let lastNetworkError: unknown;\n\n for (let i = 0; i < MAX_ATTEMPTS; i++) {\n const isLast = i === MAX_ATTEMPTS - 1;\n let res: Response;\n try {\n res = await attempt(method, url, opts);\n } catch (e) {\n // A caller-initiated abort is intent, not a fault — never retry or wrap it.\n if (opts.signal?.aborted) throw e;\n lastNetworkError = e;\n if (!idempotent || isLast) {\n throw new APIError(e instanceof Error ? e.message : String(e), {\n type: \"api_error\",\n code: 0,\n status: 0,\n });\n }\n await backoff(INITIAL_BACKOFF_MS * 2 ** i, opts.signal);\n if (opts.signal?.aborted) throw e;\n continue;\n }\n\n if (res.ok) return res;\n if (!RETRYABLE_STATUS.has(res.status) || !idempotent || isLast) {\n throw await toError(res, url, errOpts);\n }\n const retryAfter = res.status === 429 ? parseRetryAfter(res.headers.get(\"retry-after\")) : undefined;\n // Drain the body so the connection can be reused on the next attempt.\n await res.text().catch(() => \"\");\n await backoff(retryAfter !== undefined ? retryAfter * 1000 : INITIAL_BACKOFF_MS * 2 ** i, opts.signal);\n // The caller gave up while we were waiting — surface their abort rather\n // than burning the remaining attempts on a request nobody wants.\n if (opts.signal?.aborted) throw await toError(res, url, errOpts);\n }\n\n throw new APIError(\n lastNetworkError instanceof Error ? lastNetworkError.message : \"Max retries exceeded\",\n { type: \"api_error\", code: 0, status: 0 },\n );\n }\n\n return {\n baseUrl,\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await send(method, path, opts);\n if (res.status === 204) return undefined as T;\n const text = await res.text();\n return (text ? (JSON.parse(text) as T) : (undefined as T));\n },\n\n raw(method: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n return send(method, path, opts);\n },\n\n async *stream(method: string, path: string, opts: StreamRequestOptions = {}) {\n // A 409 on a stream route means \"the run already finished\" — surfaced as\n // RunNotStreamingError so callers fall back to runs.get() instead of\n // treating a completed run as an error.\n const res = await send(method, path, opts, { conflictIsNotStreaming: true });\n // An idempotent retry was answered from the run the first attempt created.\n // Hand it to the resource, which joins that run's stream — the caller asked\n // for a stream and still gets one, without learning a retry happened.\n if (opts.onReplay && res.headers.get(REPLAY_HEADER)) {\n const run = (await res.json()) as { id: number; status: string };\n yield* opts.onReplay(run);\n return;\n }\n if (!res.body) return;\n const normalizer = opts.normalizer ?? createNormalizer();\n const decoder = createSseDecoder({ onMalformed: options.onMalformed });\n const reader = res.body.getReader();\n const td = new TextDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n for (const frame of decoder.push(td.decode(value, { stream: true }))) {\n yield* normalizer.push(frame);\n }\n }\n for (const frame of decoder.flush()) yield* normalizer.push(frame);\n } finally {\n // cancel() tears down the connection on an early break (caller stopped\n // iterating); releaseLock() alone would leak a live SSE connection.\n try {\n await reader.cancel();\n } catch {\n try {\n reader.releaseLock();\n } catch {\n /* already released */\n }\n }\n }\n },\n };\n}\n","/**\n * Cursor pagination over the V2 `ListResponse` envelope (`{data, has_more}`).\n *\n * Mirrors the Python SDK's `SyncPage` (`sdk/py/m8tes/_types.py`): a page is the\n * raw response plus an async iterator that walks every remaining page for you.\n *\n * The cursor is the last item's `id`, or its `name` for `/apps` (the one resource\n * keyed by name). Same rule as Python, so both SDKs paginate identically.\n */\n\nexport interface ListResponse<T> {\n data: T[];\n hasMore: boolean;\n}\n\n/** A page of results. `for await (const item of page)` walks ALL pages. */\nexport class Page<T> implements ListResponse<T>, AsyncIterable<T> {\n readonly data: T[];\n readonly hasMore: boolean;\n /** Fetches the next page given a cursor. Absent on a terminal page. */\n private readonly fetchNext?: (startingAfter: string | number) => Promise<Page<T>>;\n\n constructor(\n data: T[],\n hasMore: boolean,\n fetchNext?: (startingAfter: string | number) => Promise<Page<T>>,\n ) {\n this.data = data;\n this.hasMore = hasMore;\n this.fetchNext = fetchNext;\n }\n\n /**\n * Auto-paging: yields every item across every page.\n *\n * Stops if the cursor ever fails to advance. A server that returns the same\n * page again with `has_more: true` — a caching layer, a replica lagging, a bug\n * — would otherwise spin forever, re-yielding the same rows and never\n * returning. Terminating is the only safe response: the caller gets the items\n * it did see rather than a hung process.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page: Page<T> = this;\n const seen = new Set<string | number>();\n for (;;) {\n yield* page.data;\n const last = page.data.at(-1) as { id?: unknown; name?: unknown } | undefined;\n if (!page.hasMore || !last || !page.fetchNext) return;\n const cursor =\n typeof last.id === \"number\" || typeof last.id === \"string\"\n ? last.id\n : typeof last.name === \"string\"\n ? last.name\n : undefined;\n if (cursor === undefined || seen.has(cursor)) return;\n seen.add(cursor);\n page = await page.fetchNext(cursor);\n }\n }\n\n /** Every item across every page, collected. Prefer iteration for large sets. */\n async all(): Promise<T[]> {\n const out: T[] = [];\n for await (const item of this) out.push(item);\n return out;\n }\n}\n","/**\n * Request-parameter plumbing. Deliberately tiny.\n *\n * This package speaks the API's own **snake_case** on the wire, in params AND in\n * response types — the same names as `/docs/api-reference` and the Python SDK, and\n * the convention `openai`, `stripe`, and `@anthropic-ai/sdk` all use. So there is\n * no case-mapping layer: request bodies are passed through, and responses are\n * returned exactly as the API sent them.\n *\n * That is not just a style choice. The mapping layer this replaced corrupted\n * caller-defined keys twice: `answers` is keyed by AskUserQuestion TEXT, and\n * `output_schema` carries the caller's own JSON-Schema property names — a key\n * rewriter silently changed both. With no rewriter, that class of bug cannot exist.\n *\n * THE BOUNDARY, precisely — snake_case is for API DATA, camelCase for SDK surfaces:\n *\n * snake_case request params + response bodies `user_id`, `created_at`,\n * (anything that crosses the wire) `output_data`, `enable_memory`\n *\n * camelCase things the SDK owns and the API `new M8tes({ apiKey })`,\n * never sees: client options, method `client.runs.createAsync()`,\n * names, `RunStream`, and the `stream.runId`,\n * normalized events in `event.requestId`\n * `@m8tes/sdk/protocol` (our own\n * format, shared with @m8tes/react's\n * UI — not the REST wire)\n *\n * So: if you read the name in `/docs/api-reference`, it is snake_case here too.\n * If it is a TypeScript construct we invented, it is camelCase.\n */\n\n/** Drop `undefined` so an omitted option is absent rather than an explicit\n * `null` — which the API reads as \"clear this field\". An explicit `null`\n * survives, because that IS how you clear one. */\nexport function toBody(params: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/** Query string from params, skipping `undefined`/`null`. Returns \"\" when empty. */\nexport function toQuery(params: Record<string, unknown>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v === undefined || v === null) continue;\n q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : \"\";\n}\n\n/**\n * `agent_id` is the canonical name; `teammate_id` is the permanent legacy alias\n * and the actual wire field. Passing conflicting values is an error rather than a\n * silent pick — mirrors `_resolve_agent_id` in the Python SDK.\n */\nexport function resolveAgentId(\n teammateId: number | undefined,\n agentId: number | undefined,\n): number | undefined {\n if (agentId !== undefined && teammateId !== undefined && agentId !== teammateId) {\n throw new Error(\"Pass agent_id or teammate_id, not both\");\n }\n return teammateId ?? agentId;\n}\n","/**\n * `client.agents` — the reusable agent personas runs execute as.\n *\n * The V2 resource is `agents`; `client.teammates` is a permanent alias because\n * the DB model and older API docs use that name. Mirrors\n * `sdk/py/m8tes/_resources/teammates.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { Agent, EmailInbox, JsonObject, PermissionMode, WebhookToggle } from \"../types\";\n\nexport interface AgentCreateParams {\n name?: string;\n /** The agent's standing instructions: who it is and how it works. */\n instructions?: string;\n /** Tool slugs it may use, e.g. `[\"gmail\", \"slack\"]`. */\n tools?: string[];\n role?: string;\n goals?: string;\n /** Your id for the end-user who owns this agent. */\n user_id?: string;\n metadata?: JsonObject;\n model?: string;\n effort?: string;\n default_permission_mode?: PermissionMode;\n /** Built-in tool toggles. Omit to inherit the platform default. */\n enable_memory?: boolean;\n enable_history?: boolean;\n enable_task_setup_tools?: boolean;\n enable_feedback?: boolean;\n enable_self_improvement?: boolean;\n /** Give the agent its own email inbox on create. */\n email_inbox?: boolean;\n /** Give the agent a webhook trigger URL on create. */\n webhook?: boolean;\n /** Start from a prebuilt persona, e.g. `\"ppc-manager\"`. Template improvements\n * keep flowing in on later reads unless you override the field. */\n from_template?: string;\n}\n\n/**\n * PATCH /agents/{id} accepts exactly these fields (backend `TeammateUpdate`).\n * Create-only fields are NOT here on purpose: sending `webhook` or `email_inbox`\n * to PATCH returns 200 and silently does nothing, which reads as a working call.\n * Use `enableWebhook()` / `enableEmailInbox()` instead.\n *\n * `null` is meaningful: it CLEARS the field back to the platform default.\n */\nexport interface AgentUpdateParams {\n name?: string | null;\n instructions?: string | null;\n tools?: string[] | null;\n role?: string | null;\n goals?: string | null;\n metadata?: JsonObject | null;\n model?: string | null;\n effort?: string | null;\n default_permission_mode?: PermissionMode | null;\n allowed_senders?: string[] | null;\n enable_memory?: boolean | null;\n enable_history?: boolean | null;\n enable_task_setup_tools?: boolean | null;\n enable_feedback?: boolean | null;\n enable_self_improvement?: boolean | null;\n}\n\nexport interface AgentListParams {\n user_id?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface AgentsResource {\n create(params?: AgentCreateParams): Promise<Agent>;\n list(params?: AgentListParams): Promise<Page<Agent>>;\n get(agentId: number, params?: { user_id?: string }): Promise<Agent>;\n update(agentId: number, params: AgentUpdateParams & { user_id?: string }): Promise<Agent>;\n delete(agentId: number, params?: { user_id?: string }): Promise<void>;\n /** Turn on the webhook trigger; returns the URL to POST to.\n * `user_id` scopes to one end-user (404 on mismatch), like get/update/delete. */\n enableWebhook(agentId: number, params?: { user_id?: string }): Promise<WebhookToggle>;\n disableWebhook(agentId: number, params?: { user_id?: string }): Promise<void>;\n /** Turn on the agent's email inbox; returns the address that starts runs. */\n enableEmailInbox(agentId: number, params?: { user_id?: string }): Promise<EmailInbox>;\n disableEmailInbox(agentId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createAgentsResource(http: Http): AgentsResource {\n return {\n create(params = {}) {\n return http.request<Agent>(\"POST\", \"/agents/\", { body: toBody({ ...params }) });\n },\n\n async list(params = {}) {\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<Agent>> => {\n const res = await http.request<{ data: Agent[]; has_more?: boolean }>(\"GET\", \"/agents/\", {\n query: toQuery(p),\n });\n return new Page<Agent>(res?.data ?? [], res?.has_more ?? false, (starting_after) =>\n fetchPage({ ...p, starting_after }),\n );\n };\n return fetchPage({ ...params });\n },\n\n get(agentId, params = {}) {\n return http.request<Agent>(\"GET\", `/agents/${seg(agentId)}`, { query: toQuery(params) });\n },\n\n update(agentId, params) {\n // user_id scopes the request (query param); everything else is the patch.\n const { user_id, ...patch } = params;\n return http.request<Agent>(\"PATCH\", `/agents/${seg(agentId)}`, {\n body: toBody(patch),\n query: toQuery({ user_id }),\n });\n },\n\n async delete(agentId, params = {}) {\n await http.request(\"DELETE\", `/agents/${seg(agentId)}`, { query: toQuery(params) });\n },\n\n enableWebhook(agentId, params = {}) {\n return http.request<WebhookToggle>(\"POST\", `/agents/${seg(agentId)}/webhook`, {\n body: {},\n query: toQuery(params),\n });\n },\n\n async disableWebhook(agentId, params = {}) {\n await http.request(\"DELETE\", `/agents/${seg(agentId)}/webhook`, { query: toQuery(params) });\n },\n\n enableEmailInbox(agentId, params = {}) {\n return http.request<EmailInbox>(\"POST\", `/agents/${seg(agentId)}/email-inbox`, {\n body: {},\n query: toQuery(params),\n });\n },\n\n async disableEmailInbox(agentId, params = {}) {\n await http.request(\"DELETE\", `/agents/${seg(agentId)}/email-inbox`, { query: toQuery(params) });\n },\n };\n}\n","/**\n * `client.apps` — the tools agents act in, and each end-user's connections to them.\n *\n * Connections are scoped: pass `user_id` and the connection belongs to that\n * end-user, so the agent acts with THEIR Gmail/Stripe/Slack rather than yours.\n * In an embed that matters a lot — an account-level connection means a\n * prompt-injected agent could act on your behalf.\n *\n * Mirrors `sdk/py/m8tes/_resources/apps.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { App, AppConnectionInitiation, AppConnectionResult } from \"../types\";\n\nexport interface AppsResource {\n /**\n * Every available tool, with connection status for the given scope.\n *\n * NOT paginated and NOT cursor-able: `GET /apps/` accepts only `user_id` and\n * returns the whole catalog. Sending `limit` or `starting_after` gets a 422\n * (`unknown_query_parameter`) — verified against a live backend, which is also\n * how the same bug was found in the published Python SDK. A `Page` is still\n * returned so `for await` works uniformly across resources.\n */\n list(params?: { user_id?: string }): Promise<Page<App>>;\n /** True when this app is connected for the given scope. */\n isConnected(appName: string, params?: { user_id?: string }): Promise<boolean>;\n /**\n * Start an OAuth connection. Send the user to the returned `authorization_url`,\n * then pass the returned `connection_id` to `connectComplete()`.\n *\n * `redirect_uri` is REQUIRED and is spelled `_uri`, not `_url` — the API 422s\n * on anything else.\n */\n connectOauth(\n appName: string,\n params: { redirect_uri: string; user_id?: string },\n ): Promise<AppConnectionInitiation>;\n /** Connect an app that authenticates with a key instead of OAuth. */\n connectApiKey(\n appName: string,\n params: { api_key: string; user_id?: string },\n ): Promise<AppConnectionResult>;\n /** Finish an OAuth connection after the user returns. `connection_id` comes\n * from `connectOauth()` and is required. */\n connectComplete(\n appName: string,\n params: { connection_id: string; user_id?: string },\n ): Promise<AppConnectionResult>;\n disconnect(appName: string, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createAppsResource(http: Http): AppsResource {\n // A local, not `this.list` — a destructured `const { isConnected } =\n // client.apps` would otherwise throw. (The same bug shipped in\n // `runs.createAndWait`; nothing in this package should depend on `this`.)\n const list = async (params: { user_id?: string } = {}): Promise<Page<App>> => {\n // Only `user_id` — see the interface comment. No fetchNext: there is no\n // cursor to follow, and inventing one would 422.\n const res = await http.request<{ data: App[]; has_more?: boolean }>(\"GET\", \"/apps/\", {\n query: toQuery({ user_id: params.user_id }),\n });\n return new Page<App>(res?.data ?? [], res?.has_more ?? false);\n };\n\n return {\n list,\n\n async isConnected(appName, params = {}) {\n // The list endpoint reports connection state per scope; a single-app filter\n // would be a second contract to keep in sync for no gain.\n const { data } = await list(params);\n return data.find((a) => a.name === appName)?.connected ?? false;\n },\n\n connectOauth(appName, params) {\n return http.request<AppConnectionInitiation>(\"POST\", `/apps/${seg(appName)}/connect`, {\n body: toBody({ ...params }),\n });\n },\n\n connectApiKey(appName, params) {\n return http.request<AppConnectionResult>(\"POST\", `/apps/${seg(appName)}/connect/api-key`, {\n body: toBody({ ...params }),\n });\n },\n\n connectComplete(appName, params) {\n return http.request<AppConnectionResult>(\"POST\", `/apps/${seg(appName)}/connect/complete`, {\n body: toBody({ ...params }),\n });\n },\n\n async disconnect(appName, params = {}) {\n await http.request(\"DELETE\", `/apps/${seg(appName)}/connections`, { query: toQuery(params) });\n },\n };\n}\n","/**\n * `client.account` — the two operations that act on the whole account rather\n * than anything inside it: take your data out, and shut the account down.\n *\n * Both exist to satisfy the GDPR/CCPA rights to access and to erasure, so they\n * are here for compliance flows you have to be able to run programmatically —\n * a data-subject request you are forwarding, or an offboarding path in your own\n * product. Neither takes parameters: they always apply to the account behind\n * the API key you authenticated with, and there is no `user_id` scoping. To\n * remove one end-user's data instead, use `client.users.delete()`.\n *\n * Mirrors `sdk/py/m8tes/_resources/account.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { AccountDeletion, AccountExport } from \"../types\";\n\nexport interface AccountResource {\n /**\n * Hand a customer (or a regulator) everything the account holds — the\n * GDPR/CCPA right to access.\n *\n * The document covers the account's agents, tasks, runs, documents, memories,\n * and integration metadata. Credentials and other secrets are never included,\n * so an export is safe to forward but is NOT a backup you can restore from.\n * It is a single JSON body, not a stream: a large account produces a large\n * response, so allow for it in your request timeout.\n */\n export(): Promise<AccountExport>;\n\n /**\n * Close the account — the GDPR/CCPA right to erasure.\n *\n * Soft-delete, and it takes effect at once: sessions and the API key are\n * revoked, billing is canceled, and all automation stops, with the data\n * erased after a grace period. In other words the key you just called this\n * with is dead afterwards, so nothing else in the SDK will work.\n */\n delete(): Promise<AccountDeletion>;\n}\n\nexport function createAccountResource(http: Http): AccountResource {\n return {\n export() {\n return http.request<AccountExport>(\"GET\", \"/account/export\");\n },\n\n delete() {\n return http.request<AccountDeletion>(\"DELETE\", \"/account\");\n },\n };\n}\n","/**\n * `client.users` — your end-users, the multi-tenancy boundary.\n *\n * `user_id` is YOUR identifier for a customer; the platform stores it as\n * `end_user_id` and isolates that person's memory, run history, and tool\n * connections strictly. There is no fallback to account-level data.\n *\n * Registering an end-user here is optional — passing `user_id` on a run creates\n * them implicitly. Do it explicitly when you want per-user budgets and rate\n * limits. Mirrors `sdk/py/m8tes/_resources/users.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { EndUser, EndUserUsage, JsonObject } from \"../types\";\n\nexport interface EndUserCreateParams {\n /** Your id for this person. Any stable string. */\n user_id: string;\n name?: string;\n email?: string;\n company?: string;\n metadata?: JsonObject;\n /** Cap this end-user's runs per billing period. */\n run_limit?: number;\n /** Cap this end-user's spend per billing period, in cents. */\n cost_limit_cents?: number;\n /** Cap this end-user's runs per minute. Exceeding it returns 429. */\n rate_per_minute?: number;\n}\n\n/** `null` CLEARS a cap (inherit the account default); omitting leaves it alone. */\nexport interface EndUserUpdateParams {\n name?: string | null;\n email?: string | null;\n company?: string | null;\n metadata?: JsonObject | null;\n run_limit?: number | null;\n cost_limit_cents?: number | null;\n rate_per_minute?: number | null;\n}\n\nexport interface PageParams {\n limit?: number;\n starting_after?: number;\n}\n\nexport interface UsersResource {\n create(params: EndUserCreateParams): Promise<EndUser>;\n list(params?: PageParams): Promise<Page<EndUser>>;\n get(userId: string): Promise<EndUser>;\n update(userId: string, params: EndUserUpdateParams): Promise<EndUser>;\n delete(userId: string): Promise<void>;\n /** Per-end-user token, run, and cost usage against their limits. */\n usage(params?: PageParams & { user_id?: string }): Promise<Page<EndUserUsage>>;\n}\n\n/** Shared cursor-paging helper: the envelope is identical across list routes. */\nexport function pager<T>(http: Http, path: string): (p: Record<string, unknown>) => Promise<Page<T>> {\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<T>> => {\n const res = await http.request<{ data: T[]; has_more?: boolean }>(\"GET\", path, {\n query: toQuery(p),\n });\n return new Page<T>(res?.data ?? [], res?.has_more ?? false, (starting_after) =>\n fetchPage({ ...p, starting_after }),\n );\n };\n return fetchPage;\n}\n\nexport function createUsersResource(http: Http): UsersResource {\n return {\n create(params) {\n return http.request<EndUser>(\"POST\", \"/users/\", { body: toBody({ ...params }) });\n },\n\n list(params = {}) {\n return pager<EndUser>(http, \"/users/\")({ ...params });\n },\n\n get(userId) {\n return http.request<EndUser>(\"GET\", `/users/${seg(userId)}`);\n },\n\n update(userId, params) {\n return http.request<EndUser>(\"PATCH\", `/users/${seg(userId)}`, {\n body: toBody({ ...params }),\n });\n },\n\n async delete(userId) {\n await http.request(\"DELETE\", `/users/${seg(userId)}`);\n },\n\n usage(params = {}) {\n return pager<EndUserUsage>(http, \"/usage/end-users\")({ ...params });\n },\n };\n}\n","/**\n * `client.billing` — what you have spent, what you may spend, and the ceiling.\n *\n * This is the resource you reach for when cost is a product requirement rather\n * than an afterthought: read current-period usage (runs, model spend, accrued\n * overage), break spend down by day / end-user / agent / model, fetch the public\n * plan catalog, and set the caps — the monthly overage cap on plan accounts, and\n * on prepaid accounts the token balance, top-ups, auto-reload, and the\n * low-balance alert threshold.\n *\n * An embed developer capping what their own customers can burn lives here: pair\n * `usageTimeseries({ user_id })` with the per-end-user limits on `client.users`\n * to meter each tenant, and `setOverage` / `setAutoReload` to bound the account\n * as a whole.\n *\n * Mirrors `sdk/py/m8tes/_resources/billing.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { resolveAgentId, toBody, toQuery } from \"../params\";\nimport type { Balance, Plan, Receipt, Usage, UsageTimeseries } from \"../types\";\nimport { type PageParams, pager } from \"./users\";\n\nexport interface UsageTimeseriesParams {\n /** Inclusive ISO date (`\"2026-07-01\"`), UTC days. Defaults to 30 days ago. */\n start_date?: string;\n /** Inclusive ISO date. Defaults to today. */\n end_date?: string;\n /** Scope to one end-user. */\n user_id?: string;\n /** Scope to one agent. */\n agent_id?: number;\n /** Permanent legacy alias for `agent_id` — the same wire field. */\n teammate_id?: number;\n /** Creation stamp: `\"api\"` embedding, `\"platform\"` first-party. Not settlement. */\n surface?: \"api\" | \"platform\";\n /** Where the run settled: `\"wallet\"` is the prepaid ledger. */\n settled_meter?: \"wallet\" | \"plan\" | \"released\" | \"own_sub\";\n /** `\"model\"` adds per-model slices to every bucket's `models`. The route\n * accepts this one value only, so it is a literal rather than a string. */\n group_by?: \"model\";\n}\n\nexport interface OverageParams {\n enabled: boolean;\n /** Hard ceiling on overage spend per period, in cents. */\n monthly_cap_cents: number;\n}\n\nexport interface TopupParams {\n /** Cents to add. $5 minimum, $1M maximum. */\n amount_cents: number;\n}\n\n/**\n * Enabling auto-reload REQUIRES both amounts; disabling takes neither. Modelled\n * as a union so `{ enabled: true }` alone is a compile error rather than a 422.\n */\nexport type AutoReloadParams =\n | {\n enabled: true;\n /** Reload when the balance drops below this, in cents. */\n threshold_cents: number;\n /** Cents to charge per reload. $5–$10,000. */\n amount_cents: number;\n }\n | {\n enabled: false;\n /** Amounts may still be updated while disabled; the API applies them. */\n threshold_cents?: number;\n amount_cents?: number;\n };\n\nexport interface AlertThresholdParams {\n /** Balance (cents) at which the low-balance warning fires. `0` warns only on depletion. */\n low_balance_threshold_cents: number;\n}\n\nexport interface BillingResource {\n /** Where you stand this period: plan, runs used vs included, model spend, and overage state. */\n usage(): Promise<Usage>;\n\n /**\n * Spend broken down by UTC day — the series to chart, alert on, or reconcile\n * against an invoice. Buckets are zero-filled across the whole window, so the\n * array is safe to plot without gap-handling. Cost matches `usage().cost_used`\n * semantics, so the series always reconciles with period totals. With\n * `group_by: \"model\"`, runs that predate model attribution fold\n * into a `\"unknown\"` slice rather than disappearing.\n */\n usageTimeseries(params?: UsageTimeseriesParams): Promise<UsageTimeseries>;\n\n /**\n * Proof of payment for finance: one row per paid prepaid top-up, newest first.\n * `receipt_url` can be `null` when Stripe can no longer retrieve the session.\n */\n receipts(params?: PageParams): Promise<Page<Receipt>>;\n\n /** What the paid plans include and cost — for your own pricing page or upgrade\n * prompt. Public (paid) plans only, straight from the canonical catalog, and\n * returned as a plain array rather than a page. */\n plans(): Promise<Plan[]>;\n\n /**\n * Decide whether runs may continue past your plan's included allotment, and how\n * far. Off by default; once enabled, extra runs bill at the per-run overage rate\n * until `monthly_cap_cents` is reached. Returns the refreshed usage so you can\n * confirm the new state without a second call.\n */\n setOverage(params: OverageParams): Promise<Usage>;\n\n /** How much prepaid credit is left, and where it went (prepaid-billed accounts).\n * Amounts are micro-USD; `balance_usd` is a rounded display string. */\n balance(): Promise<Balance>;\n\n /**\n * Add credit when a human is present to pay. Returns a Stripe Checkout URL to\n * send the buyer to — nothing is credited until they complete payment.\n */\n topup(params: TopupParams): Promise<string>;\n\n /**\n * Keep credit topped up without a human, so runs never stop for an empty wallet:\n * a balance below `threshold_cents` charges `amount_cents` to the saved card\n * off-session. Enabling requires a saved payment method (any completed top-up\n * Checkout saves one) — without it this throws a billing error with code\n * `NO_SAVED_PAYMENT_METHOD`. Disabling needs only `enabled: false`. At most one\n * reload fires per 6-hour window. Returns the refreshed balance.\n */\n setAutoReload(params: AutoReloadParams): Promise<Balance>;\n\n /**\n * Choose when you want to hear about a draining balance. The critical tier is\n * fixed at 20% of the value you set, and `0` warns only on depletion. Warnings\n * arrive by email and as `balance.low` / `balance.critical` / `balance.depleted`\n * webhook events. Returns the refreshed balance.\n */\n setAlertThreshold(params: AlertThresholdParams): Promise<Balance>;\n}\n\nexport function createBillingResource(http: Http): BillingResource {\n return {\n usage() {\n return http.request<Usage>(\"GET\", \"/usage/\");\n },\n\n usageTimeseries(params = {}) {\n const { agent_id, teammate_id, ...rest } = params;\n const query = toQuery(\n toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) }),\n );\n return http.request<UsageTimeseries>(\"GET\", \"/usage/timeseries\", { query });\n },\n\n receipts(params = {}) {\n return pager<Receipt>(http, \"/billing/receipts\")({ ...params });\n },\n\n plans() {\n return http.request<Plan[]>(\"GET\", \"/billing/plans\");\n },\n\n setOverage(params) {\n return http.request<Usage>(\"PATCH\", \"/billing/overage\", { body: toBody({ ...params }) });\n },\n\n balance() {\n return http.request<Balance>(\"GET\", \"/billing/balance\");\n },\n\n async topup(params) {\n const res = await http.request<{ checkout_url: string }>(\"POST\", \"/billing/topup\", {\n body: toBody({ ...params }),\n });\n return res.checkout_url;\n },\n\n setAutoReload(params) {\n return http.request<Balance>(\"PATCH\", \"/billing/auto-reload\", {\n body: toBody({ ...params }),\n });\n },\n\n setAlertThreshold(params) {\n return http.request<Balance>(\"PATCH\", \"/billing/alert-settings\", {\n body: toBody({ ...params }),\n });\n },\n };\n}\n","/**\n * `client.memories` — pre-load what an agent already knows about someone.\n *\n * A run starts cold unless it has memories to draw on. Writing them here lets you\n * seed an end-user's context from data you already hold (plan, timezone, past\n * decisions, preferences) so the first run behaves like the tenth, instead of\n * waiting for the agent to learn it over several conversations.\n *\n * `user_id` is the scope, and the scopes never mix: with it, the memory belongs to\n * that one end-user and is visible only to runs carrying the same `user_id`;\n * without it, the memory is account-level and visible only to runs that carry no\n * `user_id`. There is no inheritance between the two — an account-level memory is\n * NOT a fallback for an end-user run.\n *\n * Documented at `/docs/users`. Mirrors `sdk/py/m8tes/_resources/memories.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport { pager } from \"./users\";\nimport type { Memory } from \"../types\";\n\nexport interface MemoryCreateParams {\n /** The fact to remember, in plain language. */\n content: string;\n /** Scope it to one end-user. Omit for an account-level memory. */\n user_id?: string;\n}\n\nexport interface MemoryListParams {\n /** Scope to read. Omit to read account-level memories. */\n user_id?: string;\n /**\n * Keyword filter on content (case-insensitive substring). It only narrows the\n * chosen scope — it never reaches across into the other one — and paging\n * applies to the filtered set.\n */\n query?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface MemoryUpdateParams {\n /** Replaces the stored text outright. */\n content: string;\n /** The scope the memory lives in. Must match, or the memory is not found. */\n user_id?: string;\n}\n\nexport interface MemoriesResource {\n /**\n * Teach an agent a fact up front, before anyone runs it.\n *\n * Throws a `ConflictError` (409) when the scope is already at its memory\n * capacity, or when identical content is already stored in it — so this is\n * safe to call repeatedly only if you handle that error.\n */\n create(params: MemoryCreateParams): Promise<Memory>;\n /** Audit or display what an agent knows about one end-user (or the account). */\n list(params?: MemoryListParams): Promise<Page<Memory>>;\n /** Correct a fact that changed, keeping its id — rather than delete + re-create. */\n update(memoryId: number, params: MemoryUpdateParams): Promise<Memory>;\n /** Make an agent forget something, e.g. on an end-user's erasure request. */\n delete(memoryId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createMemoriesResource(http: Http): MemoriesResource {\n return {\n create(params) {\n return http.request<Memory>(\"POST\", \"/memories/\", { body: toBody({ ...params }) });\n },\n\n list(params = {}) {\n return pager<Memory>(http, \"/memories/\")({ ...params });\n },\n\n update(memoryId, { user_id, content }) {\n // Scope travels in the query string, the new text in the body.\n return http.request<Memory>(\"PATCH\", `/memories/${seg(memoryId)}`, {\n query: toQuery({ user_id }),\n body: toBody({ content }),\n });\n },\n\n async delete(memoryId, params = {}) {\n await http.request(\"DELETE\", `/memories/${seg(memoryId)}`, {\n query: toQuery({ user_id: params.user_id }),\n });\n },\n };\n}\n","/**\n * `client.models` — find out which `model` values are actually valid, and what\n * they cost, instead of guessing from the docs.\n *\n * `model` is a plain string everywhere in this SDK, which keeps new models\n * usable the day they're enabled but means a typo is only caught by the API. Ask\n * this route instead: it returns the models your account can select right now\n * (Anthropic and not — the set grows without an SDK release), which one is the\n * default, and the per-million-token prices the platform bills you at, so you\n * can estimate spend before starting a run.\n *\n * Mirrors `sdk/py/m8tes/_resources/models.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport type { Model } from \"../types\";\n\nexport interface ModelsResource {\n /**\n * The models you can pass as `model` on an agent or a run, with USD pricing\n * per million tokens.\n *\n * Omit `model` on an agent/run to get the entry flagged `default: true` — that\n * flag is per-viewer, so the default you see here is the default you'd get.\n *\n * Takes no arguments and has no cursor: `GET /models/` returns the whole\n * catalog in one response. A `Page` is still returned so `for await` works the\n * same as on every other list, but it never fetches a second page.\n */\n /**\n * The model catalog. Check `zdr_supported` before sending customer data: a\n * non-ZDR model is allowed on the API but may retain inputs and outputs.\n */\n list(): Promise<Page<Model>>;\n}\n\nexport function createModelsResource(http: Http): ModelsResource {\n return {\n async list() {\n const res = await http.request<{ data: Model[]; has_more?: boolean }>(\"GET\", \"/models/\");\n // No fetchNext: the route accepts no cursor, matching the Python SDK's\n // SyncPage built without `_fetch_next`.\n return new Page<Model>(res?.data ?? [], res?.has_more ?? false);\n },\n };\n}\n","/** Account-level OAuth subscriptions used by the Claude Code execution harness. */\n\nimport type { Http } from \"../http\";\nimport { seg } from \"../protocol/seg\";\n\nexport type ModelConnectionProvider = \"claude\" | \"openai\" | \"xai\" | \"gemini\";\nexport type AuthorizableModelConnectionProvider = \"openai\" | \"xai\" | \"gemini\";\nexport type DeviceModelConnectionProvider = \"openai\" | \"xai\";\nexport type CodeModelConnectionProvider = \"gemini\";\n\nexport interface ModelConnection {\n\tprovider: ModelConnectionProvider;\n\tdisplay_name: string;\n\tconnected: boolean;\n\tstatus?: string | null;\n\taccount_label?: string | null;\n\texpires_at?: string | null;\n}\n\nexport interface ModelAuthorization {\n\tprovider: AuthorizableModelConnectionProvider;\n\tstate: string;\n\tstatus: \"pending\" | \"connected\";\n\tauthorization_url?: string | null;\n\tuser_code?: string | null;\n\texpires_at?: string | null;\n\tinterval_seconds: number;\n}\n\nexport interface ModelConnectionsResource {\n\t/** List supported providers. Credential material is never returned. */\n\tlist(): Promise<ModelConnection[]>;\n\t/** Start provider-native authorization; show the returned URL and device code when used. */\n\tauthorize(provider: AuthorizableModelConnectionProvider): Promise<ModelAuthorization>;\n\t/** Poll once; successful device authorization is saved automatically. */\n\tauthorizationStatus(\n\t\tprovider: DeviceModelConnectionProvider,\n\t\tstate: string\n\t): Promise<ModelAuthorization>;\n\t/** Exchange a pasted authorization code and store the connection. */\n\tcompleteAuthorization(\n\t\tprovider: CodeModelConnectionProvider,\n\t\tstate: string,\n\t\tparams: { code: string }\n\t): Promise<ModelAuthorization>;\n\t/** Cancel a short-lived provider authorization session. */\n\tcancelAuthorization(provider: AuthorizableModelConnectionProvider, state: string): Promise<void>;\n\t/** Delete m8tes' encrypted copy of the provider credentials. */\n\tdisconnect(provider: ModelConnectionProvider): Promise<ModelConnection>;\n}\n\nexport function createModelConnectionsResource(http: Http): ModelConnectionsResource {\n\treturn {\n\t\tasync list() {\n\t\t\tconst res = await http.request<{ data: ModelConnection[] }>(\"GET\", \"/model-connections/\");\n\t\t\treturn res?.data ?? [];\n\t\t},\n\t\tauthorize(provider) {\n\t\t\treturn http.request<ModelAuthorization>(\n\t\t\t\t\"POST\",\n\t\t\t\t`/model-connections/${seg(provider)}/authorizations`\n\t\t\t);\n\t\t},\n\t\tauthorizationStatus(provider, state) {\n\t\t\treturn http.request<ModelAuthorization>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/model-connections/${seg(provider)}/authorizations/${seg(state)}`\n\t\t\t);\n\t\t},\n\t\tcompleteAuthorization(provider, state, params) {\n\t\t\treturn http.request<ModelAuthorization>(\n\t\t\t\t\"POST\",\n\t\t\t\t`/model-connections/${seg(provider)}/authorizations/${seg(state)}`,\n\t\t\t\t{ body: { code: params.code } }\n\t\t\t);\n\t\t},\n\t\tasync cancelAuthorization(provider, state) {\n\t\t\tawait http.request(\"DELETE\", `/model-connections/${seg(provider)}/authorizations/${seg(state)}`);\n\t\t},\n\t\tdisconnect(provider) {\n\t\t\treturn http.request<ModelConnection>(\"DELETE\", `/model-connections/${seg(provider)}`);\n\t\t},\n\t};\n}\n","/**\n * `client.permissions` — standing tool allow-lists, one end-user at a time.\n *\n * A run pauses whenever the agent reaches for a tool that is not pre-approved,\n * and stays paused until somebody answers. That is the right default for a first\n * run and the wrong one for a tool your product has already decided is fine. A\n * policy here says \"this end-user's runs may use this tool\" once, so their runs\n * stop stopping.\n *\n * Scope: policies are per end-user (`user_id` is required on every call — there\n * is no account-wide policy) and outlive the run, unlike `runs.answerPermission()`\n * which unblocks a single gate. `/docs/users` documents this surface; mirrors\n * `sdk/py/m8tes/_resources/permissions.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { PermissionPolicy } from \"../types\";\nimport { type PageParams, pager } from \"./users\";\n\nexport interface PermissionCreateParams {\n /** The end-user whose runs this policy applies to. Required — policies never span end-users. */\n user_id: string;\n /** The tool to pre-approve, e.g. `\"Bash\"` or an `mcp__*` tool name. */\n tool: string;\n}\n\nexport interface PermissionListParams extends PageParams {\n /** Required: you list one end-user's policies, never the account's. */\n user_id: string;\n}\n\nexport interface PermissionsResource {\n /**\n * Pre-approve a tool so this end-user's runs no longer pause on it.\n * Idempotent — re-approving the same tool returns the existing policy rather\n * than erroring or duplicating. Send `tool`; the policy comes back as `tool_name`.\n */\n create(params: PermissionCreateParams): Promise<PermissionPolicy>;\n /** Audit what an end-user's runs are allowed to do without asking. */\n list(params: PermissionListParams): Promise<Page<PermissionPolicy>>;\n /**\n * Revoke a pre-approval, so the tool gates again on the next run.\n * `user_id` is required and scopes the delete — an id alone will not resolve.\n */\n delete(permissionId: number, params: { user_id: string }): Promise<void>;\n}\n\nexport function createPermissionsResource(http: Http): PermissionsResource {\n return {\n create(params) {\n return http.request<PermissionPolicy>(\"POST\", \"/permissions/\", {\n body: toBody({ ...params }),\n });\n },\n\n list(params) {\n return pager<PermissionPolicy>(http, \"/permissions/\")({ ...params });\n },\n\n async delete(permissionId, params) {\n await http.request(\"DELETE\", `/permissions/${seg(permissionId)}`, {\n query: toQuery({ user_id: params.user_id }),\n });\n },\n };\n}\n","/**\n * Filename → MIME type, for run attachments.\n *\n * The upload endpoint validates `content_type` against a strict allowlist\n * (`fastapi/app/services/execution/file_validation.py::ALLOWED_TYPES`) and\n * rejects the whole batch on a miss. A `Blob` built from bytes or a string has\n * no type, so it arrives as `application/octet-stream` and every upload fails\n * with `Invalid type: application/octet-stream` — which tells the developer\n * nothing about what to do next.\n *\n * So the type is inferred from the extension, and a caller can always override\n * it explicitly. Found by a live E2E: the mocked tests could not see it, because\n * only the real server enforces the allowlist.\n *\n * This map mirrors that allowlist. Adding a type here that the server does not\n * accept just moves the failure; keep the two in step.\n */\n\n// null-prototype on purpose: a plain object literal resolves `constructor`,\n// `__proto__`, `toString` through the prototype chain, so a filename ending\n// `.constructor` returned a truthy NON-string that sailed past the `if (!type)`\n// guard and became a garbage Content-Type. Filenames are often user-supplied.\nconst EXTENSION_TYPES: Record<string, string> = Object.assign(Object.create(null), {\n // Images (the agent can actually see these via its Read tool)\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n // Documents\n pdf: \"application/pdf\",\n txt: \"text/plain\",\n md: \"text/markdown\",\n markdown: \"text/markdown\",\n html: \"text/html\",\n htm: \"text/html\",\n // Code\n py: \"text/x-python\",\n js: \"application/javascript\",\n mjs: \"application/javascript\",\n cjs: \"application/javascript\",\n json: \"application/json\",\n ts: \"text/typescript\",\n tsx: \"text/typescript\",\n css: \"text/css\",\n c: \"text/x-c\",\n h: \"text/x-c\",\n java: \"text/x-java-source\",\n go: \"text/x-go\",\n sql: \"application/sql\",\n // Data / config\n csv: \"text/csv\",\n tsv: \"text/csv\",\n xml: \"application/xml\",\n yaml: \"text/yaml\",\n yml: \"text/yaml\",\n // Archives\n zip: \"application/zip\",\n gz: \"application/gzip\",\n tgz: \"application/gzip\",\n tar: \"application/x-tar\",\n // Office\n xlsx: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n xls: \"application/vnd.ms-excel\",\n docx: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n pptx: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ppt: \"application/vnd.ms-powerpoint\",\n});\n\n/** Every type the upload endpoint accepts. Used to make a rejection actionable. */\nexport const UPLOADABLE_EXTENSIONS = Object.keys(EXTENSION_TYPES);\n\n/**\n * The MIME type for a filename, or undefined when the extension is unknown.\n *\n * Undefined rather than a fallback on purpose: `application/octet-stream` is\n * exactly what the server rejects, so guessing it would only reproduce the\n * original confusing error.\n */\nexport function mimeTypeForFilename(name: string): string | undefined {\n const ext = name.includes(\".\") ? name.slice(name.lastIndexOf(\".\") + 1).toLowerCase() : \"\";\n return EXTENSION_TYPES[ext];\n}\n\n/**\n * Message for a file whose type cannot be determined. The server's own error\n * (\"Invalid type: application/octet-stream\") does not say what to do about it.\n */\nexport function unknownTypeMessage(name: string): string {\n return (\n `@m8tes/sdk: cannot infer a content type for \"${name}\", and the upload endpoint ` +\n `rejects files whose type it does not recognise. Pass it explicitly — ` +\n `{ name: \"${name}\", data, type: \"text/plain\" } — or rename the file with a known ` +\n `extension (${UPLOADABLE_EXTENSIONS.slice(0, 12).join(\", \")}, ...).`\n );\n}\n","/**\n * Wait for a run to finish.\n *\n * Streaming is the good path: you see the work as it happens. But plenty of\n * integrations are a queue worker or a cron job that just wants the answer, and\n * without this every one of them hand-rolls the same loop — with its own idea of\n * which statuses are terminal, its own backoff, and usually no timeout. That is\n * the single most common thing a developer had to build themselves.\n *\n * Mirrors `sdk/py/m8tes/_resources/runs.py` (`poll`, `wait`): same terminal set,\n * same 2s interval and 300s default timeout, same \"a transient API error is not\n * a failure, keep polling until the deadline\" behaviour.\n */\n\nimport {\n AuthenticationError,\n ConflictError,\n NotFoundError,\n PermissionDeniedError,\n ValidationError,\n} from \"./protocol/index\";\nimport type { PermissionRequest, Run } from \"./types\";\n\n/**\n * A revoked key, a deleted run, or a bad id will NEVER become terminal, so\n * retrying is pure cost: ~150 authenticated requests over the default 300s,\n * ending in a timeout whose advice (\"raise the timeout, or stream instead\") is\n * wrong for all three. Only genuinely transient failures keep polling.\n */\nfunction isPermanent(err: unknown): boolean {\n return (\n err instanceof AuthenticationError ||\n err instanceof PermissionDeniedError ||\n err instanceof NotFoundError ||\n err instanceof ValidationError\n );\n}\n\n/**\n * A run is done when it reaches one of these.\n *\n * Mirrors `TERMINAL_RUN_STATUSES` in `fastapi/app/models/run.py`, which is the\n * canonical set — including `\"closed\"` (a user-closed chat that cannot resume).\n * Both SDKs previously omitted it, so a closed run polled until the timeout.\n * The backend's own comment on that set warns these lists drift and that \"a\n * 'closed' chat run burned tokens too\". `archived` is deliberately NOT here:\n * it is a display state applied to already-terminal runs.\n */\nexport const TERMINAL_STATUSES = new Set([\"completed\", \"failed\", \"cancelled\", \"closed\"]);\n\n/**\n * Gate refusals `wait()` may ride out, keyed on the server's machine-readable\n * `error.details.error_code` (`fastapi/app/routers/v2/runs.py::approve_permission`).\n * Mirrors `_BENIGN_GATE_REFUSALS` in `sdk/py/m8tes/_resources/runs.py`.\n *\n * Membership is the SAFETY boundary, so it is an ALLOWLIST, not a denylist: anything\n * unrecognised — including an older server that sends no code at all — propagates. A\n * refusal the SDK cannot positively identify as harmless is treated as harmful,\n * because the one it must never swallow (`gate_resolved_otherwise`: another approver\n * decided the OPPOSITE way) is indistinguishable from the benign ones without it.\n *\n * `run_not_active` is benign ONLY because the server raises it exclusively for a gate\n * still OPEN on a finished run. If a CONTRADICTED decision could ever report\n * `run_not_active`, a lost denial would be swallowed here — so that split is a\n * contract, pinned server-side by\n * `test_a_contradicted_decision_on_a_terminal_run_is_not_reported_as_benign`.\n */\nconst BENIGN_GATE_REFUSAL_CODES = new Set([\"gate_cancelled\", \"run_not_active\"]);\n\n/**\n * The one benign refusal the server still spells as prose. `POST /runs/{id}/answer`\n * raises `HTTPException(409, detail=\"auto_continued\")` — a STRING detail, and\n * `routers/v2/_errors.py` lifts `error_code` only out of a DICT one — so the envelope\n * carries no code to branch on. It means the platform proceeded with the\n * \"(Recommended)\" option after ~10 minutes and the run is executing normally.\n *\n * Matched as the EXACT, complete message, never a substring, so no other 409 can\n * borrow it. Giving that endpoint a real code (and deleting this) is filed in\n * `TODOS.md`; until then, dropping it would break every polling caller on the\n * documented auto-continue path.\n */\nconst AUTO_CONTINUED_MESSAGE = \"auto_continued\";\n\nfunction isBenignGateRefusal(err: ConflictError | NotFoundError): boolean {\n if (err.errorCode !== undefined) return BENIGN_GATE_REFUSAL_CODES.has(err.errorCode);\n return err instanceof ConflictError && err.message === AUTO_CONTINUED_MESSAGE;\n}\n\nexport interface PollOptions {\n /** Seconds between polls. Default 2. */\n interval?: number;\n /** Seconds before giving up. Default 300. */\n timeout?: number;\n /** Abort the wait early. The in-flight request is cancelled with it. */\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions extends PollOptions {\n /**\n * Called when a tool needs a decision. Return \"allow\" or \"deny\".\n * Without it, a run that pauses for a tool throws rather than hanging until\n * the timeout — silence would look identical to a slow run.\n */\n onApproval?: (request: PermissionRequest) => \"allow\" | \"deny\" | Promise<\"allow\" | \"deny\">;\n /**\n * Called when the agent asks a question. Return `{ [question text]: answer }`.\n * The keys must be the exact `question` strings from the request.\n */\n onQuestion?: (\n request: PermissionRequest,\n ) => Record<string, string> | Promise<Record<string, string>>;\n}\n\n/** Thrown when a run does not reach a terminal status before the deadline. */\nexport class RunTimeoutError extends Error {\n readonly runId: number;\n readonly timeoutSeconds: number;\n /** The last error seen while polling, if any. Without it a timeout hides the\n * transient failure that actually caused it. */\n override readonly cause?: unknown;\n /** The run's status when the deadline hit, when one was ever observed. */\n readonly lastStatus?: string;\n constructor(runId: number, timeoutSeconds: number, cause?: unknown, lastStatus?: string) {\n // The likeliest cause of a poll() timeout is a run parked at\n // awaiting_approval, which NEVER becomes terminal — so \"raise the timeout\"\n // is the one piece of advice guaranteed not to help. Say what actually\n // unblocks it when we know the status.\n const advice =\n lastStatus === \"awaiting_approval\"\n ? `The run is waiting for a human and will never finish on its own: use runs.wait() with ` +\n `onApproval/onQuestion, or resolve it yourself via runs.permissions(${runId}).`\n : `Raise the timeout, or stream the run instead of polling it.`;\n super(\n `Run ${runId} did not reach a terminal status within ${timeoutSeconds}s` +\n (lastStatus ? ` (last status: ${lastStatus})` : \"\") +\n `. ${advice}` +\n (cause instanceof Error ? ` Last error while polling: ${cause.message}` : \"\"),\n );\n this.name = \"RunTimeoutError\";\n this.runId = runId;\n this.timeoutSeconds = timeoutSeconds;\n this.cause = cause;\n if (lastStatus !== undefined) this.lastStatus = lastStatus;\n }\n}\n\n/**\n * Thrown when a run pauses for a human and no handler was supplied. Better than\n * waiting out the full timeout, which gives the caller no idea what happened.\n */\nexport class RunPausedError extends Error {\n readonly runId: number;\n readonly request: PermissionRequest;\n constructor(runId: number, request: PermissionRequest, hint: string) {\n super(`Run ${runId} is waiting for a human: ${hint}`);\n this.name = \"RunPausedError\";\n this.runId = runId;\n this.request = request;\n }\n}\n\n/** Normalized options, with a monotonic deadline. */\nfunction plan(options: PollOptions): {\n interval: number;\n timeout: number;\n deadline: number;\n signal?: AbortSignal;\n} {\n const interval = options.interval ?? 2;\n const timeout = options.timeout ?? 300;\n // NaN makes every `now() >= deadline` false and turns setTimeout into an\n // immediate timer, so the loop hot-spins against the API until something\n // external kills it. A negative interval does the same. Refuse both loudly.\n for (const [name, value] of [[\"interval\", interval], [\"timeout\", timeout]] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new TypeError(\n `@m8tes/sdk: ${name} must be a finite, non-negative number of seconds (got ${String(value)}).`,\n );\n }\n }\n return { interval, timeout, deadline: now() + timeout * 1000, signal: options.signal };\n}\n\n/**\n * Sleep for `interval`, but never past the deadline — otherwise a long interval\n * with a short timeout overshoots by the whole interval before anyone checks.\n */\nfunction napUntil(interval: number, deadline: number, signal?: AbortSignal): Promise<void> {\n const remaining = Math.max(0, deadline - now()) / 1000;\n return sleep(Math.min(interval, remaining), signal);\n}\n\n/**\n * Bound an awaited operation by the deadline (and the abort signal).\n *\n * Without this the advertised timeout only gated the gaps BETWEEN awaits: a\n * caller's `onApproval` that never settles hung `wait()` forever, and a slow\n * request could return success long after the deadline had passed. Now every\n * await is raced against the remaining time.\n */\nasync function withDeadline<T>(\n start: () => Promise<T>,\n deadline: number,\n signal: AbortSignal | undefined,\n onExpired: () => Error,\n): Promise<T> {\n const remaining = deadline - now();\n // A FACTORY, not a promise: an argument would be evaluated eagerly, firing a\n // request (or invoking the caller's callback) that is then thrown away — the\n // work happens, costs, and is ignored. Nothing starts once time is up.\n if (remaining <= 0) throw onExpired();\n const work = start();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort: (() => void) | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(onExpired()), remaining);\n if (signal) {\n onAbort = () => reject(onExpired());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n if (signal && onAbort) signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/** Interruptible sleep. An abort resolves it immediately rather than stranding the caller. */\nfunction sleep(seconds: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(done, seconds * 1000);\n function done(): void {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n resolve();\n }\n signal?.addEventListener(\"abort\", done, { once: true });\n });\n}\n\n/** True for an AskUserQuestion pause carrying a plan for approval (plan mode). */\nexport function isPlanApproval(request: PermissionRequest): boolean {\n if (request.tool_name !== \"AskUserQuestion\") return false;\n const questions = (request.tool_input as { questions?: Array<{ header?: string }> } | null)\n ?.questions;\n return Array.isArray(questions) && questions.some((q) => q?.header === \"Plan Approval\");\n}\n\n/** The proposed plan text, for a plan-approval pause. Null otherwise. */\nexport function planText(request: PermissionRequest): string | null {\n if (!isPlanApproval(request)) return null;\n const questions = (\n request.tool_input as { questions?: Array<{ header?: string; question?: string }> } | null\n )?.questions;\n return questions?.find((q) => q?.header === \"Plan Approval\")?.question ?? null;\n}\n\n/**\n * Injected by the runs resource so this module stays free of transport concerns.\n * Every call takes the caller's `signal`, so an abort cancels the in-flight HTTP\n * request instead of only shortening the next sleep.\n */\nexport interface PollDeps {\n get(runId: number, signal?: AbortSignal): Promise<Run>;\n permissions(runId: number, signal?: AbortSignal): Promise<PermissionRequest[]>;\n approve(\n runId: number,\n params: { request_id: string; decision: \"allow\" | \"deny\" },\n signal?: AbortSignal,\n ): Promise<unknown>;\n answer(\n runId: number,\n params: { answers: Record<string, string> },\n signal?: AbortSignal,\n ): Promise<unknown>;\n}\n\n/**\n * Monotonic milliseconds. `Date.now()` follows the wall clock, so an NTP\n * correction backwards mid-wait extends the timeout by the same amount (and\n * repeated corrections can stop it expiring at all). Python uses\n * `time.monotonic()` for exactly this reason.\n */\nconst now = (): number =>\n typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n\n/** Thrown when the caller aborts the wait. */\nexport class RunWaitAbortedError extends Error {\n /**\n * The run being waited on — `undefined` when the abort landed BEFORE any run\n * was created, which is the one case where there is nothing to go back to.\n * Previously this path passed a literal 0, producing \"Waiting on run 0 was\n * aborted\" and pointing the reader at a run that never existed.\n */\n readonly runId?: number;\n constructor(runId?: number) {\n super(\n runId === undefined\n ? \"Aborted before the run was created; nothing was started and nothing was billed.\"\n : `Waiting on run ${runId} was aborted. The run is still executing — ` +\n `poll it later with runs.get(${runId}), or stop it with runs.cancel(${runId}).`,\n );\n this.name = \"RunWaitAbortedError\";\n if (runId !== undefined) this.runId = runId;\n }\n}\n\n/**\n * Poll until the run is terminal.\n *\n * A run that pauses for a human never becomes terminal, so this would spin until\n * the timeout — `waitForRun` handles that case. `poll` is for autonomous runs.\n */\nexport async function pollRun(deps: PollDeps, runId: number, options: PollOptions = {}): Promise<Run> {\n const { interval, timeout, deadline, signal } = plan(options);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n // Kept so a timeout can still show WHY the last attempt failed.\n let lastError: unknown;\n // Kept so the timeout can give advice that fits the state the run is actually in.\n let lastStatus: string | undefined;\n\n for (;;) {\n let run: Run | undefined;\n try {\n run = await withDeadline(() => deps.get(runId, signal), deadline, signal, () =>\n signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus),\n );\n } catch (err) {\n // A timeout/abort raised by withDeadline is the verdict, not a blip.\n if (err instanceof RunTimeoutError || err instanceof RunWaitAbortedError) throw err;\n // A blip while the run is executing is not a failure: keep polling until\n // the deadline. But a 401/403/404 never resolves, so surface it now.\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (isPermanent(err)) throw err;\n lastError = err;\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n continue;\n }\n\n lastStatus = run.status;\n if (TERMINAL_STATUSES.has(run.status)) return run;\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n // The deadline can pass DURING the sleep; without this the loop would issue\n // one more request and could return successfully long after it expired.\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n }\n}\n\n/**\n * Wait for a run, answering human-in-the-loop pauses through callbacks.\n *\n * Same loop as `pollRun`, plus: on `awaiting_approval`, resolve every pending\n * request and let the run continue.\n */\nexport async function waitForRun(\n deps: PollDeps,\n runId: number,\n options: WaitOptions = {},\n): Promise<Run> {\n const { interval, timeout, deadline, signal } = plan(options);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n // Kept so a timeout can still show WHY the last attempt failed.\n let lastError: unknown;\n // Kept so the timeout can give advice that fits the state the run is actually in.\n let lastStatus: string | undefined;\n // A request we have already answered can still come back as \"pending\" on the\n // next poll, because the backend has not flipped its status yet. Without this\n // ledger the caller's onApproval/onQuestion fires again for the same gate —\n // and a callback that notifies a human or increments a counter would repeat.\n // Measured: 3 duplicate calls across 4 polls before this was added.\n const answered = new Set<string>();\n\n for (;;) {\n let run: Run | undefined;\n try {\n run = await withDeadline(() => deps.get(runId, signal), deadline, signal, () =>\n signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus),\n );\n } catch (err) {\n if (err instanceof RunTimeoutError || err instanceof RunWaitAbortedError) throw err;\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (isPermanent(err)) throw err;\n lastError = err;\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n continue;\n }\n\n lastStatus = run.status;\n if (TERMINAL_STATUSES.has(run.status)) return run;\n\n if (run.status === \"awaiting_approval\") {\n const expired = () =>\n signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus);\n const bound = <T>(start: () => Promise<T>): Promise<T> => withDeadline(start, deadline, signal, expired);\n /**\n * Resolving a gate can lose a race the caller cannot prevent — but two very\n * different losses look alike, so this branches on the SERVER'S code, never on\n * the status alone.\n *\n * benign — the gate was cancelled, the run went terminal, or the platform\n * auto-continued a \"(Recommended)\" question. Nothing a human decided was\n * contradicted, and `wait()` owes the caller the RUN's outcome, not the\n * gate's; keep polling and the next `get()` returns the real result.\n *\n * CONTRADICTED — another approver decided the OTHER way (or answered the same\n * question differently), so this caller's decision did NOT happen and the\n * opposite one is what runs. `onQuestion` picks A, Slack commits B, `/answer`\n * 409s the losing A: swallowing that makes `wait()` return a completed run to\n * a caller who believes they blocked the tool that just executed. It is the\n * same false confirmation the 404 exists to prevent, one layer up.\n *\n * Swallowing EVERY conflict could not tell those apart. See\n * `_BENIGN_GATE_REFUSALS` in `sdk/py/m8tes/_resources/runs.py` — same allowlist,\n * same reasoning, deliberately kept in step.\n */\n const resolveGate = async (start: () => Promise<unknown>): Promise<void> => {\n try {\n await bound(start);\n } catch (err) {\n if (!(err instanceof ConflictError) && !(err instanceof NotFoundError)) throw err;\n if (!isBenignGateRefusal(err)) throw err;\n }\n };\n const pending = (await bound(() => deps.permissions(runId, signal))).filter(\n (r) => r.status === \"pending\" && !answered.has(r.request_id),\n );\n for (const request of pending) {\n answered.add(request.request_id);\n if (request.tool_name === \"AskUserQuestion\") {\n if (!options.onQuestion) {\n throw new RunPausedError(\n runId,\n request,\n \"the agent asked a question. Pass onQuestion to answer it, or call runs.answer() yourself.\",\n );\n }\n // The callback is the caller's code: it can hang, so it is bounded too.\n const answers = await bound(async () => options.onQuestion!(request));\n await resolveGate(() => deps.answer(runId, { answers }, signal));\n } else {\n if (!options.onApproval) {\n throw new RunPausedError(\n runId,\n request,\n `the tool \"${request.tool_name}\" needs a decision. Pass onApproval, or call runs.approve() yourself.`,\n );\n }\n const decision = await bound(async () => options.onApproval!(request));\n await resolveGate(() => deps.approve(runId, { request_id: request.request_id, decision }, signal));\n }\n }\n }\n\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n }\n}\n","/**\n * `RunStream` — the developer-facing view of a streaming run.\n *\n * Mirrors the Python SDK's `RunStream` (`sdk/py/m8tes/_streaming.py`): iterate\n * events, or just await the text. It accumulates as you consume, so after\n * iterating you have `.text`, `.runId`, and `.errors` without a second request.\n *\n * Beyond Python it also exposes `.state` — the full normalized conversation\n * (messages, tool calls, notices) from the shared protocol accumulator. Useful\n * server-side for logging what the agent actually did, not just what it said.\n *\n * Nothing is consumed until you iterate: constructing a RunStream is free, and\n * an un-iterated stream is closed by `close()` without reading the body.\n */\n\nimport {\n RunFailedError,\n accumulate,\n initialConversationState,\n isTerminalEvent,\n type ConversationState,\n type M8tesStreamEvent,\n} from \"./protocol/index\";\n\nexport interface RunStreamOptions {\n /**\n * Throw `RunFailedError` once iteration finishes if the run emitted any error\n * event, so a mid-run failure is never mistaken for a successful empty run.\n * Defaults to false, matching the Python SDK.\n */\n raiseOnError?: boolean;\n /**\n * Reuse this key to retry the same call safely — the server replays the run the\n * first attempt produced instead of starting (and billing) a second one. One is\n * minted per call automatically; supply your own only when a retry must survive\n * a process restart. Sent as the `Idempotency-Key` header.\n */\n idempotencyKey?: string;\n}\n\nexport class RunStream implements AsyncIterable<M8tesStreamEvent> {\n private readonly source: AsyncGenerator<M8tesStreamEvent, void, unknown>;\n private readonly raiseOnError: boolean;\n private state: ConversationState = initialConversationState;\n private textChunks: string[] = [];\n private errorMessages: string[] = [];\n private runIdValue: number | null = null;\n private consumed = false;\n\n constructor(\n source: AsyncGenerator<M8tesStreamEvent, void, unknown>,\n options: RunStreamOptions = {},\n ) {\n this.source = source;\n this.raiseOnError = options.raiseOnError ?? false;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<M8tesStreamEvent> {\n if (this.consumed) {\n throw new Error(\n \"RunStream has already been consumed. A stream is single-pass — iterate once, \" +\n \"then read .text / .state / .errors, or call runs.get(runId) to re-read the result.\",\n );\n }\n this.consumed = true;\n try {\n for await (const event of this.source) {\n this.state = accumulate(this.state, event);\n if (event.type === \"text-delta\") this.textChunks.push(event.delta);\n if (event.type === \"run-start\" && event.runId !== null) this.runIdValue = event.runId;\n if (event.type === \"run-error\") this.errorMessages.push(event.message || event.error);\n yield event;\n }\n } finally {\n // Closing the source generator cancels the underlying HTTP response even\n // when the caller breaks out of the loop early.\n await this.source.return(undefined).catch(() => undefined);\n }\n if (this.raiseOnError && this.errorMessages.length > 0) {\n throw new RunFailedError(`Run failed: ${this.errorMessages.join(\"; \")}`, {\n type: \"run_failed\",\n code: 0,\n status: 0,\n details: { errors: this.errorMessages },\n });\n }\n }\n\n /** Yield only the assistant's text, in order. The 90% case for a server. */\n async *iterText(): AsyncGenerator<string, void, unknown> {\n for await (const event of this) {\n if (event.type === \"text-delta\") yield event.delta;\n }\n }\n\n /** Drain the stream and return the full assistant text. */\n async text(): Promise<string> {\n for await (const _ of this) {\n /* accumulate */\n }\n return this.textChunks.join(\"\");\n }\n\n /** Accumulated text so far (complete once iteration finishes). */\n get output(): string {\n return this.textChunks.join(\"\");\n }\n\n /** Run id, available as soon as the first `run-start` event arrives. */\n get runId(): number | null {\n return this.runIdValue;\n }\n\n /** Error messages the run emitted. Check this, or pass `raiseOnError`. */\n get errors(): string[] {\n return [...this.errorMessages];\n }\n\n get hasErrors(): boolean {\n return this.errorMessages.length > 0;\n }\n\n /** Full normalized conversation: messages, tool calls, notices, status. */\n get conversation(): ConversationState {\n return this.state;\n }\n\n /** Close the underlying response without draining it. */\n async close(): Promise<void> {\n await this.source.return(undefined).catch(() => undefined);\n }\n}\n\nexport { isTerminalEvent };\n","/**\n * `client.runs` — start agents, stream what they do, and answer them mid-run.\n *\n * `create()` is the one call most integrations need: it provisions a default\n * agent if the account has none, so a brand-new key can run an agent in one\n * request. Mirrors `sdk/py/m8tes/_resources/runs.py`, field for field.\n */\n\nimport { IDEMPOTENCY_HEADER, type Http } from \"../http\";\nimport { mimeTypeForFilename, unknownTypeMessage } from \"../mime\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { resolveAgentId, toBody, toQuery } from \"../params\";\nimport {\n pollRun,\n RunWaitAbortedError,\n TERMINAL_STATUSES,\n waitForRun,\n type PollDeps,\n type PollOptions,\n type WaitOptions,\n} from \"../polling\";\nimport { ConflictError, type M8tesStreamEvent } from \"../protocol/index\";\n\n/**\n * Stamp the run id onto an error on its way out of a wait.\n *\n * `waitForRun` tolerates transient failures on `get`, but a failure while\n * resolving a permission gate (permissions/answer/approve) escapes to the\n * caller. Escaping is a defensible trade-off; escaping ANONYMOUSLY is not — for\n * `createAndWait` the caller never saw the id, so a run that is created,\n * billed, and STILL EXECUTING became unreachable. The error's class is\n * preserved so `instanceof ValidationError` and friends keep working; the id is\n * purely additive, and never overwrites an existing `runId`.\n */\nfunction withRunId<E>(err: E, runId: number): E {\n if (err && typeof err === \"object\" && !(\"runId\" in err)) {\n Object.defineProperty(err, \"runId\", { value: runId, enumerable: true, configurable: true });\n const e = err as { message?: string };\n if (typeof e.message === \"string\" && !e.message.includes(String(runId))) {\n e.message = `${e.message} (while waiting on run ${runId}, which is still executing)`;\n }\n }\n return err;\n}\nimport { RunStream, type RunStreamOptions } from \"../streaming\";\nimport type {\n JsonObject,\n PermissionMode,\n PermissionRequest,\n Run,\n RunFile,\n RunOutcome,\n} from \"../types\";\n\nexport interface RunCreateParams {\n /** What the agent should do. */\n message: string;\n /** Which agent runs it. Omit to use (or auto-provision) the account default. */\n agent_id?: number;\n /** Permanent legacy alias for `agent_id` — the same wire field. */\n teammate_id?: number;\n /** Your id for the end-user this run belongs to. Isolates their memory, history, and tool connections. */\n user_id?: string;\n /** Tool slugs available for this run. */\n tools?: string[];\n /** One-off system instructions for this run. */\n instructions?: string;\n /** Name a newly auto-created agent. */\n name?: string;\n /** Your own key/value data, echoed back on the Run. */\n metadata?: JsonObject;\n model?: string;\n effort?: string;\n permission_mode?: PermissionMode;\n /** Enable clarifying questions, tool approval, and plan mode. */\n human_in_the_loop?: boolean;\n /** Run-level overrides for the built-in tools. Omit to inherit the agent default. */\n memory?: boolean;\n history?: boolean;\n task_setup_tools?: boolean;\n feedback?: boolean;\n /** Ask for structured output matching this JSON Schema; lands on `run.output_data`. */\n output_schema?: JsonObject;\n /** Give this run's agent an email inbox. */\n email_inbox?: boolean;\n /**\n * Reuse this key to retry the same create safely — the server returns the run\n * the first attempt made instead of starting (and billing) a second one.\n *\n * One is minted per call automatically, which is what makes the SDK's own\n * retries safe. Supply your own only when a retry must survive a process\n * restart: a job runner re-driving the same unit of work should pass its job\n * id. Sent as the `Idempotency-Key` header; never part of the request body.\n */\n idempotencyKey?: string;\n /**\n * Files the agent can read: a CSV to analyze, a PDF to summarize. Each is a\n * `{ name, data }` pair; `data` accepts anything `FormData` takes (Blob,\n * Uint8Array, ArrayBuffer, string). Sending files switches the request to the\n * multipart `/runs/with-files` endpoint; every other option behaves the same.\n *\n * Attachments require sandbox execution (the agent reads them with its file\n * tools from the run's working directory).\n */\n files?: RunFileInput[];\n}\n\n/** One attachment for `runs.create({ files })`. */\nexport interface RunFileInput {\n /** Filename the agent will see. Its extension determines the content type. */\n name: string;\n /** Contents. `Blob`/`File` pass straight through; bytes and strings are wrapped. */\n data: Blob | ArrayBuffer | ArrayBufferView | string;\n /**\n * Content type, if the extension does not imply it. The upload endpoint\n * validates against an allowlist and rejects the batch on a miss, so this is\n * inferred from `name` by default rather than defaulting to\n * `application/octet-stream` (which the server refuses).\n */\n type?: string;\n}\n\nexport interface RunListParams {\n user_id?: string;\n agent_id?: number;\n teammate_id?: number;\n task_id?: number;\n status?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface ApproveParams {\n /** From the `approval-request` event, or `runs.permissions()`. */\n request_id: string;\n decision: \"allow\" | \"deny\";\n /**\n * Apply the same decision to matching tool requests for the rest of THIS run.\n * For a policy that outlives the run, use the permissions API instead.\n */\n remember?: boolean;\n}\n\nexport interface AnswerParams {\n /**\n * Question text → the option label you picked. The keys must be the exact\n * `question` strings from the `question` event.\n */\n answers: Record<string, string>;\n}\n\nexport interface RunsResource {\n /** Start a run and stream it. */\n create(params: RunCreateParams, options?: RunStreamOptions): RunStream;\n /** Start a run and return immediately; poll `get()` or use a webhook for the result. */\n createAsync(params: RunCreateParams): Promise<Run>;\n /**\n * Start a run and wait for the result. The batch/cron counterpart to `create()`.\n * Pass `onApproval`/`onQuestion` to answer human-in-the-loop pauses inline;\n * without them a paused run throws `RunPausedError` rather than hanging.\n */\n createAndWait(params: RunCreateParams, options?: WaitOptions): Promise<Run>;\n /** Poll an existing run until it is terminal. Throws `RunTimeoutError` on deadline. */\n poll(runId: number, options?: PollOptions): Promise<Run>;\n /** Like `poll`, but resolves human-in-the-loop pauses through callbacks. */\n wait(runId: number, options?: WaitOptions): Promise<Run>;\n /**\n * Retry a failed or cancelled run. Returns a NEW run — poll that one's id, the\n * original stays failed. Idempotent: an in-flight retry is returned as-is.\n *\n * If the run already did something visible (sent a message, changed data), the\n * API refuses with a 409 `retry_needs_confirmation`; pass `confirm: true` to\n * proceed. Check `run.retryable` first to avoid a guaranteed conflict.\n */\n retry(runId: number, params?: { confirm?: boolean }): Promise<Run>;\n /** Join a run already in flight. Throws `RunNotStreamingError` if it has finished. */\n stream(runId: number, options?: RunStreamOptions): RunStream;\n /** Continue the conversation on an existing run, streaming the reply. */\n reply(runId: number, message: string, options?: RunStreamOptions): RunStream;\n /** GET /runs/{id} takes NO query params — it is already account-scoped, and\n * sending `user_id` returns 422 `unknown_query_parameter`. */\n get(runId: number): Promise<Run>;\n list(params?: RunListParams): Promise<Page<Run>>;\n /** Cancel a running run. Returns the updated Run, like the Python SDK. */\n cancel(runId: number): Promise<Run>;\n /** Approve or deny a pending tool-permission gate. */\n approve(runId: number, params: ApproveParams): Promise<PermissionRequest>;\n /** Answer a pending AskUserQuestion gate, resuming the run. */\n answer(runId: number, params: AnswerParams): Promise<{ status: string; resumed: boolean }>;\n /** Gates currently waiting on a human. */\n permissions(runId: number): Promise<PermissionRequest[]>;\n /** Condensed result: headline, summary, tokens, cost. */\n outcome(runId: number): Promise<RunOutcome>;\n /** Files the agent produced. */\n files(runId: number): Promise<RunFile[]>;\n /** Download one produced file. */\n downloadFile(runId: number, filename: string): Promise<ArrayBuffer>;\n}\n\n/** Unwrap `{data: [...]}` or a bare array — both shapes exist across v2 routes. */\nfunction items(payload: { data?: unknown[] } | unknown[] | undefined): unknown[] {\n return Array.isArray(payload) ? payload : (payload?.data ?? []);\n}\n\n/**\n * Headers for a run-creating POST — minting a key when the caller gave none.\n *\n * A key is ALWAYS sent. Runs are billable, so a POST that times out is otherwise\n * unanswerable: retry and you may pay twice, don't and you may drop the request.\n * With a key the server binds it to the run it created and replays that run for\n * every repeat, which is what lets `http` retry these POSTs at all.\n *\n * Mirrors `idempotency_headers` in the Python SDK. Auto-minting never dedupes two\n * DELIBERATE identical runs: those are two calls, and each mints its own key.\n * Pass `idempotencyKey` to reuse one across process restarts (a job runner\n * re-driving the same unit of work should pass its job id).\n */\nexport function idempotencyHeaders(key?: string): Record<string, string> {\n return { [IDEMPOTENCY_HEADER]: key ?? crypto.randomUUID() };\n}\n\n/**\n * Follow an idempotent replay to the run's live stream.\n *\n * A run that has ALREADY finished by the time the retry lands has nothing to\n * join, so this throws rather than yielding an empty stream that would read as\n * \"the agent said nothing\". The window is the retry backoff (sub-second), and the\n * error names the run so the caller can fetch its result — still strictly better\n * than the pre-idempotency outcome, where a timed-out create left them unable to\n * learn the run existed at all.\n */\nexport function replayJoin(\n http: Http,\n): (run: { id: number; status: string }) => AsyncGenerator<M8tesStreamEvent, void, unknown> {\n return async function* (run) {\n if (TERMINAL_STATUSES.has(run.status)) {\n throw new ConflictError(\n `Run ${run.id} was already created by an earlier attempt with this idempotency ` +\n `key and has finished (status=${run.status}), so there is no stream to join. ` +\n `You were charged once. Fetch the result with runs.get(${run.id}).`,\n {\n type: \"invalid_request_error\",\n code: 409,\n status: 409,\n details: { error_code: \"idempotent_replay_terminal\", run_id: run.id, status: run.status },\n },\n );\n }\n yield* http.stream(\"GET\", `/runs/${seg(run.id)}/stream`);\n };\n}\n\nexport function createRunsResource(http: Http): RunsResource {\n const createBody = (p: RunCreateParams, stream: boolean): Record<string, unknown> => {\n const { agent_id, teammate_id, files, idempotencyKey, ...rest } = p;\n void files; // carried in the multipart form, never in the JSON body\n void idempotencyKey; // rides in the Idempotency-Key HEADER, never in the body\n return toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id), stream });\n };\n\n /** Multipart form for /runs/with-files: the same JSON under `payload`, plus the files. */\n const createForm = (p: RunCreateParams, stream: boolean): FormData => {\n const form = new FormData();\n form.append(\"payload\", JSON.stringify(createBody(p, stream)));\n for (const f of p.files ?? []) {\n // Precedence: an explicit `type` always wins (otherwise a Blob carrying\n // application/octet-stream would override the caller's own correction and\n // the server would reject the batch), then the Blob's own type, then the\n // filename extension.\n const blobType = f.data instanceof Blob && f.data.type ? f.data.type : undefined;\n const type = f.type ?? blobType ?? mimeTypeForFilename(f.name);\n if (!type) throw new TypeError(unknownTypeMessage(f.name));\n const blob =\n f.data instanceof Blob && f.data.type === type\n ? f.data\n : new Blob([f.data as BlobPart], { type });\n form.append(\"files\", blob, f.name);\n }\n return form;\n };\n\n const hasFiles = (p: RunCreateParams): boolean => (p.files?.length ?? 0) > 0;\n\n // Injected into the polling helpers so they stay transport-free.\n // The caller's abort signal reaches every request, so cancelling a wait\n // cancels the in-flight HTTP call rather than just shortening the next sleep.\n const deps: PollDeps = {\n get: (runId, signal) => http.request<Run>(\"GET\", `/runs/${seg(runId)}`, { signal }),\n permissions: async (runId, signal) =>\n items(await http.request(\"GET\", `/runs/${seg(runId)}/permissions`, { signal })) as PermissionRequest[],\n approve: (runId, params, signal) =>\n http.request(\"POST\", `/runs/${seg(runId)}/approve`, { body: { remember: false, ...params }, signal }),\n answer: (runId, params, signal) =>\n http.request(\"POST\", `/runs/${seg(runId)}/answer`, { body: params, signal }),\n };\n\n // Declared as a local (not a method) so nothing here depends on `this`:\n // `const { createAndWait } = client.runs` is a normal thing to write, and it\n // threw \"Cannot read properties of undefined\" while createAndWait was the one\n // method calling `this.createAsync`. Verified against the packed tarball.\n //\n // `async` on purpose: an unmappable attachment must REJECT, not throw\n // synchronously, or `.catch()` would miss what try/catch catches. (Streaming\n // `create()` returns a RunStream rather than a promise, so it throws\n // synchronously — you never got a stream to iterate.)\n const createAsync = async (params: RunCreateParams): Promise<Run> => {\n const headers = idempotencyHeaders(params.idempotencyKey);\n return hasFiles(params)\n ? http.request<Run>(\"POST\", \"/runs/with-files\", { form: createForm(params, false), headers })\n : http.request<Run>(\"POST\", \"/runs\", { body: createBody(params, false), headers });\n };\n\n return {\n create(params, options) {\n const headers = idempotencyHeaders(params.idempotencyKey);\n const init = hasFiles(params)\n ? { form: createForm(params, true), headers }\n : { body: createBody(params, true), headers };\n const path = hasFiles(params) ? \"/runs/with-files\" : \"/runs\";\n return new RunStream(\n http.stream(\"POST\", path, { ...init, onReplay: replayJoin(http) }),\n options,\n );\n },\n\n createAsync,\n\n async createAndWait(params, options = {}) {\n // Check BEFORE creating: a run costs money, and starting one for an\n // operation the caller already cancelled is the one mistake here that\n // spends real budget. (Verified: this used to issue the POST first.)\n if (options.signal?.aborted) throw new RunWaitAbortedError();\n const started = await createAsync(params);\n // Past this line the run exists and is billable, so every failure must\n // still tell the caller WHICH run to go back to.\n try {\n return await waitForRun(deps, started.id, options);\n } catch (err) {\n throw withRunId(err, started.id);\n }\n },\n\n poll(runId, options) {\n return pollRun(deps, runId, options);\n },\n\n wait(runId, options) {\n return waitForRun(deps, runId, options);\n },\n\n // `confirm` is a QUERY param and the route takes no body (verified against\n // fastapi/app/routers/v2/runs.py::retry_run), so send neither.\n retry(runId, params = {}) {\n return http.request<Run>(\"POST\", `/runs/${seg(runId)}/retry`, {\n query: params.confirm ? toQuery({ confirm: true }) : \"\",\n });\n },\n\n stream(runId, options) {\n return new RunStream(http.stream(\"GET\", `/runs/${seg(runId)}/stream`), options);\n },\n\n reply(runId, message, options) {\n return new RunStream(\n http.stream(\"POST\", `/runs/${seg(runId)}/reply`, {\n body: { message },\n headers: idempotencyHeaders(options?.idempotencyKey),\n onReplay: replayJoin(http),\n }),\n options,\n );\n },\n\n get(runId) {\n return http.request<Run>(\"GET\", `/runs/${seg(runId)}`);\n },\n\n async list(params = {}) {\n const { agent_id, teammate_id, ...rest } = params;\n const q = toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) });\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<Run>> => {\n const res = await http.request<{ data: Run[]; has_more?: boolean }>(\"GET\", \"/runs\", {\n query: toQuery(p),\n });\n return new Page<Run>(res?.data ?? [], res?.has_more ?? false, (starting_after) =>\n fetchPage({ ...p, starting_after }),\n );\n };\n return fetchPage(q);\n },\n\n cancel(runId) {\n return http.request<Run>(\"POST\", `/runs/${seg(runId)}/cancel`, { body: {} });\n },\n\n approve(runId, params) {\n return http.request<PermissionRequest>(\"POST\", `/runs/${seg(runId)}/approve`, {\n body: { remember: false, ...params },\n });\n },\n\n answer(runId, params) {\n // `answers` is keyed by question text and goes over the wire verbatim.\n return http.request<{ status: string; resumed: boolean }>(\"POST\", `/runs/${seg(runId)}/answer`, {\n body: { answers: params.answers },\n });\n },\n\n async permissions(runId) {\n return items(await http.request(\"GET\", `/runs/${seg(runId)}/permissions`)) as PermissionRequest[];\n },\n\n outcome(runId) {\n return http.request<RunOutcome>(\"GET\", `/runs/${seg(runId)}/outcome`);\n },\n\n async files(runId) {\n return items(await http.request(\"GET\", `/runs/${seg(runId)}/files`)) as RunFile[];\n },\n\n async downloadFile(runId, filename) {\n const res = await http.raw(\"GET\", `/runs/${seg(runId)}/files/${seg(filename)}/download`, {\n headers: { accept: \"application/octet-stream\" },\n });\n return res.arrayBuffer();\n },\n };\n}\n","/**\n * `client.settings` — account-level configuration.\n *\n * In v0.1 scope for one concrete reason: strict multi-tenant mode\n * (`require_end_user_id`) is ON by default for API accounts, and when it rejects a\n * request the backend's own 422 message says \"turn it off once with\n * client.settings.update(require_end_user_id=False)\". Without this resource a\n * TypeScript developer would follow that instruction into a method that does not\n * exist. Found by running the SDK against a real backend.\n *\n * Mirrors `sdk/py/m8tes/_resources/settings.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { toBody } from \"../params\";\n\nexport interface AccountSettings {\n /** Per-end-user monthly run cap. null = uncapped. */\n per_end_user_run_limit: number | null;\n /** Per-end-user monthly metered spend cap, in cents. null = uncapped. */\n per_end_user_cost_limit_cents: number | null;\n /** Per-end-user run-starts per minute. null = unthrottled. */\n per_end_user_rate_per_minute: number | null;\n /** \"standard\", or \"metadata_only\" for zero data retention. */\n retention_mode: string;\n /** When true, any request that would fall back to the account scope is rejected. */\n require_end_user_id: boolean;\n}\n\nexport interface AccountSettingsUpdateParams {\n /** Pass a number to set, `null` to clear, omit to leave unchanged. */\n per_end_user_run_limit?: number | null;\n per_end_user_cost_limit_cents?: number | null;\n per_end_user_rate_per_minute?: number | null;\n retention_mode?: \"standard\" | \"metadata_only\";\n /**\n * Strict multi-tenant mode. ON by default for API accounts: a request that\n * omits `user_id` and would therefore land in the account-level scope is\n * rejected with a 422 rather than silently assuming the global scope.\n *\n * Set false only if you are building for yourself (single-tenant).\n */\n require_end_user_id?: boolean;\n}\n\nexport interface SettingsResource {\n get(): Promise<AccountSettings>;\n update(params: AccountSettingsUpdateParams): Promise<AccountSettings>;\n}\n\nexport function createSettingsResource(http: Http): SettingsResource {\n return {\n get() {\n return http.request<AccountSettings>(\"GET\", \"/settings/\");\n },\n // `null` must survive (it CLEARS a cap); only `undefined` is dropped.\n update(params) {\n return http.request<AccountSettings>(\"PATCH\", \"/settings/\", { body: toBody({ ...params }) });\n },\n };\n}\n","/**\n * `client.tasks` — reusable work definitions, plus the triggers that fire them.\n *\n * A task is \"what to do\"; a trigger is \"when\". `client.tasks.triggers` covers all\n * four kinds (schedule, webhook, email, app event). Mirrors\n * `sdk/py/m8tes/_resources/tasks.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { resolveAgentId, toBody, toQuery } from \"../params\";\nimport { idempotencyHeaders, replayJoin } from \"./runs\";\nimport { RunStream, type RunStreamOptions } from \"../streaming\";\nimport type { JsonObject, Run, Task, Trigger, TriggerType, WebhookToggle } from \"../types\";\n\n/** A task must belong to an agent: `POST /tasks/` requires `teammate_id`, so the\n * type requires one of the two spellings rather than letting you discover it as\n * a 422. */\ntype TaskOwner = { agent_id: number; teammate_id?: never } | { teammate_id: number; agent_id?: never };\n\nexport type TaskCreateParams = TaskOwner & TaskCreateFields;\n\nexport interface TaskCreateFields {\n /** What the agent should do each time this task runs. */\n instructions: string;\n name?: string;\n tools?: string[];\n /** What a good result looks like. */\n expected_output?: string;\n goals?: string;\n user_id?: string;\n /** Email the account owner when a run finishes. Default true. */\n email_notifications?: boolean;\n /** Create a webhook trigger alongside the task. */\n webhook?: boolean;\n /** Cron expression, e.g. `\"0 9 * * 1-5\"`. Creates a schedule trigger. */\n schedule?: string;\n /** IANA timezone for `schedule`. Default \"UTC\". */\n schedule_timezone?: string;\n enable_memory?: boolean;\n enable_history?: boolean;\n enable_task_setup_tools?: boolean;\n enable_feedback?: boolean;\n /** Accumulate self-improvement lessons across this task's runs. Default true. */\n enable_lessons?: boolean;\n}\n\n/**\n * PATCH /tasks/{id} accepts exactly these fields (backend `DevTaskUpdate`).\n * `schedule`, `schedule_timezone`, `webhook`, and the agent id are create-only:\n * sending them to PATCH returns 200 and changes nothing. Change a schedule via\n * `tasks.triggers.update()`, and a webhook via `enableWebhook()`.\n *\n * `null` is meaningful: it CLEARS the field.\n */\nexport interface TaskUpdateParams {\n name?: string | null;\n instructions?: string | null;\n tools?: string[] | null;\n expected_output?: string | null;\n goals?: string | null;\n email_notifications?: boolean | null;\n enable_memory?: boolean | null;\n enable_history?: boolean | null;\n enable_task_setup_tools?: boolean | null;\n enable_feedback?: boolean | null;\n enable_lessons?: boolean | null;\n}\n\nexport interface TaskListParams {\n user_id?: string;\n agent_id?: number;\n teammate_id?: number;\n status?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface TriggerCreateParams {\n type: TriggerType | string;\n /** Schedule triggers: a cron expression. */\n cron?: string;\n /** Schedule triggers: a plain interval instead of cron. */\n interval_seconds?: number;\n /** IANA timezone. Default \"UTC\". */\n timezone?: string;\n /** App-event triggers: the app slug, e.g. `\"github\"`. */\n app?: string;\n /** App-event triggers: the event name, e.g. `\"pull_request_opened\"`. */\n trigger_name?: string;\n trigger_config?: JsonObject;\n user_id?: string;\n /** Email triggers: only these senders may start a run. */\n allowed_senders?: string[];\n}\n\nexport interface TriggersResource {\n create(taskId: number, params: TriggerCreateParams): Promise<Trigger>;\n list(taskId: number, params?: { user_id?: string }): Promise<Trigger[]>;\n /** Only the schedule shape and the enabled flag are mutable — a trigger's\n * `type`/`app`/`trigger_name` are fixed at creation and are silently ignored\n * on PATCH. Delete and recreate to change those. `user_id` scopes to one\n * end-user (404 on mismatch). */\n update(\n taskId: number,\n triggerId: number,\n params: {\n cron?: string;\n interval_seconds?: number;\n timezone?: string;\n enabled?: boolean;\n user_id?: string;\n },\n ): Promise<Trigger>;\n delete(taskId: number, triggerId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport interface TaskRunParams {\n /** Run on behalf of this end-user. */\n user_id?: string;\n /**\n * Reuse this key to retry the same call safely — the server returns the run the\n * first attempt made instead of starting (and billing) a second one. One is\n * minted per call automatically; supply your own (e.g. a scheduler's job id)\n * only when a retry must survive a process restart. Sent as the\n * `Idempotency-Key` header, never in the body.\n */\n idempotencyKey?: string;\n}\n\nexport interface TasksResource {\n triggers: TriggersResource;\n create(params: TaskCreateParams): Promise<Task>;\n list(params?: TaskListParams): Promise<Page<Task>>;\n get(taskId: number, params?: { user_id?: string }): Promise<Task>;\n update(taskId: number, params: TaskUpdateParams & { user_id?: string }): Promise<Task>;\n delete(taskId: number, params?: { user_id?: string }): Promise<void>;\n /** Run the task now, streaming it. */\n run(taskId: number, params?: TaskRunParams, options?: RunStreamOptions): RunStream;\n /** Run the task now without streaming; poll `runs.get()` for the result. */\n runAsync(taskId: number, params?: TaskRunParams): Promise<Run>;\n /** `user_id` scopes to one end-user (404 on mismatch), like get/update/delete. */\n enableWebhook(taskId: number, params?: { user_id?: string }): Promise<WebhookToggle>;\n disableWebhook(taskId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createTasksResource(http: Http): TasksResource {\n const triggers: TriggersResource = {\n create(taskId, params) {\n // user_id rides both channels on purpose: the query copy is the end-user\n // scope gate on the task (404 on mismatch); the body copy picks whose\n // connected account an app trigger arms.\n return http.request<Trigger>(\"POST\", `/tasks/${seg(taskId)}/triggers/`, {\n body: toBody({ timezone: \"UTC\", ...params }),\n query: toQuery({ user_id: params.user_id }),\n });\n },\n async list(taskId, params = {}) {\n const res = await http.request<{ data?: Trigger[] } | Trigger[]>(\n \"GET\",\n `/tasks/${seg(taskId)}/triggers/`,\n { query: toQuery(params) },\n );\n return Array.isArray(res) ? res : (res?.data ?? []);\n },\n update(taskId, triggerId, params) {\n const { user_id, ...patch } = params;\n return http.request<Trigger>(\"PATCH\", `/tasks/${seg(taskId)}/triggers/${seg(triggerId)}`, {\n body: toBody(patch),\n query: toQuery({ user_id }),\n });\n },\n async delete(taskId, triggerId, params = {}) {\n await http.request(\"DELETE\", `/tasks/${seg(taskId)}/triggers/${seg(triggerId)}`, {\n query: toQuery(params),\n });\n },\n };\n\n return {\n triggers,\n\n create(params) {\n const { agent_id, teammate_id, ...rest } = params;\n return http.request<Task>(\"POST\", \"/tasks/\", {\n body: toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) }),\n });\n },\n\n async list(params = {}) {\n const { agent_id, teammate_id, ...rest } = params;\n const q = toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) });\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<Task>> => {\n const res = await http.request<{ data: Task[]; has_more?: boolean }>(\"GET\", \"/tasks/\", {\n query: toQuery(p),\n });\n return new Page<Task>(res?.data ?? [], res?.has_more ?? false, (starting_after) =>\n fetchPage({ ...p, starting_after }),\n );\n };\n return fetchPage(q);\n },\n\n get(taskId, params = {}) {\n return http.request<Task>(\"GET\", `/tasks/${seg(taskId)}`, { query: toQuery(params) });\n },\n\n update(taskId, params) {\n const { user_id, ...patch } = params;\n return http.request<Task>(\"PATCH\", `/tasks/${seg(taskId)}`, {\n body: toBody(patch),\n query: toQuery({ user_id }),\n });\n },\n\n async delete(taskId, params = {}) {\n await http.request(\"DELETE\", `/tasks/${seg(taskId)}`, { query: toQuery(params) });\n },\n\n run(taskId, params = {}, options) {\n const { idempotencyKey, ...rest } = params;\n return new RunStream(\n http.stream(\"POST\", `/tasks/${seg(taskId)}/runs`, {\n body: toBody({ ...rest, stream: true }),\n headers: idempotencyHeaders(idempotencyKey),\n // Shares the create path's replay handling, so a fix on one side can\n // never silently miss the other.\n onReplay: replayJoin(http),\n }),\n options,\n );\n },\n\n runAsync(taskId, params = {}) {\n const { idempotencyKey, ...rest } = params;\n return http.request<Run>(\"POST\", `/tasks/${seg(taskId)}/runs`, {\n body: toBody({ ...rest, stream: false }),\n headers: idempotencyHeaders(idempotencyKey),\n });\n },\n\n enableWebhook(taskId, params = {}) {\n return http.request<WebhookToggle>(\"POST\", `/tasks/${seg(taskId)}/webhook`, {\n body: {},\n query: toQuery(params),\n });\n },\n\n async disableWebhook(taskId, params = {}) {\n await http.request(\"DELETE\", `/tasks/${seg(taskId)}/webhook`, { query: toQuery(params) });\n },\n };\n}\n","/**\n * `client.webhooks` — outbound event delivery, plus signature verification.\n *\n * `verifySignature` is the one function every webhook receiver needs, so it is\n * also exported standalone from the package root: verifying does not require a\n * client or an API key. Mirrors `sdk/py/m8tes/_resources/webhooks.py` byte for\n * byte on the signing scheme, so a payload verified by one SDK verifies in the\n * other.\n *\n * Scheme: HMAC-SHA256 over `\"{webhook-id}.{webhook-timestamp}.{raw body}\"`, hex,\n * prefixed `v1=`, compared in constant time.\n */\n\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody } from \"../params\";\nimport { pager } from \"./users\";\nimport type { Webhook, WebhookDelivery } from \"../types\";\n\nexport interface VerifySignatureOptions {\n /**\n * Reject signatures whose timestamp is older (or newer) than this many\n * seconds — replay protection. Omit to skip the check. 300 is a good default\n * for a public endpoint.\n */\n toleranceSeconds?: number;\n /** Injectable clock, for tests. Seconds since epoch. */\n now?: () => number;\n}\n\n/**\n * Verify a m8tes webhook signature.\n *\n * Pass the RAW request body — a parsed-and-restringified object will not match,\n * because JSON.stringify does not preserve key order or spacing.\n *\n * ```ts\n * const raw = await req.text();\n * if (!verifySignature(raw, Object.fromEntries(req.headers), secret, { toleranceSeconds: 300 })) {\n * return new Response(\"bad signature\", { status: 401 });\n * }\n * ```\n */\nexport function verifySignature(\n body: string | Uint8Array,\n headers: Record<string, string | string[] | undefined> | Headers,\n secret: string,\n options: VerifySignatureOptions = {},\n): boolean {\n const get = (name: string): string | undefined => {\n if (typeof (headers as Headers).get === \"function\") {\n return (headers as Headers).get(name) ?? undefined;\n }\n // Header names are case-insensitive on the wire; normalize before lookup.\n const lower = Object.fromEntries(\n Object.entries(headers as Record<string, string | string[] | undefined>).map(([k, v]) => [\n k.toLowerCase(),\n Array.isArray(v) ? v[0] : v,\n ]),\n );\n return lower[name];\n };\n\n const webhookId = get(\"webhook-id\");\n const timestamp = get(\"webhook-timestamp\");\n const signature = get(\"webhook-signature\");\n if (!webhookId || !timestamp || !signature) return false;\n\n if (options.toleranceSeconds !== undefined) {\n const ts = Number.parseInt(timestamp, 10);\n if (!Number.isFinite(ts)) return false;\n const now = options.now ? options.now() : Math.floor(Date.now() / 1000);\n if (Math.abs(now - ts) > options.toleranceSeconds) return false;\n }\n\n const raw = typeof body === \"string\" ? body : new TextDecoder().decode(body);\n const expected = `v1=${createHmac(\"sha256\", secret).update(`${webhookId}.${timestamp}.${raw}`).digest(\"hex\")}`;\n const a = Buffer.from(expected);\n const b = Buffer.from(signature);\n // timingSafeEqual throws on length mismatch; a length difference is already a\n // mismatch, so short-circuit rather than leak it as an exception.\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nexport interface WebhooksResource {\n verifySignature: typeof verifySignature;\n /** Register an endpoint. The signing secret is returned ONLY here — store it. */\n create(params: { url: string; events?: string[] }): Promise<Webhook>;\n list(params?: { limit?: number; starting_after?: number }): Promise<Page<Webhook>>;\n get(webhookId: number): Promise<Webhook>;\n update(\n webhookId: number,\n params: { url?: string; events?: string[]; active?: boolean },\n ): Promise<Webhook>;\n delete(webhookId: number): Promise<void>;\n /** Delivery attempts, for debugging a receiver that is not getting events. */\n listDeliveries(\n webhookId: number,\n params?: { limit?: number; starting_after?: number },\n ): Promise<Page<WebhookDelivery>>;\n}\n\nexport function createWebhooksResource(http: Http): WebhooksResource {\n return {\n verifySignature,\n\n create(params) {\n return http.request<Webhook>(\"POST\", \"/webhooks/\", { body: toBody({ ...params }) });\n },\n\n list(params = {}) {\n return pager<Webhook>(http, \"/webhooks/\")({ ...params });\n },\n\n get(webhookId) {\n return http.request<Webhook>(\"GET\", `/webhooks/${seg(webhookId)}`);\n },\n\n update(webhookId, params) {\n return http.request<Webhook>(\"PATCH\", `/webhooks/${seg(webhookId)}`, { body: toBody({ ...params }) });\n },\n\n async delete(webhookId) {\n await http.request(\"DELETE\", `/webhooks/${seg(webhookId)}`);\n },\n\n listDeliveries(webhookId, params = {}) {\n return pager<WebhookDelivery>(http, `/webhooks/${seg(webhookId)}/deliveries`)({ ...params });\n },\n };\n}\n","/**\n * `@m8tes/sdk` — TypeScript client for the m8tes API.\n *\n * ```ts\n * import { M8tes } from \"@m8tes/sdk\";\n *\n * const client = new M8tes(); // reads M8TES_API_KEY\n *\n * const run = client.runs.create({\n * message: \"A customer asked to cancel. Draft a warm reply offering to pause instead.\",\n * userId: \"customer_42\", // isolates this end-user's memory, history, and connections\n * });\n * for await (const chunk of run.iterText()) process.stdout.write(chunk);\n * ```\n *\n * SECURITY: this entry point holds your secret `m8_` key and is server-only.\n * Never import it from client-side code. To render an agent in a browser, use\n * `@m8tes/react` plus its server proxy, which keeps the key on your server.\n *\n * The streaming wire protocol lives in `@m8tes/sdk/protocol` (browser-safe, no\n * auth) so this package and `@m8tes/react` share one implementation.\n */\n\nimport { createHttp, DEFAULT_BASE_URL, type ClientOptions, type Http } from \"./http\";\nimport { createAgentsResource, type AgentsResource } from \"./resources/agents\";\nimport { createAppsResource, type AppsResource } from \"./resources/apps\";\nimport { createAccountResource, type AccountResource } from \"./resources/account\";\nimport { createBillingResource, type BillingResource } from \"./resources/billing\";\nimport { createMemoriesResource, type MemoriesResource } from \"./resources/memories\";\nimport { createModelsResource, type ModelsResource } from \"./resources/models\";\nimport {\n createModelConnectionsResource,\n type ModelConnectionsResource,\n} from \"./resources/model-connections\";\nimport { createPermissionsResource, type PermissionsResource } from \"./resources/permissions\";\nimport { createRunsResource, type RunsResource } from \"./resources/runs\";\nimport { createSettingsResource, type SettingsResource } from \"./resources/settings\";\nimport { createTasksResource, type TasksResource } from \"./resources/tasks\";\nimport { createUsersResource, type UsersResource } from \"./resources/users\";\nimport { createWebhooksResource, verifySignature, type WebhooksResource } from \"./resources/webhooks\";\n\n/** Kept in lockstep with package.json \"version\" — guarded by test/version.test.ts. */\nexport const M8TES_SDK_VERSION = \"0.1.0-alpha.2\";\n\nexport class M8tes {\n readonly runs: RunsResource;\n readonly agents: AgentsResource;\n /** Permanent alias for `agents` — the DB model and older docs say \"teammate\". */\n readonly teammates: AgentsResource;\n readonly tasks: TasksResource;\n readonly users: UsersResource;\n readonly apps: AppsResource;\n readonly webhooks: WebhooksResource;\n readonly settings: SettingsResource;\n readonly memories: MemoriesResource;\n readonly permissions: PermissionsResource;\n readonly models: ModelsResource;\n readonly modelConnections: ModelConnectionsResource;\n readonly billing: BillingResource;\n readonly account: AccountResource;\n /** The underlying transport. Use it to call an endpoint this version does not wrap yet. */\n readonly http: Http;\n\n constructor(options: ClientOptions = {}) {\n this.http = createHttp(options);\n this.runs = createRunsResource(this.http);\n this.agents = createAgentsResource(this.http);\n this.teammates = this.agents;\n this.tasks = createTasksResource(this.http);\n this.users = createUsersResource(this.http);\n this.apps = createAppsResource(this.http);\n this.webhooks = createWebhooksResource(this.http);\n this.settings = createSettingsResource(this.http);\n this.memories = createMemoriesResource(this.http);\n this.permissions = createPermissionsResource(this.http);\n this.models = createModelsResource(this.http);\n this.modelConnections = createModelConnectionsResource(this.http);\n this.billing = createBillingResource(this.http);\n this.account = createAccountResource(this.http);\n }\n}\n\n// No default export on purpose: mixing default + named exports makes the CJS\n// build ambiguous (`require(...)` consumers would need `.default`). The one\n// documented form is `import { M8tes } from \"@m8tes/sdk\"`.\n\n// Webhook verification needs no client and no key — import it directly in a\n// route handler that only receives events.\nexport { verifySignature, type VerifySignatureOptions } from \"./resources/webhooks\";\n\n// Transport + client options.\nexport { createHttp, DEFAULT_BASE_URL, type ClientOptions, type FetchLike, type Http } from \"./http\";\n\n// Streaming + pagination.\nexport { RunStream, type RunStreamOptions } from \"./streaming\";\n// Waiting on a run. The error classes are exported so `catch (e) { if (e\n// instanceof RunTimeoutError) ... }` works — without them a caller can only\n// match on a message string.\nexport {\n pollRun,\n waitForRun,\n isPlanApproval,\n planText,\n RunTimeoutError,\n RunPausedError,\n RunWaitAbortedError,\n TERMINAL_STATUSES,\n type PollOptions,\n type WaitOptions,\n} from \"./polling\";\nexport { Page, type ListResponse } from \"./pagination\";\n\n// Resource params + shapes.\nexport type {\n AgentsResource,\n AgentCreateParams,\n AgentUpdateParams,\n AgentListParams,\n} from \"./resources/agents\";\nexport type { AppsResource } from \"./resources/apps\";\nexport type { RunsResource, RunCreateParams, RunListParams } from \"./resources/runs\";\nexport type {\n TasksResource,\n TriggersResource,\n TaskCreateParams,\n TaskUpdateParams,\n TaskListParams,\n TaskRunParams,\n TriggerCreateParams,\n} from \"./resources/tasks\";\nexport type {\n UsersResource,\n EndUserCreateParams,\n EndUserUpdateParams,\n PageParams,\n} from \"./resources/users\";\nexport type { WebhooksResource } from \"./resources/webhooks\";\nexport type {\n SettingsResource,\n AccountSettings,\n AccountSettingsUpdateParams,\n} from \"./resources/settings\";\nexport type * from \"./resources/memories\";\nexport type * from \"./resources/permissions\";\nexport type * from \"./resources/models\";\nexport type * from \"./resources/model-connections\";\nexport type * from \"./resources/billing\";\nexport type * from \"./resources/account\";\nexport * from \"./types\";\n\n// The full wire protocol + typed errors, re-exported so a single import of\n// `@m8tes/sdk` is enough for the common case.\nexport * from \"./protocol/index\";\n"]}
1
+ {"version":3,"sources":["../src/http.ts","../src/pagination.ts","../src/params.ts","../src/resources/agents.ts","../src/resources/apps.ts","../src/resources/account.ts","../src/resources/users.ts","../src/resources/billing.ts","../src/resources/memories.ts","../src/resources/models.ts","../src/resources/model-connections.ts","../src/resources/permissions.ts","../src/mime.ts","../src/polling.ts","../src/streaming.ts","../src/resources/runs.ts","../src/resources/settings.ts","../src/resources/tasks.ts","../src/resources/webhooks.ts","../src/index.ts"],"names":["now"],"mappings":";;;;;AAkCO,IAAM,gBAAA,GAAmB;AAEhC,IAAM,YAAA,GAAe,CAAA;AACrB,IAAM,kBAAA,GAAqB,GAAA;AAC3B,IAAM,gBAAA,uBAAuB,GAAA,CAAI,CAAC,KAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAG,CAAC,CAAA;AAC1D,IAAM,kBAAA,uBAAyB,GAAA,CAAI,CAAC,OAAO,MAAA,EAAQ,KAAA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AA,EAChD;AACF","file":"index.js","sourcesContent":["/**\n * Server-side transport for the m8tes V2 API.\n *\n * SECURITY: this module holds the secret `m8_` API key and must NEVER reach a\n * browser bundle. Client-side rendering of an agent goes through\n * `@m8tes/react` + its server proxy, which keeps the key on the server. The\n * bundle-boundary test asserts `dist/protocol/index.js` contains none of this.\n *\n * Retry semantics mirror the Python SDK (`sdk/py/m8tes/_http.py`) exactly so the\n * two languages behave the same under load:\n * - 3 attempts total, 0.5s initial backoff, doubling\n * - retry only 429/500/502/503/504\n * - retry GET/HEAD/PUT/DELETE/OPTIONS always, and a POST only when it carries\n * an `Idempotency-Key`. Without one, a POST that timed out may already have\n * started a billable run, so re-sending it could double-charge; with one, the\n * server replays the run it already created, which is why the run-creating\n * calls mint a key on every request.\n * - honour `Retry-After` on 429\n */\n\nimport {\n APIError,\n errorClassForStatus,\n parseErrorEnvelope,\n parseRetryAfter,\n type ErrorFromResponseOptions,\n type M8tesApiError,\n type M8tesStreamEvent,\n type Normalizer,\n createNormalizer,\n createSseDecoder,\n} from \"./protocol/index\";\n\n/** Canonical hosted API. Includes the `/api/v2` prefix, like the Python SDK's DEFAULT_BASE_URL. */\nexport const DEFAULT_BASE_URL = \"https://api.m8tes.ai/api/v2\";\n\nconst MAX_ATTEMPTS = 3;\nconst INITIAL_BACKOFF_MS = 500;\nconst RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);\nconst IDEMPOTENT_METHODS = new Set([\"GET\", \"HEAD\", \"PUT\", \"DELETE\", \"OPTIONS\"]);\n\n/** Makes a POST safe to repeat: the server replays the run the first one created. */\nexport const IDEMPOTENCY_HEADER = \"idempotency-key\";\n/** Set by the API when a response is a replay rather than a fresh result. */\nexport const REPLAY_HEADER = \"idempotent-replay\";\n\n/**\n * The ONLY routes whose POST the server makes idempotent.\n *\n * Retry eligibility checks this as well as the header, because the header alone is\n * not evidence the server will honour it. `new M8tes({headers: {\"Idempotency-Key\":\n * …}})` sets it on EVERY request, which would make every POST retryable —\n * including `tasks.create`, which has no server-side idempotency, so a timed-out\n * create would be re-sent and duplicate the task. Found in review.\n *\n * Matched against the path RELATIVE to baseUrl, and fully anchored. An earlier\n * version matched suffixes, which also accepted `/foo/reply` and `/foo/runs` — and\n * `request()`/`raw()` are public, so an unsupported path could have been retried on\n * a route that ignores the key. Anchoring is the whole point of the check, so it\n * must not be approximate.\n */\nconst IDEMPOTENT_POST_PATHS = [\n /^\\/runs\\/?$/,\n /^\\/runs\\/with-files\\/?$/,\n /^\\/runs\\/\\d+\\/reply\\/?$/,\n /^\\/runs\\/\\d+\\/reply\\/with-files\\/?$/,\n /^\\/tasks\\/\\d+\\/runs\\/?$/,\n];\n\nfunction isIdempotentRoute(path: string): boolean {\n const clean = path.split(\"?\")[0] ?? \"\";\n return IDEMPOTENT_POST_PATHS.some((re) => re.test(clean));\n}\n\n/**\n * Whether this request may be re-sent after a timeout or 5xx.\n *\n * Mirrors `_is_retryable` in the Python SDK (`sdk/py/m8tes/_http.py`) so the two\n * languages behave identically under load. Header names are compared lowercased\n * because `mergeHeaders` normalises them — a caller writing `Idempotency-Key`\n * must get retries just like one writing `idempotency-key`.\n */\nfunction isRetryable(method: string, path: string, headers: Record<string, string>): boolean {\n if (IDEMPOTENT_METHODS.has(method.toUpperCase())) return true;\n return IDEMPOTENCY_HEADER in headers && isIdempotentRoute(path);\n}\n\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\nexport interface ClientOptions {\n /** Your `m8_` key. Defaults to `process.env.M8TES_API_KEY`. */\n apiKey?: string;\n /** Override the API host. Must include the `/api/v2` prefix. */\n baseUrl?: string;\n /** Per-request timeout in ms. Default 300_000 (5 min), matching the Python SDK. */\n timeout?: number;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Pluggable fetch, for tests or a custom agent/proxy. Default `globalThis.fetch`. */\n fetch?: FetchLike;\n /** Reported (not thrown) when a stream frame is unparseable. */\n onMalformed?: (rawPayload: string, error: unknown) => void;\n}\n\nexport interface RequestOptions {\n body?: unknown;\n query?: string;\n signal?: AbortSignal;\n headers?: Record<string, string>;\n /**\n * Send as multipart/form-data instead of JSON. Used by the file-upload route.\n * `fetch` sets its own `content-type` with the boundary, so we must NOT set\n * one — a hand-written header omits the boundary and the server cannot parse\n * the body.\n */\n form?: FormData;\n}\n\nexport interface StreamRequestOptions extends RequestOptions {\n /** Reuse a normalizer across reconnects so its dedupe ledger persists. */\n normalizer?: Normalizer;\n /**\n * Called instead of decoding the body when the server answers a run-creating\n * POST with `Idempotent-Replay: true`.\n *\n * A replay is JSON (the run), not SSE — a run that already exists has no fresh\n * stream to emit — so the caller decides what to do with it, in practice\n * joining that run's own stream. It lives here rather than in the resource\n * because this is the only place the Response object exists; by the time\n * `stream()` yields, the headers are gone.\n */\n onReplay?: (run: { id: number; status: string }) => AsyncGenerator<M8tesStreamEvent, void, unknown>;\n}\n\n/**\n * Backoff that an abort cuts short. A plain `setTimeout` would keep a caller\n * waiting out the full delay after they cancelled — with `Retry-After: 3600` on\n * a 429, that is an hour of a request that nobody is waiting for any more.\n */\nfunction backoff(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n resolve();\n }\n signal?.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nfunction looksLikeHtml(res: Response, text: string): boolean {\n if ((res.headers.get(\"content-type\") ?? \"\").includes(\"text/html\")) return true;\n const head = text.trimStart().slice(0, 9).toLowerCase();\n return head.startsWith(\"<!doctype\") || head.startsWith(\"<html\");\n}\n\n/**\n * Replace the raw body with an actionable message when the response says\n * \"you are not talking to the m8tes API\" — the two mistakes that otherwise\n * surface as a baffling 404 or a wall of HTML. Ported from the Python SDK.\n */\nfunction diagnose(res: Response, text: string, body: unknown, url: string): string | undefined {\n if (looksLikeHtml(res, text)) {\n return (\n `Received an HTML page instead of an API response (HTTP ${res.status}) from ${url}. ` +\n `This usually means the host does not serve the m8tes API; check your baseUrl ` +\n `(the hosted API is ${DEFAULT_BASE_URL}).`\n );\n }\n const isBareNotFound =\n res.status === 404 &&\n body !== null &&\n typeof body === \"object\" &&\n !(\"error\" in body) &&\n (body as { detail?: unknown }).detail === \"Not Found\";\n if (isBareNotFound) {\n return (\n `HTTP 404 from ${url} with no API error envelope — the path matched no route. ` +\n `Check your baseUrl includes the /api/v2 prefix (the hosted API is ${DEFAULT_BASE_URL}).`\n );\n }\n return undefined;\n}\n\nexport interface Http {\n baseUrl: string;\n request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;\n /** The OK `Response` itself — for binary bodies (file downloads). Retries and\n * typed errors still apply; the caller owns reading the body. */\n raw(method: string, path: string, opts?: RequestOptions): Promise<Response>;\n stream(\n method: string,\n path: string,\n opts?: StreamRequestOptions,\n ): AsyncGenerator<M8tesStreamEvent, void, unknown>;\n}\n\nexport function createHttp(options: ClientOptions = {}): Http {\n // A secret `m8_` key in a browser is readable by every visitor. Bundlers do not\n // stop you importing this entry into client code, so fail loudly the moment it\n // runs there rather than shipping a leaked key quietly. (Edge/worker runtimes\n // have no `document`, so they are unaffected.)\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new Error(\n \"@m8tes/sdk is server-only: it holds your secret m8_ API key, which anyone \" +\n \"could read out of a browser bundle. To render an agent in the browser use \" +\n \"@m8tes/react, which talks to a server proxy that keeps the key on your server. \" +\n \"See https://www.m8tes.ai/docs/embed-a-ui\",\n );\n }\n const apiKey = options.apiKey ?? globalThis.process?.env?.[\"M8TES_API_KEY\"];\n if (!apiKey) {\n throw new Error(\n \"@m8tes/sdk: no API key. Pass `new M8tes({ apiKey })` or set M8TES_API_KEY. \" +\n \"Create a key at https://m8tes.ai/developer.\",\n );\n }\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const timeout = options.timeout ?? 300_000;\n const maybeFetch = options.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!maybeFetch) {\n throw new Error(\n \"@m8tes/sdk: no global fetch. Use Node 18+ or pass `fetch` in the client options.\",\n );\n }\n const fetchImpl: FetchLike = maybeFetch; // narrowed; safe to capture in closures\n\n async function toError(\n res: Response,\n url: string,\n errOpts: ErrorFromResponseOptions,\n ): Promise<M8tesApiError> {\n const text = await res.text().catch(() => \"\");\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n const parsed = parseErrorEnvelope(res.status, body, res.headers);\n const message = diagnose(res, text, body, url) ?? (body ? parsed.message : text || parsed.message);\n return new (errorClassForStatus(res.status, errOpts))(message, parsed.fields);\n }\n\n /**\n * Merge header maps case-insensitively.\n *\n * HTTP header names are case-insensitive, but a plain object is not: a caller\n * passing `Content-Type` and the SDK setting `content-type` produced BOTH, and\n * fetch joins duplicates into `application/json, application/json`, which the\n * server cannot parse. Everything is lowercased so last-writer-wins actually\n * wins.\n */\n function mergeHeaders(...sources: Array<Record<string, string> | undefined>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const src of sources) {\n for (const [k, v] of Object.entries(src ?? {})) out[k.toLowerCase()] = v;\n }\n return out;\n }\n\n /** One attempt. Layers the client timeout onto any caller-supplied signal. */\n async function attempt(method: string, url: string, opts: RequestOptions): Promise<Response> {\n // Auth LAST: a server proxy that forwards inbound request headers into\n // `headers` would otherwise silently replace the SDK's credential with a\n // client-supplied one. The key you constructed the client with always wins.\n const headers = mergeHeaders(options.headers, opts.headers, {\n authorization: `Bearer ${apiKey}`,\n });\n const init: RequestInit = { method, headers };\n if (opts.form !== undefined) {\n // Deliberately no content-type: fetch adds it WITH the multipart boundary.\n // A content-type configured globally (or per-request) would suppress that\n // header, leaving the server unable to parse the body. Keys are lowercased\n // by mergeHeaders, so one delete covers every casing the caller used.\n delete headers[\"content-type\"];\n init.body = opts.form;\n } else if (opts.body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n init.body = JSON.stringify(opts.body);\n }\n const timer = AbortSignal.timeout(timeout);\n init.signal = opts.signal ? AbortSignal.any([opts.signal, timer]) : timer;\n return fetchImpl(url, init);\n }\n\n /**\n * Retry loop shared by `request` and `stream`. Returns the OK response; throws\n * a typed error once the attempts are spent or the status is not retryable.\n */\n async function send(\n method: string,\n path: string,\n opts: RequestOptions,\n errOpts: ErrorFromResponseOptions = {},\n ): Promise<Response> {\n const url = `${baseUrl}${path}${opts.query ?? \"\"}`;\n // Same merge (and lowercasing) `attempt` applies, so this sees exactly the\n // headers that go on the wire — a key set globally on the client counts too.\n const idempotent = isRetryable(method, path, mergeHeaders(options.headers, opts.headers));\n let lastNetworkError: unknown;\n\n for (let i = 0; i < MAX_ATTEMPTS; i++) {\n const isLast = i === MAX_ATTEMPTS - 1;\n let res: Response;\n try {\n res = await attempt(method, url, opts);\n } catch (e) {\n // A caller-initiated abort is intent, not a fault — never retry or wrap it.\n if (opts.signal?.aborted) throw e;\n lastNetworkError = e;\n if (!idempotent || isLast) {\n throw new APIError(e instanceof Error ? e.message : String(e), {\n type: \"api_error\",\n code: 0,\n status: 0,\n });\n }\n await backoff(INITIAL_BACKOFF_MS * 2 ** i, opts.signal);\n if (opts.signal?.aborted) throw e;\n continue;\n }\n\n if (res.ok) return res;\n if (!RETRYABLE_STATUS.has(res.status) || !idempotent || isLast) {\n throw await toError(res, url, errOpts);\n }\n const retryAfter = res.status === 429 ? parseRetryAfter(res.headers.get(\"retry-after\")) : undefined;\n // Drain the body so the connection can be reused on the next attempt.\n await res.text().catch(() => \"\");\n await backoff(retryAfter !== undefined ? retryAfter * 1000 : INITIAL_BACKOFF_MS * 2 ** i, opts.signal);\n // The caller gave up while we were waiting — surface their abort rather\n // than burning the remaining attempts on a request nobody wants.\n if (opts.signal?.aborted) throw await toError(res, url, errOpts);\n }\n\n throw new APIError(\n lastNetworkError instanceof Error ? lastNetworkError.message : \"Max retries exceeded\",\n { type: \"api_error\", code: 0, status: 0 },\n );\n }\n\n return {\n baseUrl,\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const res = await send(method, path, opts);\n if (res.status === 204) return undefined as T;\n const text = await res.text();\n return (text ? (JSON.parse(text) as T) : (undefined as T));\n },\n\n raw(method: string, path: string, opts: RequestOptions = {}): Promise<Response> {\n return send(method, path, opts);\n },\n\n async *stream(method: string, path: string, opts: StreamRequestOptions = {}) {\n // A 409 on a stream route means \"the run already finished\" — surfaced as\n // RunNotStreamingError so callers fall back to runs.get() instead of\n // treating a completed run as an error.\n const res = await send(method, path, opts, { conflictIsNotStreaming: true });\n // An idempotent retry was answered from the run the first attempt created.\n // Hand it to the resource, which joins that run's stream — the caller asked\n // for a stream and still gets one, without learning a retry happened.\n if (opts.onReplay && res.headers.get(REPLAY_HEADER)) {\n const run = (await res.json()) as { id: number; status: string };\n yield* opts.onReplay(run);\n return;\n }\n if (!res.body) return;\n const normalizer = opts.normalizer ?? createNormalizer();\n const decoder = createSseDecoder({ onMalformed: options.onMalformed });\n const reader = res.body.getReader();\n const td = new TextDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n for (const frame of decoder.push(td.decode(value, { stream: true }))) {\n yield* normalizer.push(frame);\n }\n }\n for (const frame of decoder.flush()) yield* normalizer.push(frame);\n } finally {\n // cancel() tears down the connection on an early break (caller stopped\n // iterating); releaseLock() alone would leak a live SSE connection.\n try {\n await reader.cancel();\n } catch {\n try {\n reader.releaseLock();\n } catch {\n /* already released */\n }\n }\n }\n },\n };\n}\n","/**\n * Cursor pagination over the V2 `ListResponse` envelope (`{data, has_more}`).\n *\n * Mirrors the Python SDK's `SyncPage` (`sdk/py/m8tes/_types.py`): a page is the\n * raw response plus an async iterator that walks every remaining page for you.\n *\n * The cursor is the last item's `id`, or its `name` for `/apps` (the one resource\n * keyed by name). Same rule as Python, so both SDKs paginate identically.\n */\n\nexport interface ListResponse<T> {\n data: T[];\n hasMore: boolean;\n /** Cursor for `?starting_after=` when `hasMore` is true; mirrors the Python SDK. */\n nextStartingAfter?: string | number | null;\n}\n\n/** A page of results. `for await (const item of page)` walks ALL pages. */\nexport class Page<T> implements ListResponse<T>, AsyncIterable<T> {\n readonly data: T[];\n readonly hasMore: boolean;\n readonly nextStartingAfter?: string | number | null;\n /** Fetches the next page given a cursor. Absent on a terminal page. */\n private readonly fetchNext?: (startingAfter: string | number) => Promise<Page<T>>;\n\n constructor(\n data: T[],\n hasMore: boolean,\n fetchNext?: (startingAfter: string | number) => Promise<Page<T>>,\n nextStartingAfter?: string | number | null,\n ) {\n this.data = data;\n this.hasMore = hasMore;\n this.fetchNext = fetchNext;\n this.nextStartingAfter = nextStartingAfter ?? null;\n }\n\n /**\n * Auto-paging: yields every item across every page.\n *\n * Stops if the cursor ever fails to advance. A server that returns the same\n * page again with `has_more: true` — a caching layer, a replica lagging, a bug\n * — would otherwise spin forever, re-yielding the same rows and never\n * returning. Terminating is the only safe response: the caller gets the items\n * it did see rather than a hung process.\n */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page: Page<T> = this;\n const seen = new Set<string | number>();\n for (;;) {\n yield* page.data;\n const last = page.data.at(-1) as { id?: unknown; name?: unknown } | undefined;\n if (!page.hasMore || !last || !page.fetchNext) return;\n let cursor: string | number | undefined =\n page.nextStartingAfter === null || page.nextStartingAfter === undefined\n ? undefined\n : page.nextStartingAfter;\n if (cursor === undefined) {\n cursor =\n typeof last.id === \"number\" || typeof last.id === \"string\"\n ? last.id\n : typeof last.name === \"string\"\n ? last.name\n : undefined;\n }\n if (cursor === undefined || seen.has(cursor)) return;\n seen.add(cursor);\n page = await page.fetchNext(cursor);\n }\n }\n\n /** Every item across every page, collected. Prefer iteration for large sets. */\n async all(): Promise<T[]> {\n const out: T[] = [];\n for await (const item of this) out.push(item);\n return out;\n }\n}\n","/**\n * Request-parameter plumbing. Deliberately tiny.\n *\n * This package speaks the API's own **snake_case** on the wire, in params AND in\n * response types — the same names as `/docs/api-reference` and the Python SDK, and\n * the convention `openai`, `stripe`, and `@anthropic-ai/sdk` all use. So there is\n * no case-mapping layer: request bodies are passed through, and responses are\n * returned exactly as the API sent them.\n *\n * That is not just a style choice. The mapping layer this replaced corrupted\n * caller-defined keys twice: `answers` is keyed by AskUserQuestion TEXT, and\n * `output_schema` carries the caller's own JSON-Schema property names — a key\n * rewriter silently changed both. With no rewriter, that class of bug cannot exist.\n *\n * THE BOUNDARY, precisely — snake_case is for API DATA, camelCase for SDK surfaces:\n *\n * snake_case request params + response bodies `user_id`, `created_at`,\n * (anything that crosses the wire) `output_data`, `enable_memory`\n *\n * camelCase things the SDK owns and the API `new M8tes({ apiKey })`,\n * never sees: client options, method `client.runs.createAsync()`,\n * names, `RunStream`, and the `stream.runId`,\n * normalized events in `event.requestId`\n * `@m8tes/sdk/protocol` (our own\n * format, shared with @m8tes/react's\n * UI — not the REST wire)\n *\n * So: if you read the name in `/docs/api-reference`, it is snake_case here too.\n * If it is a TypeScript construct we invented, it is camelCase.\n */\n\n/** Drop `undefined` so an omitted option is absent rather than an explicit\n * `null` — which the API reads as \"clear this field\". An explicit `null`\n * survives, because that IS how you clear one. */\nexport function toBody(params: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined) out[k] = v;\n }\n return out;\n}\n\n/** Query string from params, skipping `undefined`/`null`. Returns \"\" when empty. */\nexport function toQuery(params: Record<string, unknown>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v === undefined || v === null) continue;\n q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : \"\";\n}\n\n/**\n * `agent_id` is the canonical name; `teammate_id` is the permanent legacy alias\n * and the actual wire field. Passing conflicting values is an error rather than a\n * silent pick — mirrors `_resolve_agent_id` in the Python SDK.\n */\nexport function resolveAgentId(\n teammateId: number | undefined,\n agentId: number | undefined,\n): number | undefined {\n if (agentId !== undefined && teammateId !== undefined && agentId !== teammateId) {\n throw new Error(\"Pass agent_id or teammate_id, not both\");\n }\n return teammateId ?? agentId;\n}\n","/**\n * `client.agents` — the reusable agent personas runs execute as.\n *\n * The V2 resource is `agents`; `client.teammates` is a permanent alias because\n * the DB model and older API docs use that name. Mirrors\n * `sdk/py/m8tes/_resources/teammates.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { Agent, EmailInbox, JsonObject, PermissionMode, WebhookToggle } from \"../types\";\n\nexport interface AgentCreateParams {\n name?: string;\n /** The agent's standing instructions: who it is and how it works. */\n instructions?: string;\n /** Tool slugs it may use, e.g. `[\"gmail\", \"slack\"]`. */\n tools?: string[];\n role?: string;\n goals?: string;\n /** Your id for the end-user who owns this agent. */\n user_id?: string;\n metadata?: JsonObject;\n model?: string;\n effort?: string;\n default_permission_mode?: PermissionMode;\n /** Built-in tool toggles. Omit to inherit the platform default. */\n enable_memory?: boolean;\n enable_history?: boolean;\n enable_task_setup_tools?: boolean;\n enable_feedback?: boolean;\n enable_self_improvement?: boolean;\n /** Give the agent its own email inbox on create. */\n email_inbox?: boolean;\n /** Give the agent a webhook trigger URL on create. */\n webhook?: boolean;\n /** Start from a prebuilt persona, e.g. `\"ppc-manager\"`. Template improvements\n * keep flowing in on later reads unless you override the field. */\n from_template?: string;\n}\n\n/**\n * PATCH /agents/{id} accepts exactly these fields (backend `TeammateUpdate`).\n * Create-only fields are NOT here on purpose: sending `webhook` or `email_inbox`\n * to PATCH returns 200 and silently does nothing, which reads as a working call.\n * Use `enableWebhook()` / `enableEmailInbox()` instead.\n *\n * `null` is meaningful: it CLEARS the field back to the platform default.\n */\nexport interface AgentUpdateParams {\n name?: string | null;\n instructions?: string | null;\n tools?: string[] | null;\n role?: string | null;\n goals?: string | null;\n metadata?: JsonObject | null;\n model?: string | null;\n effort?: string | null;\n default_permission_mode?: PermissionMode | null;\n /** Who can see this agent. Omit or null leaves it unchanged. */\n visibility?: \"personal\" | \"organization\" | null;\n allowed_senders?: string[] | null;\n enable_memory?: boolean | null;\n enable_history?: boolean | null;\n enable_task_setup_tools?: boolean | null;\n enable_feedback?: boolean | null;\n enable_self_improvement?: boolean | null;\n}\n\nexport interface AgentListParams {\n user_id?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface AgentsResource {\n create(params?: AgentCreateParams): Promise<Agent>;\n list(params?: AgentListParams): Promise<Page<Agent>>;\n get(agentId: number, params?: { user_id?: string }): Promise<Agent>;\n update(agentId: number, params: AgentUpdateParams & { user_id?: string }): Promise<Agent>;\n delete(agentId: number, params?: { user_id?: string }): Promise<void>;\n /** Turn on the webhook trigger; returns the URL to POST to.\n * `user_id` scopes to one end-user (404 on mismatch), like get/update/delete. */\n enableWebhook(agentId: number, params?: { user_id?: string }): Promise<WebhookToggle>;\n disableWebhook(agentId: number, params?: { user_id?: string }): Promise<void>;\n /** Turn on the agent's email inbox; returns the address that starts runs. */\n enableEmailInbox(agentId: number, params?: { user_id?: string }): Promise<EmailInbox>;\n disableEmailInbox(agentId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createAgentsResource(http: Http): AgentsResource {\n return {\n create(params = {}) {\n return http.request<Agent>(\"POST\", \"/agents/\", { body: toBody({ ...params }) });\n },\n\n async list(params = {}) {\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<Agent>> => {\n const res = await http.request<{ data: Agent[]; has_more?: boolean; next_starting_after?: string | number | null }>(\"GET\", \"/agents/\", {\n query: toQuery(p),\n });\n return new Page<Agent>(\n res?.data ?? [],\n res?.has_more ?? false,\n (starting_after) => fetchPage({ ...p, starting_after }),\n res?.next_starting_after,\n );\n };\n return fetchPage({ ...params });\n },\n\n get(agentId, params = {}) {\n return http.request<Agent>(\"GET\", `/agents/${seg(agentId)}`, { query: toQuery(params) });\n },\n\n update(agentId, params) {\n // user_id scopes the request (query param); everything else is the patch.\n const { user_id, ...patch } = params;\n return http.request<Agent>(\"PATCH\", `/agents/${seg(agentId)}`, {\n body: toBody(patch),\n query: toQuery({ user_id }),\n });\n },\n\n async delete(agentId, params = {}) {\n await http.request(\"DELETE\", `/agents/${seg(agentId)}`, { query: toQuery(params) });\n },\n\n enableWebhook(agentId, params = {}) {\n return http.request<WebhookToggle>(\"POST\", `/agents/${seg(agentId)}/webhook`, {\n body: {},\n query: toQuery(params),\n });\n },\n\n async disableWebhook(agentId, params = {}) {\n await http.request(\"DELETE\", `/agents/${seg(agentId)}/webhook`, { query: toQuery(params) });\n },\n\n enableEmailInbox(agentId, params = {}) {\n return http.request<EmailInbox>(\"POST\", `/agents/${seg(agentId)}/email-inbox`, {\n body: {},\n query: toQuery(params),\n });\n },\n\n async disableEmailInbox(agentId, params = {}) {\n await http.request(\"DELETE\", `/agents/${seg(agentId)}/email-inbox`, { query: toQuery(params) });\n },\n };\n}\n","/**\n * `client.apps` — the tools agents act in, and each end-user's connections to them.\n *\n * Connections are scoped: pass `user_id` and the connection belongs to that\n * end-user, so the agent acts with THEIR Gmail/Stripe/Slack rather than yours.\n * In an embed that matters a lot — an account-level connection means a\n * prompt-injected agent could act on your behalf.\n *\n * Mirrors `sdk/py/m8tes/_resources/apps.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { App, AppConnectionInitiation, AppConnectionResult } from \"../types\";\n\nexport interface AppsResource {\n /**\n * Every available tool, with connection status for the given scope.\n *\n * NOT paginated and NOT cursor-able: `GET /apps/` accepts only `user_id` and\n * returns the whole catalog. Sending `limit` or `starting_after` gets a 422\n * (`unknown_query_parameter`) — verified against a live backend, which is also\n * how the same bug was found in the published Python SDK. A `Page` is still\n * returned so `for await` works uniformly across resources.\n */\n list(params?: { user_id?: string }): Promise<Page<App>>;\n /** True when this app is connected for the given scope. */\n isConnected(appName: string, params?: { user_id?: string }): Promise<boolean>;\n /**\n * Start an OAuth connection. Send the user to the returned `authorization_url`,\n * then pass the returned `connection_id` to `connectComplete()`.\n *\n * `redirect_uri` is REQUIRED and is spelled `_uri`, not `_url` — the API 422s\n * on anything else.\n */\n connectOauth(\n appName: string,\n params: { redirect_uri: string; user_id?: string },\n ): Promise<AppConnectionInitiation>;\n /** Connect an app that authenticates with a key instead of OAuth. */\n connectApiKey(\n appName: string,\n params: { api_key: string; user_id?: string },\n ): Promise<AppConnectionResult>;\n /** Finish an OAuth connection after the user returns. `connection_id` comes\n * from `connectOauth()` and is required. */\n connectComplete(\n appName: string,\n params: { connection_id: string; user_id?: string },\n ): Promise<AppConnectionResult>;\n disconnect(appName: string, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createAppsResource(http: Http): AppsResource {\n // A local, not `this.list` — a destructured `const { isConnected } =\n // client.apps` would otherwise throw. (The same bug shipped in\n // `runs.createAndWait`; nothing in this package should depend on `this`.)\n const list = async (params: { user_id?: string } = {}): Promise<Page<App>> => {\n // Only `user_id` — see the interface comment. No fetchNext: there is no\n // cursor to follow, and inventing one would 422.\n const res = await http.request<{ data: App[]; has_more?: boolean; next_starting_after?: string | number | null }>(\"GET\", \"/apps/\", {\n query: toQuery({ user_id: params.user_id }),\n });\n return new Page<App>(res?.data ?? [], res?.has_more ?? false, undefined, res?.next_starting_after);\n };\n\n return {\n list,\n\n async isConnected(appName, params = {}) {\n // The list endpoint reports connection state per scope; a single-app filter\n // would be a second contract to keep in sync for no gain.\n const { data } = await list(params);\n return data.find((a) => a.name === appName)?.connected ?? false;\n },\n\n connectOauth(appName, params) {\n return http.request<AppConnectionInitiation>(\"POST\", `/apps/${seg(appName)}/connect`, {\n body: toBody({ ...params }),\n });\n },\n\n connectApiKey(appName, params) {\n return http.request<AppConnectionResult>(\"POST\", `/apps/${seg(appName)}/connect/api-key`, {\n body: toBody({ ...params }),\n });\n },\n\n connectComplete(appName, params) {\n return http.request<AppConnectionResult>(\"POST\", `/apps/${seg(appName)}/connect/complete`, {\n body: toBody({ ...params }),\n });\n },\n\n async disconnect(appName, params = {}) {\n await http.request(\"DELETE\", `/apps/${seg(appName)}/connections`, { query: toQuery(params) });\n },\n };\n}\n","/**\n * `client.account` — the two operations that act on the whole account rather\n * than anything inside it: take your data out, and shut the account down.\n *\n * Both exist to satisfy the GDPR/CCPA rights to access and to erasure, so they\n * are here for compliance flows you have to be able to run programmatically —\n * a data-subject request you are forwarding, or an offboarding path in your own\n * product. Neither takes parameters: they always apply to the account behind\n * the API key you authenticated with, and there is no `user_id` scoping. To\n * remove one end-user's data instead, use `client.users.delete()`.\n *\n * Mirrors `sdk/py/m8tes/_resources/account.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { AccountDeletion, AccountExport } from \"../types\";\n\nexport interface AccountResource {\n /**\n * Hand a customer (or a regulator) everything the account holds — the\n * GDPR/CCPA right to access.\n *\n * The document covers the account's agents, tasks, runs, documents, memories,\n * and integration metadata. Credentials and other secrets are never included,\n * so an export is safe to forward but is NOT a backup you can restore from.\n * It is a single JSON body, not a stream: a large account produces a large\n * response, so allow for it in your request timeout.\n */\n export(): Promise<AccountExport>;\n\n /**\n * Close the account — the GDPR/CCPA right to erasure.\n *\n * Soft-delete, and it takes effect at once: sessions and the API key are\n * revoked, billing is canceled, and all automation stops, with the data\n * erased after a grace period. In other words the key you just called this\n * with is dead afterwards, so nothing else in the SDK will work.\n */\n delete(): Promise<AccountDeletion>;\n}\n\nexport function createAccountResource(http: Http): AccountResource {\n return {\n export() {\n return http.request<AccountExport>(\"GET\", \"/account/export\");\n },\n\n delete() {\n return http.request<AccountDeletion>(\"DELETE\", \"/account\");\n },\n };\n}\n","/**\n * `client.users` — your end-users, the multi-tenancy boundary.\n *\n * `user_id` is YOUR identifier for a customer; the platform stores it as\n * `end_user_id` and isolates that person's memory, run history, and tool\n * connections strictly. There is no fallback to account-level data.\n *\n * Registering an end-user here is optional — passing `user_id` on a run creates\n * them implicitly. Do it explicitly when you want per-user budgets and rate\n * limits. Mirrors `sdk/py/m8tes/_resources/users.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { EndUser, EndUserUsage, JsonObject } from \"../types\";\n\nexport interface EndUserCreateParams {\n /** Your id for this person. Any stable string. */\n user_id: string;\n name?: string;\n email?: string;\n company?: string;\n metadata?: JsonObject;\n /** Cap this end-user's runs per billing period. */\n run_limit?: number;\n /** Cap this end-user's spend per billing period, in cents. */\n cost_limit_cents?: number;\n /** Cap this end-user's runs per minute. Exceeding it returns 429. */\n rate_per_minute?: number;\n}\n\n/** `null` CLEARS a cap (inherit the account default); omitting leaves it alone. */\nexport interface EndUserUpdateParams {\n name?: string | null;\n email?: string | null;\n company?: string | null;\n metadata?: JsonObject | null;\n run_limit?: number | null;\n cost_limit_cents?: number | null;\n rate_per_minute?: number | null;\n}\n\nexport interface PageParams {\n limit?: number;\n starting_after?: number;\n}\n\nexport interface UsersResource {\n create(params: EndUserCreateParams): Promise<EndUser>;\n list(params?: PageParams): Promise<Page<EndUser>>;\n get(userId: string): Promise<EndUser>;\n update(userId: string, params: EndUserUpdateParams): Promise<EndUser>;\n delete(userId: string): Promise<void>;\n /** Per-end-user token, run, and cost usage against their limits. */\n usage(params?: PageParams & { user_id?: string }): Promise<Page<EndUserUsage>>;\n}\n\n/** Shared cursor-paging helper: the envelope is identical across list routes. */\nexport function pager<T>(http: Http, path: string): (p: Record<string, unknown>) => Promise<Page<T>> {\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<T>> => {\n const res = await http.request<{ data: T[]; has_more?: boolean; next_starting_after?: string | number | null }>(\"GET\", path, {\n query: toQuery(p),\n });\n return new Page<T>(\n res?.data ?? [],\n res?.has_more ?? false,\n (starting_after) => fetchPage({ ...p, starting_after }),\n res?.next_starting_after,\n );\n };\n return fetchPage;\n}\n\nexport function createUsersResource(http: Http): UsersResource {\n return {\n create(params) {\n return http.request<EndUser>(\"POST\", \"/users/\", { body: toBody({ ...params }) });\n },\n\n list(params = {}) {\n return pager<EndUser>(http, \"/users/\")({ ...params });\n },\n\n get(userId) {\n return http.request<EndUser>(\"GET\", `/users/${seg(userId)}`);\n },\n\n update(userId, params) {\n return http.request<EndUser>(\"PATCH\", `/users/${seg(userId)}`, {\n body: toBody({ ...params }),\n });\n },\n\n async delete(userId) {\n await http.request(\"DELETE\", `/users/${seg(userId)}`);\n },\n\n usage(params = {}) {\n return pager<EndUserUsage>(http, \"/usage/end-users\")({ ...params });\n },\n };\n}\n","/**\n * `client.billing` — what you have spent, what you may spend, and the ceiling.\n *\n * This is the resource you reach for when cost is a product requirement rather\n * than an afterthought: read current-period usage (runs, model spend, accrued\n * overage), break spend down by day / end-user / agent / model, fetch the public\n * plan catalog, and set the caps — the monthly overage cap on plan accounts, and\n * on prepaid accounts the token balance, top-ups, auto-reload, and the\n * low-balance alert threshold.\n *\n * An embed developer capping what their own customers can burn lives here: pair\n * `usageTimeseries({ user_id })` with the per-end-user limits on `client.users`\n * to meter each tenant, and `setOverage` / `setAutoReload` to bound the account\n * as a whole.\n *\n * Mirrors `sdk/py/m8tes/_resources/billing.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { resolveAgentId, toBody, toQuery } from \"../params\";\nimport type { Balance, Plan, Receipt, Usage, UsageTimeseries } from \"../types\";\nimport { type PageParams, pager } from \"./users\";\n\nexport interface UsageTimeseriesParams {\n /** Inclusive ISO date (`\"2026-07-01\"`), UTC days. Defaults to 30 days ago. */\n start_date?: string;\n /** Inclusive ISO date. Defaults to today. */\n end_date?: string;\n /** Scope to one end-user. */\n user_id?: string;\n /** Scope to one agent. */\n agent_id?: number;\n /** Permanent legacy alias for `agent_id` — the same wire field. */\n teammate_id?: number;\n /** Creation stamp: `\"api\"` embedding, `\"platform\"` first-party. Not settlement. */\n surface?: \"api\" | \"platform\";\n /** Where the run settled: `\"wallet\"` is the prepaid ledger. */\n settled_meter?: \"wallet\" | \"plan\" | \"released\" | \"own_sub\";\n /** `\"model\"` adds per-model slices to every bucket's `models`. The route\n * accepts this one value only, so it is a literal rather than a string. */\n group_by?: \"model\";\n}\n\nexport interface OverageParams {\n enabled: boolean;\n /** Hard ceiling on overage spend per period, in cents. */\n monthly_cap_cents: number;\n}\n\nexport interface TopupParams {\n /** Cents to add. $5 minimum, $1M maximum. */\n amount_cents: number;\n}\n\n/**\n * Enabling auto-reload REQUIRES both amounts; disabling takes neither. Modelled\n * as a union so `{ enabled: true }` alone is a compile error rather than a 422.\n */\nexport type AutoReloadParams =\n | {\n enabled: true;\n /** Reload when the balance drops below this, in cents. */\n threshold_cents: number;\n /** Cents to charge per reload. $5–$10,000. */\n amount_cents: number;\n }\n | {\n enabled: false;\n /** Amounts may still be updated while disabled; the API applies them. */\n threshold_cents?: number;\n amount_cents?: number;\n };\n\nexport interface AlertThresholdParams {\n /** Balance (cents) at which the low-balance warning fires. `0` warns only on depletion. */\n low_balance_threshold_cents: number;\n}\n\nexport interface BillingResource {\n /** Where you stand this period: plan, runs used vs included, model spend, and overage state. */\n usage(): Promise<Usage>;\n\n /**\n * Spend broken down by UTC day — the series to chart, alert on, or reconcile\n * against an invoice. Buckets are zero-filled across the whole window, so the\n * array is safe to plot without gap-handling. Cost matches `usage().cost_used`\n * semantics, so the series always reconciles with period totals. With\n * `group_by: \"model\"`, runs that predate model attribution fold\n * into a `\"unknown\"` slice rather than disappearing.\n */\n usageTimeseries(params?: UsageTimeseriesParams): Promise<UsageTimeseries>;\n\n /**\n * Proof of payment for finance: one row per paid prepaid top-up, newest first.\n * `receipt_url` can be `null` when Stripe can no longer retrieve the session.\n */\n receipts(params?: PageParams): Promise<Page<Receipt>>;\n\n /** What the paid plans include and cost — for your own pricing page or upgrade\n * prompt. Public (paid) plans only, straight from the canonical catalog, and\n * returned as a plain array rather than a page. */\n plans(): Promise<Plan[]>;\n\n /**\n * Decide whether runs may continue past your plan's included allotment, and how\n * far. Off by default; once enabled, extra runs bill at the per-run overage rate\n * until `monthly_cap_cents` is reached. Returns the refreshed usage so you can\n * confirm the new state without a second call.\n */\n setOverage(params: OverageParams): Promise<Usage>;\n\n /** How much prepaid credit is left, and where it went (prepaid-billed accounts).\n * Amounts are micro-USD; `balance_usd` is a rounded display string. */\n balance(): Promise<Balance>;\n\n /**\n * Add credit when a human is present to pay. Returns a Stripe Checkout URL to\n * send the buyer to — nothing is credited until they complete payment.\n */\n topup(params: TopupParams): Promise<string>;\n\n /**\n * Keep credit topped up without a human, so runs never stop for an empty wallet:\n * a balance below `threshold_cents` charges `amount_cents` to the saved card\n * off-session. Enabling requires a saved payment method (any completed top-up\n * Checkout saves one) — without it this throws a billing error with code\n * `NO_SAVED_PAYMENT_METHOD`. Disabling needs only `enabled: false`. At most one\n * reload fires per 6-hour window. Returns the refreshed balance.\n */\n setAutoReload(params: AutoReloadParams): Promise<Balance>;\n\n /**\n * Choose when you want to hear about a draining balance. The critical tier is\n * fixed at 20% of the value you set, and `0` warns only on depletion. Warnings\n * arrive by email and as `balance.low` / `balance.critical` / `balance.depleted`\n * webhook events. Returns the refreshed balance.\n */\n setAlertThreshold(params: AlertThresholdParams): Promise<Balance>;\n}\n\nexport function createBillingResource(http: Http): BillingResource {\n return {\n usage() {\n return http.request<Usage>(\"GET\", \"/usage/\");\n },\n\n usageTimeseries(params = {}) {\n const { agent_id, teammate_id, ...rest } = params;\n const query = toQuery(\n toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) }),\n );\n return http.request<UsageTimeseries>(\"GET\", \"/usage/timeseries\", { query });\n },\n\n receipts(params = {}) {\n return pager<Receipt>(http, \"/billing/receipts\")({ ...params });\n },\n\n plans() {\n return http.request<Plan[]>(\"GET\", \"/billing/plans\");\n },\n\n setOverage(params) {\n return http.request<Usage>(\"PATCH\", \"/billing/overage\", { body: toBody({ ...params }) });\n },\n\n balance() {\n return http.request<Balance>(\"GET\", \"/billing/balance\");\n },\n\n async topup(params) {\n const res = await http.request<{ checkout_url: string }>(\"POST\", \"/billing/topup\", {\n body: toBody({ ...params }),\n });\n return res.checkout_url;\n },\n\n setAutoReload(params) {\n return http.request<Balance>(\"PATCH\", \"/billing/auto-reload\", {\n body: toBody({ ...params }),\n });\n },\n\n setAlertThreshold(params) {\n return http.request<Balance>(\"PATCH\", \"/billing/alert-settings\", {\n body: toBody({ ...params }),\n });\n },\n };\n}\n","/**\n * `client.memories` — pre-load what an agent already knows about someone.\n *\n * A run starts cold unless it has memories to draw on. Writing them here lets you\n * seed an end-user's context from data you already hold (plan, timezone, past\n * decisions, preferences) so the first run behaves like the tenth, instead of\n * waiting for the agent to learn it over several conversations.\n *\n * `user_id` is the scope, and the scopes never mix: with it, the memory belongs to\n * that one end-user and is visible only to runs carrying the same `user_id`;\n * without it, the memory is account-level and visible only to runs that carry no\n * `user_id`. There is no inheritance between the two — an account-level memory is\n * NOT a fallback for an end-user run.\n *\n * Documented at `/docs/users`. Mirrors `sdk/py/m8tes/_resources/memories.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport { pager } from \"./users\";\nimport type { Memory } from \"../types\";\n\nexport interface MemoryCreateParams {\n /** The fact to remember, in plain language. */\n content: string;\n /** Scope it to one end-user. Omit for an account-level memory. */\n user_id?: string;\n}\n\nexport interface MemoryListParams {\n /** Scope to read. Omit to read account-level memories. */\n user_id?: string;\n /**\n * Keyword filter on content (case-insensitive substring). It only narrows the\n * chosen scope — it never reaches across into the other one — and paging\n * applies to the filtered set.\n */\n query?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface MemoryUpdateParams {\n /** Replaces the stored text outright. */\n content: string;\n /** The scope the memory lives in. Must match, or the memory is not found. */\n user_id?: string;\n}\n\nexport interface MemoriesResource {\n /**\n * Teach an agent a fact up front, before anyone runs it.\n *\n * Throws a `ConflictError` (409) when the scope is already at its memory\n * capacity, or when identical content is already stored in it — so this is\n * safe to call repeatedly only if you handle that error.\n */\n create(params: MemoryCreateParams): Promise<Memory>;\n /** Audit or display what an agent knows about one end-user (or the account). */\n list(params?: MemoryListParams): Promise<Page<Memory>>;\n /** Correct a fact that changed, keeping its id — rather than delete + re-create. */\n update(memoryId: number, params: MemoryUpdateParams): Promise<Memory>;\n /** Make an agent forget something, e.g. on an end-user's erasure request. */\n delete(memoryId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createMemoriesResource(http: Http): MemoriesResource {\n return {\n create(params) {\n return http.request<Memory>(\"POST\", \"/memories/\", { body: toBody({ ...params }) });\n },\n\n list(params = {}) {\n return pager<Memory>(http, \"/memories/\")({ ...params });\n },\n\n update(memoryId, { user_id, content }) {\n // Scope travels in the query string, the new text in the body.\n return http.request<Memory>(\"PATCH\", `/memories/${seg(memoryId)}`, {\n query: toQuery({ user_id }),\n body: toBody({ content }),\n });\n },\n\n async delete(memoryId, params = {}) {\n await http.request(\"DELETE\", `/memories/${seg(memoryId)}`, {\n query: toQuery({ user_id: params.user_id }),\n });\n },\n };\n}\n","/**\n * `client.models` — find out which `model` values are actually valid, and what\n * they cost, instead of guessing from the docs.\n *\n * `model` is a plain string everywhere in this SDK, which keeps new models\n * usable the day they're enabled but means a typo is only caught by the API. Ask\n * this route instead: it returns the models your account can select right now\n * (Anthropic and not — the set grows without an SDK release), which one is the\n * default, and the per-million-token prices the platform bills you at, so you\n * can estimate spend before starting a run.\n *\n * Mirrors `sdk/py/m8tes/_resources/models.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport type { Model } from \"../types\";\n\nexport interface ModelsResource {\n /**\n * The models you can pass as `model` on an agent or a run, with USD pricing\n * per million tokens.\n *\n * Omit `model` on an agent/run to get the entry flagged `default: true` — that\n * flag is per-viewer, so the default you see here is the default you'd get.\n *\n * Takes no arguments and has no cursor: `GET /models/` returns the whole\n * catalog in one response. A `Page` is still returned so `for await` works the\n * same as on every other list, but it never fetches a second page.\n */\n /**\n * The model catalog. Check `zdr_supported` before sending customer data: a\n * non-ZDR model is allowed on the API but may retain inputs and outputs.\n */\n list(): Promise<Page<Model>>;\n}\n\nexport function createModelsResource(http: Http): ModelsResource {\n return {\n async list() {\n const res = await http.request<{ data: Model[]; has_more?: boolean; next_starting_after?: string | number | null }>(\"GET\", \"/models/\");\n // No fetchNext: the route accepts no cursor, matching the Python SDK's\n // SyncPage built without `_fetch_next`.\n return new Page<Model>(res?.data ?? [], res?.has_more ?? false, undefined, res?.next_starting_after);\n },\n };\n}\n","/** Account-level OAuth subscriptions used by the Claude Code execution harness. */\n\nimport type { Http } from \"../http\";\nimport { seg } from \"../protocol/seg\";\n\nexport type ModelConnectionProvider = \"claude\" | \"openai\" | \"xai\" | \"gemini\";\nexport type AuthorizableModelConnectionProvider = \"openai\" | \"xai\" | \"gemini\";\nexport type DeviceModelConnectionProvider = \"openai\" | \"xai\";\nexport type CodeModelConnectionProvider = \"gemini\";\n\nexport interface ModelConnection {\n\tprovider: ModelConnectionProvider;\n\tdisplay_name: string;\n\tconnected: boolean;\n\tstatus?: string | null;\n\taccount_label?: string | null;\n\texpires_at?: string | null;\n}\n\nexport interface ModelAuthorization {\n\tprovider: AuthorizableModelConnectionProvider;\n\tstate: string;\n\tstatus: \"pending\" | \"connected\";\n\tauthorization_url?: string | null;\n\tuser_code?: string | null;\n\texpires_at?: string | null;\n\tinterval_seconds: number;\n}\n\nexport interface ModelConnectionsResource {\n\t/** List supported providers. Credential material is never returned. */\n\tlist(): Promise<ModelConnection[]>;\n\t/** Start provider-native authorization; show the returned URL and device code when used. */\n\tauthorize(provider: AuthorizableModelConnectionProvider): Promise<ModelAuthorization>;\n\t/** Poll once; successful device authorization is saved automatically. */\n\tauthorizationStatus(\n\t\tprovider: DeviceModelConnectionProvider,\n\t\tstate: string\n\t): Promise<ModelAuthorization>;\n\t/** Exchange a pasted authorization code and store the connection. */\n\tcompleteAuthorization(\n\t\tprovider: CodeModelConnectionProvider,\n\t\tstate: string,\n\t\tparams: { code: string }\n\t): Promise<ModelAuthorization>;\n\t/** Cancel a short-lived provider authorization session. */\n\tcancelAuthorization(provider: AuthorizableModelConnectionProvider, state: string): Promise<void>;\n\t/** Delete m8tes' encrypted copy of the provider credentials. */\n\tdisconnect(provider: ModelConnectionProvider): Promise<ModelConnection>;\n\t/** Clear the account model-plan default so platform mates use m8tes credits again. */\n\tclearDefault(): Promise<boolean>;\n}\n\nexport function createModelConnectionsResource(http: Http): ModelConnectionsResource {\n\treturn {\n\t\tasync list() {\n\t\t\tconst res = await http.request<{ data: ModelConnection[] }>(\"GET\", \"/model-connections/\");\n\t\t\treturn res?.data ?? [];\n\t\t},\n\t\tauthorize(provider) {\n\t\t\treturn http.request<ModelAuthorization>(\n\t\t\t\t\"POST\",\n\t\t\t\t`/model-connections/${seg(provider)}/authorizations`\n\t\t\t);\n\t\t},\n\t\tauthorizationStatus(provider, state) {\n\t\t\treturn http.request<ModelAuthorization>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/model-connections/${seg(provider)}/authorizations/${seg(state)}`\n\t\t\t);\n\t\t},\n\t\tcompleteAuthorization(provider, state, params) {\n\t\t\treturn http.request<ModelAuthorization>(\n\t\t\t\t\"POST\",\n\t\t\t\t`/model-connections/${seg(provider)}/authorizations/${seg(state)}`,\n\t\t\t\t{ body: { code: params.code } }\n\t\t\t);\n\t\t},\n\t\tasync cancelAuthorization(provider, state) {\n\t\t\tawait http.request(\"DELETE\", `/model-connections/${seg(provider)}/authorizations/${seg(state)}`);\n\t\t},\n\t\tdisconnect(provider) {\n\t\t\treturn http.request<ModelConnection>(\"DELETE\", `/model-connections/${seg(provider)}`);\n\t\t},\n\t\tasync clearDefault() {\n\t\t\tconst res = await http.request<{ cleared: boolean }>(\n\t\t\t\t\"DELETE\",\n\t\t\t\t\"/model-connections/preferred-default\"\n\t\t\t);\n\t\t\treturn Boolean(res?.cleared);\n\t\t},\n\t};\n}\n","/**\n * `client.permissions` — standing tool allow-lists, one end-user at a time.\n *\n * A run pauses whenever the agent reaches for a tool that is not pre-approved,\n * and stays paused until somebody answers. That is the right default for a first\n * run and the wrong one for a tool your product has already decided is fine. A\n * policy here says \"this end-user's runs may use this tool\" once, so their runs\n * stop stopping.\n *\n * Scope: policies are per end-user (`user_id` is required on every call — there\n * is no account-wide policy) and outlive the run, unlike `runs.answerPermission()`\n * which unblocks a single gate. `/docs/users` documents this surface; mirrors\n * `sdk/py/m8tes/_resources/permissions.py`.\n */\n\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody, toQuery } from \"../params\";\nimport type { PermissionPolicy } from \"../types\";\nimport { type PageParams, pager } from \"./users\";\n\nexport interface PermissionCreateParams {\n /** The end-user whose runs this policy applies to. Required — policies never span end-users. */\n user_id: string;\n /** The tool to pre-approve, e.g. `\"Bash\"` or an `mcp__*` tool name. */\n tool: string;\n}\n\nexport interface PermissionListParams extends PageParams {\n /** Required: you list one end-user's policies, never the account's. */\n user_id: string;\n}\n\nexport interface PermissionsResource {\n /**\n * Pre-approve a tool so this end-user's runs no longer pause on it.\n * Idempotent — re-approving the same tool returns the existing policy rather\n * than erroring or duplicating. Send `tool`; the policy comes back as `tool_name`.\n */\n create(params: PermissionCreateParams): Promise<PermissionPolicy>;\n /** Audit what an end-user's runs are allowed to do without asking. */\n list(params: PermissionListParams): Promise<Page<PermissionPolicy>>;\n /**\n * Revoke a pre-approval, so the tool gates again on the next run.\n * `user_id` is required and scopes the delete — an id alone will not resolve.\n */\n delete(permissionId: number, params: { user_id: string }): Promise<void>;\n}\n\nexport function createPermissionsResource(http: Http): PermissionsResource {\n return {\n create(params) {\n return http.request<PermissionPolicy>(\"POST\", \"/permissions/\", {\n body: toBody({ ...params }),\n });\n },\n\n list(params) {\n return pager<PermissionPolicy>(http, \"/permissions/\")({ ...params });\n },\n\n async delete(permissionId, params) {\n await http.request(\"DELETE\", `/permissions/${seg(permissionId)}`, {\n query: toQuery({ user_id: params.user_id }),\n });\n },\n };\n}\n","/**\n * Filename → MIME type, for run attachments.\n *\n * The upload endpoint validates `content_type` against a strict allowlist\n * (`fastapi/app/services/execution/file_validation.py::ALLOWED_TYPES`) and\n * rejects the whole batch on a miss. A `Blob` built from bytes or a string has\n * no type, so it arrives as `application/octet-stream` and every upload fails\n * with `Invalid type: application/octet-stream` — which tells the developer\n * nothing about what to do next.\n *\n * So the type is inferred from the extension, and a caller can always override\n * it explicitly. Found by a live E2E: the mocked tests could not see it, because\n * only the real server enforces the allowlist.\n *\n * This map mirrors that allowlist. Adding a type here that the server does not\n * accept just moves the failure; keep the two in step.\n */\n\n// null-prototype on purpose: a plain object literal resolves `constructor`,\n// `__proto__`, `toString` through the prototype chain, so a filename ending\n// `.constructor` returned a truthy NON-string that sailed past the `if (!type)`\n// guard and became a garbage Content-Type. Filenames are often user-supplied.\nconst EXTENSION_TYPES: Record<string, string> = Object.assign(Object.create(null), {\n // Images (the agent can actually see these via its Read tool)\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n // Documents\n pdf: \"application/pdf\",\n txt: \"text/plain\",\n md: \"text/markdown\",\n markdown: \"text/markdown\",\n html: \"text/html\",\n htm: \"text/html\",\n // Code\n py: \"text/x-python\",\n js: \"application/javascript\",\n mjs: \"application/javascript\",\n cjs: \"application/javascript\",\n json: \"application/json\",\n ts: \"text/typescript\",\n tsx: \"text/typescript\",\n css: \"text/css\",\n c: \"text/x-c\",\n h: \"text/x-c\",\n java: \"text/x-java-source\",\n go: \"text/x-go\",\n sql: \"application/sql\",\n // Data / config\n csv: \"text/csv\",\n tsv: \"text/csv\",\n xml: \"application/xml\",\n yaml: \"text/yaml\",\n yml: \"text/yaml\",\n // Archives\n zip: \"application/zip\",\n gz: \"application/gzip\",\n tgz: \"application/gzip\",\n tar: \"application/x-tar\",\n // Office\n xlsx: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n xls: \"application/vnd.ms-excel\",\n docx: \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n pptx: \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ppt: \"application/vnd.ms-powerpoint\",\n});\n\n/** Every type the upload endpoint accepts. Used to make a rejection actionable. */\nexport const UPLOADABLE_EXTENSIONS = Object.keys(EXTENSION_TYPES);\n\n/**\n * The MIME type for a filename, or undefined when the extension is unknown.\n *\n * Undefined rather than a fallback on purpose: `application/octet-stream` is\n * exactly what the server rejects, so guessing it would only reproduce the\n * original confusing error.\n */\nexport function mimeTypeForFilename(name: string): string | undefined {\n const ext = name.includes(\".\") ? name.slice(name.lastIndexOf(\".\") + 1).toLowerCase() : \"\";\n return EXTENSION_TYPES[ext];\n}\n\n/**\n * Message for a file whose type cannot be determined. The server's own error\n * (\"Invalid type: application/octet-stream\") does not say what to do about it.\n */\nexport function unknownTypeMessage(name: string): string {\n return (\n `@m8tes/sdk: cannot infer a content type for \"${name}\", and the upload endpoint ` +\n `rejects files whose type it does not recognise. Pass it explicitly — ` +\n `{ name: \"${name}\", data, type: \"text/plain\" } — or rename the file with a known ` +\n `extension (${UPLOADABLE_EXTENSIONS.slice(0, 12).join(\", \")}, ...).`\n );\n}\n","/**\n * Wait for a run to finish.\n *\n * Streaming is the good path: you see the work as it happens. But plenty of\n * integrations are a queue worker or a cron job that just wants the answer, and\n * without this every one of them hand-rolls the same loop — with its own idea of\n * which statuses are terminal, its own backoff, and usually no timeout. That is\n * the single most common thing a developer had to build themselves.\n *\n * Mirrors `sdk/py/m8tes/_resources/runs.py` (`poll`, `wait`): same terminal set,\n * same 2s interval and 300s default timeout, same \"a transient API error is not\n * a failure, keep polling until the deadline\" behaviour.\n */\n\nimport {\n AuthenticationError,\n ConflictError,\n NotFoundError,\n PermissionDeniedError,\n ValidationError,\n} from \"./protocol/index\";\nimport type { PermissionRequest, Run } from \"./types\";\n\n/**\n * A revoked key, a deleted run, or a bad id will NEVER become terminal, so\n * retrying is pure cost: ~150 authenticated requests over the default 300s,\n * ending in a timeout whose advice (\"raise the timeout, or stream instead\") is\n * wrong for all three. Only genuinely transient failures keep polling.\n */\nfunction isPermanent(err: unknown): boolean {\n return (\n err instanceof AuthenticationError ||\n err instanceof PermissionDeniedError ||\n err instanceof NotFoundError ||\n err instanceof ValidationError\n );\n}\n\n/**\n * A run is done when it reaches one of these.\n *\n * Mirrors `TERMINAL_RUN_STATUSES` in `fastapi/app/models/run.py`, which is the\n * canonical set — including `\"closed\"` (a user-closed chat that cannot resume).\n * Both SDKs previously omitted it, so a closed run polled until the timeout.\n * The backend's own comment on that set warns these lists drift and that \"a\n * 'closed' chat run burned tokens too\". `archived` is deliberately NOT here:\n * it is a display state applied to already-terminal runs.\n */\nexport const TERMINAL_STATUSES = new Set([\"completed\", \"failed\", \"cancelled\", \"closed\"]);\n\n/**\n * Gate refusals `wait()` may ride out, keyed on the server's machine-readable\n * `error.details.error_code` (`fastapi/app/routers/v2/runs.py::approve_permission`).\n * Mirrors `_BENIGN_GATE_REFUSALS` in `sdk/py/m8tes/_resources/runs.py`.\n *\n * Membership is the SAFETY boundary, so it is an ALLOWLIST, not a denylist: anything\n * unrecognised — including an older server that sends no code at all — propagates. A\n * refusal the SDK cannot positively identify as harmless is treated as harmful,\n * because the one it must never swallow (`gate_resolved_otherwise`: another approver\n * decided the OPPOSITE way) is indistinguishable from the benign ones without it.\n *\n * `run_not_active` is benign ONLY because the server raises it exclusively for a gate\n * still OPEN on a finished run. If a CONTRADICTED decision could ever report\n * `run_not_active`, a lost denial would be swallowed here — so that split is a\n * contract, pinned server-side by\n * `test_a_contradicted_decision_on_a_terminal_run_is_not_reported_as_benign`.\n */\nconst BENIGN_GATE_REFUSAL_CODES = new Set([\"gate_cancelled\", \"run_not_active\"]);\n\n/**\n * The one benign refusal the server still spells as prose. `POST /runs/{id}/answer`\n * raises `HTTPException(409, detail=\"auto_continued\")` — a STRING detail, and\n * `routers/v2/_errors.py` lifts `error_code` only out of a DICT one — so the envelope\n * carries no code to branch on. It means the platform proceeded with the\n * \"(Recommended)\" option after ~10 minutes and the run is executing normally.\n *\n * Matched as the EXACT, complete message, never a substring, so no other 409 can\n * borrow it. Giving that endpoint a real code (and deleting this) is filed in\n * `TODOS.md`; until then, dropping it would break every polling caller on the\n * documented auto-continue path.\n */\nconst AUTO_CONTINUED_MESSAGE = \"auto_continued\";\n\nfunction isBenignGateRefusal(err: ConflictError | NotFoundError): boolean {\n if (err.errorCode !== undefined) return BENIGN_GATE_REFUSAL_CODES.has(err.errorCode);\n return err instanceof ConflictError && err.message === AUTO_CONTINUED_MESSAGE;\n}\n\nexport interface PollOptions {\n /** Seconds between polls. Default 2. */\n interval?: number;\n /** Seconds before giving up. Default 300. */\n timeout?: number;\n /** Abort the wait early. The in-flight request is cancelled with it. */\n signal?: AbortSignal;\n /**\n * End-user scope for each `GET /runs/{id}` poll. Required when the account\n * has strict multi-tenant mode on — without it every poll 422s.\n */\n user_id?: string;\n}\n\nexport interface WaitOptions extends PollOptions {\n /**\n * Called when a tool needs a decision. Return \"allow\" or \"deny\".\n * Without it, a run that pauses for a tool throws rather than hanging until\n * the timeout — silence would look identical to a slow run.\n */\n onApproval?: (request: PermissionRequest) => \"allow\" | \"deny\" | Promise<\"allow\" | \"deny\">;\n /**\n * Called when the agent asks a question. Return `{ [question text]: answer }`.\n * The keys must be the exact `question` strings from the request.\n */\n onQuestion?: (\n request: PermissionRequest,\n ) => Record<string, string> | Promise<Record<string, string>>;\n}\n\n/** Thrown when a run does not reach a terminal status before the deadline. */\nexport class RunTimeoutError extends Error {\n readonly runId: number;\n readonly timeoutSeconds: number;\n /** The last error seen while polling, if any. Without it a timeout hides the\n * transient failure that actually caused it. */\n override readonly cause?: unknown;\n /** The run's status when the deadline hit, when one was ever observed. */\n readonly lastStatus?: string;\n constructor(runId: number, timeoutSeconds: number, cause?: unknown, lastStatus?: string) {\n // The likeliest cause of a poll() timeout is a run parked at\n // awaiting_approval, which NEVER becomes terminal — so \"raise the timeout\"\n // is the one piece of advice guaranteed not to help. Say what actually\n // unblocks it when we know the status.\n const advice =\n lastStatus === \"awaiting_approval\"\n ? `The run is waiting for a human and will never finish on its own: use runs.wait() with ` +\n `onApproval/onQuestion, or resolve it yourself via runs.permissions(${runId}).`\n : `Raise the timeout, or stream the run instead of polling it.`;\n super(\n `Run ${runId} did not reach a terminal status within ${timeoutSeconds}s` +\n (lastStatus ? ` (last status: ${lastStatus})` : \"\") +\n `. ${advice}` +\n (cause instanceof Error ? ` Last error while polling: ${cause.message}` : \"\"),\n );\n this.name = \"RunTimeoutError\";\n this.runId = runId;\n this.timeoutSeconds = timeoutSeconds;\n this.cause = cause;\n if (lastStatus !== undefined) this.lastStatus = lastStatus;\n }\n}\n\n/**\n * Thrown when a run pauses for a human and no handler was supplied. Better than\n * waiting out the full timeout, which gives the caller no idea what happened.\n */\nexport class RunPausedError extends Error {\n readonly runId: number;\n readonly request: PermissionRequest;\n constructor(runId: number, request: PermissionRequest, hint: string) {\n super(`Run ${runId} is waiting for a human: ${hint}`);\n this.name = \"RunPausedError\";\n this.runId = runId;\n this.request = request;\n }\n}\n\n/** Normalized options, with a monotonic deadline. */\nfunction plan(options: PollOptions): {\n interval: number;\n timeout: number;\n deadline: number;\n signal?: AbortSignal;\n} {\n const interval = options.interval ?? 2;\n const timeout = options.timeout ?? 300;\n // NaN makes every `now() >= deadline` false and turns setTimeout into an\n // immediate timer, so the loop hot-spins against the API until something\n // external kills it. A negative interval does the same. Refuse both loudly.\n for (const [name, value] of [[\"interval\", interval], [\"timeout\", timeout]] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new TypeError(\n `@m8tes/sdk: ${name} must be a finite, non-negative number of seconds (got ${String(value)}).`,\n );\n }\n }\n return { interval, timeout, deadline: now() + timeout * 1000, signal: options.signal };\n}\n\n/**\n * Sleep for `interval`, but never past the deadline — otherwise a long interval\n * with a short timeout overshoots by the whole interval before anyone checks.\n */\nfunction napUntil(interval: number, deadline: number, signal?: AbortSignal): Promise<void> {\n const remaining = Math.max(0, deadline - now()) / 1000;\n return sleep(Math.min(interval, remaining), signal);\n}\n\n/**\n * Bound an awaited operation by the deadline (and the abort signal).\n *\n * Without this the advertised timeout only gated the gaps BETWEEN awaits: a\n * caller's `onApproval` that never settles hung `wait()` forever, and a slow\n * request could return success long after the deadline had passed. Now every\n * await is raced against the remaining time.\n */\nasync function withDeadline<T>(\n start: () => Promise<T>,\n deadline: number,\n signal: AbortSignal | undefined,\n onExpired: () => Error,\n): Promise<T> {\n const remaining = deadline - now();\n // A FACTORY, not a promise: an argument would be evaluated eagerly, firing a\n // request (or invoking the caller's callback) that is then thrown away — the\n // work happens, costs, and is ignored. Nothing starts once time is up.\n if (remaining <= 0) throw onExpired();\n const work = start();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort: (() => void) | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(onExpired()), remaining);\n if (signal) {\n onAbort = () => reject(onExpired());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n if (signal && onAbort) signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/** Interruptible sleep. An abort resolves it immediately rather than stranding the caller. */\nfunction sleep(seconds: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(done, seconds * 1000);\n function done(): void {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", done);\n resolve();\n }\n signal?.addEventListener(\"abort\", done, { once: true });\n });\n}\n\n/** True for an AskUserQuestion pause carrying a plan for approval (plan mode). */\nexport function isPlanApproval(request: PermissionRequest): boolean {\n if (request.tool_name !== \"AskUserQuestion\") return false;\n const questions = (request.tool_input as { questions?: Array<{ header?: string }> } | null)\n ?.questions;\n return Array.isArray(questions) && questions.some((q) => q?.header === \"Plan Approval\");\n}\n\n/** The proposed plan text, for a plan-approval pause. Null otherwise. */\nexport function planText(request: PermissionRequest): string | null {\n if (!isPlanApproval(request)) return null;\n const questions = (\n request.tool_input as { questions?: Array<{ header?: string; question?: string }> } | null\n )?.questions;\n return questions?.find((q) => q?.header === \"Plan Approval\")?.question ?? null;\n}\n\n/**\n * Injected by the runs resource so this module stays free of transport concerns.\n * Every call takes the caller's `signal`, so an abort cancels the in-flight HTTP\n * request instead of only shortening the next sleep.\n */\nexport interface PollDeps {\n get(runId: number, signal?: AbortSignal): Promise<Run>;\n permissions(runId: number, signal?: AbortSignal): Promise<PermissionRequest[]>;\n approve(\n runId: number,\n params: { request_id: string; decision: \"allow\" | \"deny\" },\n signal?: AbortSignal,\n ): Promise<unknown>;\n answer(\n runId: number,\n params: { answers: Record<string, string> },\n signal?: AbortSignal,\n ): Promise<unknown>;\n}\n\n/**\n * Monotonic milliseconds. `Date.now()` follows the wall clock, so an NTP\n * correction backwards mid-wait extends the timeout by the same amount (and\n * repeated corrections can stop it expiring at all). Python uses\n * `time.monotonic()` for exactly this reason.\n */\nconst now = (): number =>\n typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n\n/** Thrown when the caller aborts the wait. */\nexport class RunWaitAbortedError extends Error {\n /**\n * The run being waited on — `undefined` when the abort landed BEFORE any run\n * was created, which is the one case where there is nothing to go back to.\n * Previously this path passed a literal 0, producing \"Waiting on run 0 was\n * aborted\" and pointing the reader at a run that never existed.\n */\n readonly runId?: number;\n constructor(runId?: number) {\n super(\n runId === undefined\n ? \"Aborted before the run was created; nothing was started and nothing was billed.\"\n : `Waiting on run ${runId} was aborted. The run is still executing — ` +\n `poll it later with runs.get(${runId}), or stop it with runs.cancel(${runId}).`,\n );\n this.name = \"RunWaitAbortedError\";\n if (runId !== undefined) this.runId = runId;\n }\n}\n\n/**\n * Poll until the run is terminal.\n *\n * A run that pauses for a human never becomes terminal, so this would spin until\n * the timeout — `waitForRun` handles that case. `poll` is for autonomous runs.\n */\nexport async function pollRun(deps: PollDeps, runId: number, options: PollOptions = {}): Promise<Run> {\n const { interval, timeout, deadline, signal } = plan(options);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n // Kept so a timeout can still show WHY the last attempt failed.\n let lastError: unknown;\n // Kept so the timeout can give advice that fits the state the run is actually in.\n let lastStatus: string | undefined;\n\n for (;;) {\n let run: Run | undefined;\n try {\n run = await withDeadline(() => deps.get(runId, signal), deadline, signal, () =>\n signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus),\n );\n } catch (err) {\n // A timeout/abort raised by withDeadline is the verdict, not a blip.\n if (err instanceof RunTimeoutError || err instanceof RunWaitAbortedError) throw err;\n // A blip while the run is executing is not a failure: keep polling until\n // the deadline. But a 401/403/404 never resolves, so surface it now.\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (isPermanent(err)) throw err;\n lastError = err;\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n continue;\n }\n\n lastStatus = run.status;\n if (TERMINAL_STATUSES.has(run.status)) return run;\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n // The deadline can pass DURING the sleep; without this the loop would issue\n // one more request and could return successfully long after it expired.\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n }\n}\n\n/**\n * Wait for a run, answering human-in-the-loop pauses through callbacks.\n *\n * Same loop as `pollRun`, plus: on `awaiting_approval`, resolve every pending\n * request and let the run continue.\n */\nexport async function waitForRun(\n deps: PollDeps,\n runId: number,\n options: WaitOptions = {},\n): Promise<Run> {\n const { interval, timeout, deadline, signal } = plan(options);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n // Kept so a timeout can still show WHY the last attempt failed.\n let lastError: unknown;\n // Kept so the timeout can give advice that fits the state the run is actually in.\n let lastStatus: string | undefined;\n // A request we have already answered can still come back as \"pending\" on the\n // next poll, because the backend has not flipped its status yet. Without this\n // ledger the caller's onApproval/onQuestion fires again for the same gate —\n // and a callback that notifies a human or increments a counter would repeat.\n // Measured: 3 duplicate calls across 4 polls before this was added.\n const answered = new Set<string>();\n\n for (;;) {\n let run: Run | undefined;\n try {\n run = await withDeadline(() => deps.get(runId, signal), deadline, signal, () =>\n signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus),\n );\n } catch (err) {\n if (err instanceof RunTimeoutError || err instanceof RunWaitAbortedError) throw err;\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (isPermanent(err)) throw err;\n lastError = err;\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n continue;\n }\n\n lastStatus = run.status;\n if (TERMINAL_STATUSES.has(run.status)) return run;\n\n if (run.status === \"awaiting_approval\") {\n const expired = () =>\n signal?.aborted ? new RunWaitAbortedError(runId) : new RunTimeoutError(runId, timeout, lastError, lastStatus);\n const bound = <T>(start: () => Promise<T>): Promise<T> => withDeadline(start, deadline, signal, expired);\n /**\n * Resolving a gate can lose a race the caller cannot prevent — but two very\n * different losses look alike, so this branches on the SERVER'S code, never on\n * the status alone.\n *\n * benign — the gate was cancelled, the run went terminal, or the platform\n * auto-continued a \"(Recommended)\" question. Nothing a human decided was\n * contradicted, and `wait()` owes the caller the RUN's outcome, not the\n * gate's; keep polling and the next `get()` returns the real result.\n *\n * CONTRADICTED — another approver decided the OTHER way (or answered the same\n * question differently), so this caller's decision did NOT happen and the\n * opposite one is what runs. `onQuestion` picks A, Slack commits B, `/answer`\n * 409s the losing A: swallowing that makes `wait()` return a completed run to\n * a caller who believes they blocked the tool that just executed. It is the\n * same false confirmation the 404 exists to prevent, one layer up.\n *\n * Swallowing EVERY conflict could not tell those apart. See\n * `_BENIGN_GATE_REFUSALS` in `sdk/py/m8tes/_resources/runs.py` — same allowlist,\n * same reasoning, deliberately kept in step.\n */\n const resolveGate = async (start: () => Promise<unknown>): Promise<void> => {\n try {\n await bound(start);\n } catch (err) {\n if (!(err instanceof ConflictError) && !(err instanceof NotFoundError)) throw err;\n if (!isBenignGateRefusal(err)) throw err;\n }\n };\n const pending = (await bound(() => deps.permissions(runId, signal))).filter(\n (r) => r.status === \"pending\" && !answered.has(r.request_id),\n );\n for (const request of pending) {\n answered.add(request.request_id);\n if (request.tool_name === \"AskUserQuestion\") {\n if (!options.onQuestion) {\n throw new RunPausedError(\n runId,\n request,\n \"the agent asked a question. Pass onQuestion to answer it, or call runs.answer() yourself.\",\n );\n }\n // The callback is the caller's code: it can hang, so it is bounded too.\n const answers = await bound(async () => options.onQuestion!(request));\n await resolveGate(() => deps.answer(runId, { answers }, signal));\n } else {\n if (!options.onApproval) {\n throw new RunPausedError(\n runId,\n request,\n `the tool \"${request.tool_name}\" needs a decision. Pass onApproval, or call runs.approve() yourself.`,\n );\n }\n const decision = await bound(async () => options.onApproval!(request));\n await resolveGate(() => deps.approve(runId, { request_id: request.request_id, decision }, signal));\n }\n }\n }\n\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n await napUntil(interval, deadline, signal);\n if (signal?.aborted) throw new RunWaitAbortedError(runId);\n if (now() >= deadline) throw new RunTimeoutError(runId, timeout, lastError, lastStatus);\n }\n}\n","/**\n * `RunStream` — the developer-facing view of a streaming run.\n *\n * Mirrors the Python SDK's `RunStream` (`sdk/py/m8tes/_streaming.py`): iterate\n * events, or just await the text. It accumulates as you consume, so after\n * iterating you have `.text`, `.runId`, and `.errors` without a second request.\n *\n * Beyond Python it also exposes `.state` — the full normalized conversation\n * (messages, tool calls, notices) from the shared protocol accumulator. Useful\n * server-side for logging what the agent actually did, not just what it said.\n *\n * Nothing is consumed until you iterate: constructing a RunStream is free, and\n * an un-iterated stream is closed by `close()` without reading the body.\n */\n\nimport {\n RunFailedError,\n accumulate,\n initialConversationState,\n isTerminalEvent,\n type ConversationState,\n type M8tesStreamEvent,\n} from \"./protocol/index\";\n\nexport interface RunStreamOptions {\n /**\n * Throw `RunFailedError` once iteration finishes if the run emitted any error\n * event, so a mid-run failure is never mistaken for a successful empty run.\n * Defaults to false, matching the Python SDK.\n */\n raiseOnError?: boolean;\n /**\n * Reuse this key to retry the same call safely — the server replays the run the\n * first attempt produced instead of starting (and billing) a second one. One is\n * minted per call automatically; supply your own only when a retry must survive\n * a process restart. Sent as the `Idempotency-Key` header.\n */\n idempotencyKey?: string;\n}\n\nexport class RunStream implements AsyncIterable<M8tesStreamEvent> {\n private readonly source: AsyncGenerator<M8tesStreamEvent, void, unknown>;\n private readonly raiseOnError: boolean;\n private state: ConversationState = initialConversationState;\n private textChunks: string[] = [];\n private errorMessages: string[] = [];\n private runIdValue: number | null = null;\n private consumed = false;\n\n constructor(\n source: AsyncGenerator<M8tesStreamEvent, void, unknown>,\n options: RunStreamOptions = {},\n ) {\n this.source = source;\n this.raiseOnError = options.raiseOnError ?? false;\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<M8tesStreamEvent> {\n if (this.consumed) {\n throw new Error(\n \"RunStream has already been consumed. A stream is single-pass — iterate once, \" +\n \"then read .text / .state / .errors, or call runs.get(runId) to re-read the result.\",\n );\n }\n this.consumed = true;\n try {\n for await (const event of this.source) {\n this.state = accumulate(this.state, event);\n if (event.type === \"text-delta\") this.textChunks.push(event.delta);\n if (event.type === \"run-start\" && event.runId !== null) this.runIdValue = event.runId;\n if (event.type === \"run-error\") this.errorMessages.push(event.message || event.error);\n yield event;\n }\n } finally {\n // Closing the source generator cancels the underlying HTTP response even\n // when the caller breaks out of the loop early.\n await this.source.return(undefined).catch(() => undefined);\n }\n if (this.raiseOnError && this.errorMessages.length > 0) {\n throw new RunFailedError(`Run failed: ${this.errorMessages.join(\"; \")}`, {\n type: \"run_failed\",\n code: 0,\n status: 0,\n details: { errors: this.errorMessages },\n });\n }\n }\n\n /** Yield only the assistant's text, in order. The 90% case for a server. */\n async *iterText(): AsyncGenerator<string, void, unknown> {\n for await (const event of this) {\n if (event.type === \"text-delta\") yield event.delta;\n }\n }\n\n /** Drain the stream and return the full assistant text. */\n async text(): Promise<string> {\n for await (const _ of this) {\n /* accumulate */\n }\n return this.textChunks.join(\"\");\n }\n\n /** Accumulated text so far (complete once iteration finishes). */\n get output(): string {\n return this.textChunks.join(\"\");\n }\n\n /** Run id, available as soon as the first `run-start` event arrives. */\n get runId(): number | null {\n return this.runIdValue;\n }\n\n /** Error messages the run emitted. Check this, or pass `raiseOnError`. */\n get errors(): string[] {\n return [...this.errorMessages];\n }\n\n get hasErrors(): boolean {\n return this.errorMessages.length > 0;\n }\n\n /** Full normalized conversation: messages, tool calls, notices, status. */\n get conversation(): ConversationState {\n return this.state;\n }\n\n /** Close the underlying response without draining it. */\n async close(): Promise<void> {\n await this.source.return(undefined).catch(() => undefined);\n }\n}\n\nexport { isTerminalEvent };\n","/**\n * `client.runs` — start agents, stream what they do, and answer them mid-run.\n *\n * `create()` is the one call most integrations need: it provisions a default\n * agent if the account has none, so a brand-new key can run an agent in one\n * request. Mirrors `sdk/py/m8tes/_resources/runs.py`, field for field.\n */\n\nimport { IDEMPOTENCY_HEADER, type Http } from \"../http\";\nimport { mimeTypeForFilename, unknownTypeMessage } from \"../mime\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { resolveAgentId, toBody, toQuery } from \"../params\";\nimport {\n pollRun,\n RunWaitAbortedError,\n TERMINAL_STATUSES,\n waitForRun,\n type PollDeps,\n type PollOptions,\n type WaitOptions,\n} from \"../polling\";\nimport { ConflictError, ValidationError, type M8tesStreamEvent } from \"../protocol/index\";\n\n/**\n * Stamp the run id onto an error on its way out of a wait.\n *\n * `waitForRun` tolerates transient failures on `get`, but a failure while\n * resolving a permission gate (permissions/answer/approve) escapes to the\n * caller. Escaping is a defensible trade-off; escaping ANONYMOUSLY is not — for\n * `createAndWait` the caller never saw the id, so a run that is created,\n * billed, and STILL EXECUTING became unreachable. The error's class is\n * preserved so `instanceof ValidationError` and friends keep working; the id is\n * purely additive, and never overwrites an existing `runId`.\n */\nfunction withRunId<E>(err: E, runId: number): E {\n if (err && typeof err === \"object\" && !(\"runId\" in err)) {\n Object.defineProperty(err, \"runId\", { value: runId, enumerable: true, configurable: true });\n const e = err as { message?: string };\n if (typeof e.message === \"string\" && !e.message.includes(String(runId))) {\n e.message = `${e.message} (while waiting on run ${runId}, which is still executing)`;\n }\n }\n return err;\n}\nimport { RunStream, type RunStreamOptions } from \"../streaming\";\nimport type {\n JsonObject,\n PermissionMode,\n PermissionRequest,\n Run,\n RunFile,\n RunOutcome,\n} from \"../types\";\n\nexport interface RunCreateParams {\n /** What the agent should do. */\n message: string;\n /** Which agent runs it. Omit to use (or auto-provision) the account default. */\n agent_id?: number;\n /** Permanent legacy alias for `agent_id` — the same wire field. */\n teammate_id?: number;\n /** Your id for the end-user this run belongs to. Isolates their memory, history, and tool connections. */\n user_id?: string;\n /** Tool slugs available for this run. */\n tools?: string[];\n /** One-off system instructions for this run. */\n instructions?: string;\n /** Name a newly auto-created agent. */\n name?: string;\n /** Your own key/value data, echoed back on the Run. */\n metadata?: JsonObject;\n model?: string;\n effort?: string;\n permission_mode?: PermissionMode;\n /** Enable clarifying questions, tool approval, and plan mode. */\n human_in_the_loop?: boolean;\n /** Run-level overrides for the built-in tools. Omit to inherit the agent default. */\n memory?: boolean;\n history?: boolean;\n task_setup_tools?: boolean;\n feedback?: boolean;\n /** Ask for structured output matching this JSON Schema; lands on `run.output_data`. */\n output_schema?: JsonObject;\n /** Give this run's agent an email inbox. */\n email_inbox?: boolean;\n /**\n * Reuse this key to retry the same create safely — the server returns the run\n * the first attempt made instead of starting (and billing) a second one.\n *\n * One is minted per call automatically, which is what makes the SDK's own\n * retries safe. Supply your own only when a retry must survive a process\n * restart: a job runner re-driving the same unit of work should pass its job\n * id. Sent as the `Idempotency-Key` header; never part of the request body.\n */\n idempotencyKey?: string;\n /**\n * Files the agent can read: a CSV to analyze, a PDF to summarize. Each is a\n * `{ name, data }` pair; `data` accepts anything `FormData` takes (Blob,\n * Uint8Array, ArrayBuffer, string). Sending files switches the request to the\n * multipart `/runs/with-files` endpoint; every other option behaves the same.\n *\n * Attachments require sandbox execution (the agent reads them with its file\n * tools from the run's working directory).\n */\n files?: RunFileInput[];\n}\n\n/** One attachment for `runs.create({ files })`. */\nexport interface RunFileInput {\n /** Filename the agent will see. Its extension determines the content type. */\n name: string;\n /** Contents. `Blob`/`File` pass straight through; bytes and strings are wrapped. */\n data: Blob | ArrayBuffer | ArrayBufferView | string;\n /**\n * Content type, if the extension does not imply it. The upload endpoint\n * validates against an allowlist and rejects the batch on a miss, so this is\n * inferred from `name` by default rather than defaulting to\n * `application/octet-stream` (which the server refuses).\n */\n type?: string;\n}\n\nexport interface RunListParams {\n user_id?: string;\n agent_id?: number;\n teammate_id?: number;\n task_id?: number;\n status?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface ApproveParams {\n /** From the `approval-request` event, or `runs.permissions()`. */\n request_id: string;\n decision: \"allow\" | \"deny\";\n /**\n * Persist beyond this single gate.\n * - `false` (default): this request only.\n * - `true` + allow: also silence matching tools for the rest of THIS run AND\n * store a cross-run always-allow policy (scoped to the run's end-user when\n * set; revoke via `/permissions`).\n * - `true` + deny: deny matching tools for the rest of THIS run only (no\n * stored policy).\n */\n remember?: boolean;\n}\n\nexport interface AnswerParams {\n /**\n * Question text → the option label you picked. The keys must be the exact\n * `question` strings from the `question` event.\n */\n answers: Record<string, string>;\n}\n\nexport interface RunsResource {\n /** Start a run and stream it. */\n create(params: RunCreateParams, options?: RunStreamOptions): RunStream;\n /** Start a run and return immediately; poll `get()` or use a webhook for the result. */\n createAsync(params: RunCreateParams): Promise<Run>;\n /**\n * Start a run and wait for the result. The batch/cron counterpart to `create()`.\n * Pass `onApproval`/`onQuestion` to answer human-in-the-loop pauses inline;\n * without them a paused run throws `RunPausedError` rather than hanging.\n */\n createAndWait(params: RunCreateParams, options?: WaitOptions): Promise<Run>;\n /** Poll an existing run until it is terminal. Throws `RunTimeoutError` on deadline. */\n poll(runId: number, options?: PollOptions): Promise<Run>;\n /** Like `poll`, but resolves human-in-the-loop pauses through callbacks. */\n wait(runId: number, options?: WaitOptions): Promise<Run>;\n /**\n * Retry a failed or cancelled run. Returns a NEW run — poll that one's id, the\n * original stays failed. Idempotent: an in-flight retry is returned as-is.\n *\n * If the run already did something visible (sent a message, changed data), the\n * API refuses with a 409 `retry_needs_confirmation`; pass `confirm: true` to\n * proceed. Check `run.retryable` first to avoid a guaranteed conflict.\n */\n retry(runId: number, params?: { confirm?: boolean; use_credits?: boolean }): Promise<Run>;\n /** Join a run already in flight. Throws `RunNotStreamingError` if it has finished. */\n stream(runId: number, options?: RunStreamOptions): RunStream;\n /** Continue the conversation on an existing run, streaming the reply. */\n reply(runId: number, message: string, options?: RunStreamOptions): RunStream;\n /** GET /runs/{id}. Pass `user_id` to scope to one end-user (required when the\n * account has strict multi-tenant mode on). */\n get(runId: number, params?: { user_id?: string }): Promise<Run>;\n list(params?: RunListParams): Promise<Page<Run>>;\n /** Cancel a running run. Returns the updated Run, like the Python SDK.\n * Pass `user_id` when the account has strict multi-tenant mode on. */\n cancel(runId: number, params?: { user_id?: string }): Promise<Run>;\n /** Approve or deny a pending tool-permission gate. */\n approve(runId: number, params: ApproveParams): Promise<PermissionRequest>;\n /** Answer a pending AskUserQuestion gate, resuming the run. */\n answer(runId: number, params: AnswerParams): Promise<{ status: string; resumed: boolean }>;\n /** Gates currently waiting on a human. */\n permissions(runId: number): Promise<PermissionRequest[]>;\n /** Condensed result: headline, summary, tokens, cost. */\n outcome(runId: number): Promise<RunOutcome>;\n /** Files the agent produced. */\n files(runId: number): Promise<RunFile[]>;\n /** Download one produced file. */\n downloadFile(runId: number, filename: string): Promise<ArrayBuffer>;\n}\n\n/** Unwrap `{data: [...]}` or a bare array — both shapes exist across v2 routes. */\nfunction items(payload: { data?: unknown[] } | unknown[] | undefined): unknown[] {\n return Array.isArray(payload) ? payload : (payload?.data ?? []);\n}\n\n/**\n * Headers for a run-creating POST — minting a key when the caller gave none.\n *\n * A key is ALWAYS sent. Runs are billable, so a POST that times out is otherwise\n * unanswerable: retry and you may pay twice, don't and you may drop the request.\n * With a key the server binds it to the run it created and replays that run for\n * every repeat, which is what lets `http` retry these POSTs at all.\n *\n * Mirrors `idempotency_headers` in the Python SDK. Auto-minting never dedupes two\n * DELIBERATE identical runs: those are two calls, and each mints its own key.\n * Pass `idempotencyKey` to reuse one across process restarts (a job runner\n * re-driving the same unit of work should pass its job id).\n */\nexport function idempotencyHeaders(key?: string): Record<string, string> {\n return { [IDEMPOTENCY_HEADER]: key ?? crypto.randomUUID() };\n}\n\n/**\n * Follow an idempotent replay to the run's live stream.\n *\n * A run that has ALREADY finished by the time the retry lands has nothing to\n * join, so this throws rather than yielding an empty stream that would read as\n * \"the agent said nothing\". The window is the retry backoff (sub-second), and the\n * error names the run so the caller can fetch its result — still strictly better\n * than the pre-idempotency outcome, where a timed-out create left them unable to\n * learn the run existed at all.\n */\nexport function replayJoin(\n http: Http,\n): (run: { id: number; status: string }) => AsyncGenerator<M8tesStreamEvent, void, unknown> {\n return async function* (run) {\n if (TERMINAL_STATUSES.has(run.status)) {\n throw new ConflictError(\n `Run ${run.id} was already created by an earlier attempt with this idempotency ` +\n `key and has finished (status=${run.status}), so there is no stream to join. ` +\n `You were charged once. Fetch the result with runs.get(${run.id}).`,\n {\n type: \"invalid_request_error\",\n code: 409,\n status: 409,\n details: { error_code: \"idempotent_replay_terminal\", run_id: run.id, status: run.status },\n },\n );\n }\n yield* http.stream(\"GET\", `/runs/${seg(run.id)}/stream`);\n };\n}\n\nexport function createRunsResource(http: Http): RunsResource {\n const createBody = (p: RunCreateParams, stream: boolean): Record<string, unknown> => {\n const { agent_id, teammate_id, files, idempotencyKey, ...rest } = p;\n void files; // carried in the multipart form, never in the JSON body\n void idempotencyKey; // rides in the Idempotency-Key HEADER, never in the body\n return toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id), stream });\n };\n\n /** Multipart form for /runs/with-files: the same JSON under `payload`, plus the files. */\n const createForm = (p: RunCreateParams, stream: boolean): FormData => {\n const form = new FormData();\n form.append(\"payload\", JSON.stringify(createBody(p, stream)));\n for (const f of p.files ?? []) {\n // Precedence: an explicit `type` always wins (otherwise a Blob carrying\n // application/octet-stream would override the caller's own correction and\n // the server would reject the batch), then the Blob's own type, then the\n // filename extension.\n const blobType = f.data instanceof Blob && f.data.type ? f.data.type : undefined;\n const type = f.type ?? blobType ?? mimeTypeForFilename(f.name);\n if (!type) throw new TypeError(unknownTypeMessage(f.name));\n const blob =\n f.data instanceof Blob && f.data.type === type\n ? f.data\n : new Blob([f.data as BlobPart], { type });\n form.append(\"files\", blob, f.name);\n }\n return form;\n };\n\n const hasFiles = (p: RunCreateParams): boolean => (p.files?.length ?? 0) > 0;\n\n // Injected into the polling helpers so they stay transport-free.\n // The caller's abort signal reaches every request, so cancelling a wait\n // cancels the in-flight HTTP call rather than just shortening the next sleep.\n //\n // `user_id` is closed over per call: strict multi-tenant mode requires it on\n // every GET /runs/{id}, and createAndWait inherits it from the create body.\n const pollDeps = (userId?: string): PollDeps => ({\n get: (runId, signal) =>\n http.request<Run>(\"GET\", `/runs/${seg(runId)}`, {\n query: toQuery({ user_id: userId }),\n signal,\n }),\n permissions: async (runId, signal) =>\n items(await http.request(\"GET\", `/runs/${seg(runId)}/permissions`, { signal })) as PermissionRequest[],\n approve: (runId, params, signal) =>\n http.request(\"POST\", `/runs/${seg(runId)}/approve`, { body: { remember: false, ...params }, signal }),\n answer: (runId, params, signal) =>\n http.request(\"POST\", `/runs/${seg(runId)}/answer`, { body: params, signal }),\n });\n\n // Declared as a local (not a method) so nothing here depends on `this`:\n // `const { createAndWait } = client.runs` is a normal thing to write, and it\n // threw \"Cannot read properties of undefined\" while createAndWait was the one\n // method calling `this.createAsync`. Verified against the packed tarball.\n //\n // `async` on purpose: an unmappable attachment must REJECT, not throw\n // synchronously, or `.catch()` would miss what try/catch catches. (Streaming\n // `create()` returns a RunStream rather than a promise, so it throws\n // synchronously — you never got a stream to iterate.)\n const createAsync = async (params: RunCreateParams): Promise<Run> => {\n const headers = idempotencyHeaders(params.idempotencyKey);\n return hasFiles(params)\n ? http.request<Run>(\"POST\", \"/runs/with-files\", { form: createForm(params, false), headers })\n : http.request<Run>(\"POST\", \"/runs\", { body: createBody(params, false), headers });\n };\n\n return {\n create(params, options) {\n const headers = idempotencyHeaders(params.idempotencyKey);\n const init = hasFiles(params)\n ? { form: createForm(params, true), headers }\n : { body: createBody(params, true), headers };\n const path = hasFiles(params) ? \"/runs/with-files\" : \"/runs\";\n return new RunStream(\n http.stream(\"POST\", path, { ...init, onReplay: replayJoin(http) }),\n options,\n );\n },\n\n createAsync,\n\n async createAndWait(params, options = {}) {\n // Check BEFORE creating: a run costs money, and starting one for an\n // operation the caller already cancelled is the one mistake here that\n // spends real budget. (Verified: this used to issue the POST first.)\n if (options.signal?.aborted) throw new RunWaitAbortedError();\n // Conflicting scopes would create a billable run then 404 on every poll\n // under strict mode — refuse before POST (Greptile T-Rex P1).\n if (\n options.user_id != null &&\n params.user_id != null &&\n options.user_id !== params.user_id\n ) {\n throw new ValidationError(\n `createAndWait: options.user_id (${JSON.stringify(options.user_id)}) conflicts with ` +\n `params.user_id (${JSON.stringify(params.user_id)}). Use one scope for create and poll.`,\n { type: \"invalid_request_error\", code: 0, status: 0 },\n );\n }\n // Fold wait-option scope into create when the body omitted it — otherwise\n // an options-only user_id would create an unscoped (or differently scoped)\n // run and then poll with a foreign scope → permanent 404 after billing.\n const createParams =\n params.user_id == null && options.user_id != null\n ? { ...params, user_id: options.user_id }\n : params;\n const started = await createAsync(createParams);\n // Past this line the run exists and is billable, so every failure must\n // still tell the caller WHICH run to go back to.\n // Prefer the API-stamped owner (truth after create), else the create body.\n // A create scope that resolves to a different stamped owner must poll as\n // stamped — otherwise strict mode 404s the billable run (Greptile P1).\n const userId = started.user_id ?? createParams.user_id ?? undefined;\n try {\n return await waitForRun(pollDeps(userId), started.id, { ...options, user_id: userId });\n } catch (err) {\n throw withRunId(err, started.id);\n }\n },\n\n poll(runId, options = {}) {\n return pollRun(pollDeps(options.user_id), runId, options);\n },\n\n wait(runId, options = {}) {\n return waitForRun(pollDeps(options.user_id), runId, options);\n },\n\n // `confirm` / `use_credits` are QUERY params and the route takes no body\n // (verified against fastapi/app/routers/v2/runs.py::retry_run).\n retry(runId, params = {}) {\n return http.request<Run>(\"POST\", `/runs/${seg(runId)}/retry`, {\n query: toQuery({\n confirm: params.confirm ? true : undefined,\n use_credits: params.use_credits ? true : undefined,\n }),\n });\n },\n\n stream(runId, options) {\n return new RunStream(http.stream(\"GET\", `/runs/${seg(runId)}/stream`), options);\n },\n\n reply(runId, message, options) {\n return new RunStream(\n http.stream(\"POST\", `/runs/${seg(runId)}/reply`, {\n body: { message },\n headers: idempotencyHeaders(options?.idempotencyKey),\n onReplay: replayJoin(http),\n }),\n options,\n );\n },\n\n get(runId, params = {}) {\n return http.request<Run>(\"GET\", `/runs/${seg(runId)}`, {\n query: toQuery({ user_id: params.user_id }),\n });\n },\n\n async list(params = {}) {\n const { agent_id, teammate_id, ...rest } = params;\n const q = toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) });\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<Run>> => {\n const res = await http.request<{ data: Run[]; has_more?: boolean; next_starting_after?: string | number | null }>(\"GET\", \"/runs\", {\n query: toQuery(p),\n });\n return new Page<Run>(\n res?.data ?? [],\n res?.has_more ?? false,\n (starting_after) => fetchPage({ ...p, starting_after }),\n res?.next_starting_after,\n );\n };\n return fetchPage(q);\n },\n\n cancel(runId, params = {}) {\n return http.request<Run>(\"POST\", `/runs/${seg(runId)}/cancel`, {\n query: toQuery({ user_id: params.user_id }),\n });\n },\n\n approve(runId, params) {\n return http.request<PermissionRequest>(\"POST\", `/runs/${seg(runId)}/approve`, {\n body: { remember: false, ...params },\n });\n },\n\n answer(runId, params) {\n // `answers` is keyed by question text and goes over the wire verbatim.\n return http.request<{ status: string; resumed: boolean }>(\"POST\", `/runs/${seg(runId)}/answer`, {\n body: { answers: params.answers },\n });\n },\n\n async permissions(runId) {\n return items(await http.request(\"GET\", `/runs/${seg(runId)}/permissions`)) as PermissionRequest[];\n },\n\n outcome(runId) {\n return http.request<RunOutcome>(\"GET\", `/runs/${seg(runId)}/outcome`);\n },\n\n async files(runId) {\n return items(await http.request(\"GET\", `/runs/${seg(runId)}/files`)) as RunFile[];\n },\n\n async downloadFile(runId, filename) {\n const res = await http.raw(\"GET\", `/runs/${seg(runId)}/files/${seg(filename)}/download`, {\n headers: { accept: \"application/octet-stream\" },\n });\n return res.arrayBuffer();\n },\n };\n}\n","/**\n * `client.settings` — account-level configuration.\n *\n * In v0.1 scope for one concrete reason: strict multi-tenant mode\n * (`require_end_user_id`) is ON by default for API accounts, and when it rejects a\n * request the backend's own 422 message says \"turn it off once with\n * client.settings.update(require_end_user_id=False)\". Without this resource a\n * TypeScript developer would follow that instruction into a method that does not\n * exist. Found by running the SDK against a real backend.\n *\n * Mirrors `sdk/py/m8tes/_resources/settings.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { toBody } from \"../params\";\n\nexport interface AccountSettings {\n /** Per-end-user monthly run cap. null = uncapped. */\n per_end_user_run_limit: number | null;\n /** Per-end-user monthly metered spend cap, in cents. null = uncapped. */\n per_end_user_cost_limit_cents: number | null;\n /** Per-end-user run-starts per minute. null = unthrottled. */\n per_end_user_rate_per_minute: number | null;\n /** \"standard\", or \"metadata_only\" for zero data retention. */\n retention_mode: string;\n /** When true, any request that would fall back to the account scope is rejected. */\n require_end_user_id: boolean;\n}\n\nexport interface AccountSettingsUpdateParams {\n /** Pass a number to set, `null` to clear, omit to leave unchanged. */\n per_end_user_run_limit?: number | null;\n per_end_user_cost_limit_cents?: number | null;\n per_end_user_rate_per_minute?: number | null;\n retention_mode?: \"standard\" | \"metadata_only\";\n /**\n * Strict multi-tenant mode. ON by default for API accounts: a request that\n * omits `user_id` and would therefore land in the account-level scope is\n * rejected with a 422 rather than silently assuming the global scope.\n *\n * Set false only if you are building for yourself (single-tenant).\n */\n require_end_user_id?: boolean;\n}\n\nexport interface SettingsResource {\n get(): Promise<AccountSettings>;\n update(params: AccountSettingsUpdateParams): Promise<AccountSettings>;\n}\n\nexport function createSettingsResource(http: Http): SettingsResource {\n return {\n get() {\n return http.request<AccountSettings>(\"GET\", \"/settings/\");\n },\n // `null` must survive (it CLEARS a cap); only `undefined` is dropped.\n update(params) {\n return http.request<AccountSettings>(\"PATCH\", \"/settings/\", { body: toBody({ ...params }) });\n },\n };\n}\n","/**\n * `client.tasks` — reusable work definitions, plus the triggers that fire them.\n *\n * A task is \"what to do\"; a trigger is \"when\". `client.tasks.triggers` covers all\n * four kinds (schedule, webhook, email, app event). Mirrors\n * `sdk/py/m8tes/_resources/tasks.py`.\n */\n\nimport type { Http } from \"../http\";\nimport { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { resolveAgentId, toBody, toQuery } from \"../params\";\nimport { idempotencyHeaders, replayJoin } from \"./runs\";\nimport { RunStream, type RunStreamOptions } from \"../streaming\";\nimport type { JsonObject, PermissionMode, Run, Task, Trigger, TriggerType, WebhookToggle } from \"../types\";\n\n/** A task must belong to an agent: `POST /tasks/` requires `teammate_id`, so the\n * type requires one of the two spellings rather than letting you discover it as\n * a 422. */\ntype TaskOwner = { agent_id: number; teammate_id?: never } | { teammate_id: number; agent_id?: never };\n\nexport type TaskCreateParams = TaskOwner & TaskCreateFields;\n\nexport interface TaskCreateFields {\n /** What the agent should do each time this task runs. */\n instructions: string;\n name?: string;\n tools?: string[];\n /** What a good result looks like. */\n expected_output?: string;\n goals?: string;\n user_id?: string;\n /** Email the account owner when a run finishes. Default true. */\n email_notifications?: boolean;\n /** Create a webhook trigger alongside the task. */\n webhook?: boolean;\n /** Cron expression, e.g. `\"0 9 * * 1-5\"`. Creates a schedule trigger. */\n schedule?: string;\n /** IANA timezone for `schedule`. Default \"UTC\". */\n schedule_timezone?: string;\n enable_memory?: boolean;\n enable_history?: boolean;\n enable_task_setup_tools?: boolean;\n enable_feedback?: boolean;\n /** Accumulate self-improvement lessons across this task's runs. Default true. */\n enable_lessons?: boolean;\n /** How this task's runs ask for approval. Default: the agent's default. */\n permission_mode?: PermissionMode;\n}\n\n/**\n * PATCH /tasks/{id} accepts exactly these fields (backend `DevTaskUpdate`).\n * `schedule`, `schedule_timezone`, `webhook`, and the agent id are create-only:\n * sending them to PATCH returns 200 and changes nothing. Change a schedule via\n * `tasks.triggers.update()`, and a webhook via `enableWebhook()`.\n *\n * `null` is meaningful: it CLEARS the field.\n */\nexport interface TaskUpdateParams {\n name?: string | null;\n instructions?: string | null;\n tools?: string[] | null;\n expected_output?: string | null;\n goals?: string | null;\n email_notifications?: boolean | null;\n enable_memory?: boolean | null;\n enable_history?: boolean | null;\n enable_task_setup_tools?: boolean | null;\n enable_feedback?: boolean | null;\n enable_lessons?: boolean | null;\n permission_mode?: PermissionMode | null;\n}\n\nexport interface TaskListParams {\n user_id?: string;\n agent_id?: number;\n teammate_id?: number;\n status?: string;\n limit?: number;\n starting_after?: number;\n}\n\nexport interface TriggerCreateParams {\n type: TriggerType | string;\n /** Schedule triggers: a cron expression. */\n cron?: string;\n /** Schedule triggers: a plain interval instead of cron. */\n interval_seconds?: number;\n /** IANA timezone. Default \"UTC\". */\n timezone?: string;\n /** App-event triggers: the app slug, e.g. `\"github\"`. */\n app?: string;\n /** App-event triggers: the event name, e.g. `\"pull_request_opened\"`. */\n trigger_name?: string;\n trigger_config?: JsonObject;\n user_id?: string;\n /** Email triggers: only these senders may start a run. */\n allowed_senders?: string[];\n}\n\nexport interface TriggersResource {\n create(taskId: number, params: TriggerCreateParams): Promise<Trigger>;\n list(taskId: number, params?: { user_id?: string }): Promise<Trigger[]>;\n /** Only the schedule shape and the enabled flag are mutable — a trigger's\n * `type`/`app`/`trigger_name` are fixed at creation and are silently ignored\n * on PATCH. Delete and recreate to change those. `user_id` scopes to one\n * end-user (404 on mismatch). */\n update(\n taskId: number,\n triggerId: number,\n params: {\n cron?: string;\n interval_seconds?: number;\n timezone?: string;\n enabled?: boolean;\n user_id?: string;\n },\n ): Promise<Trigger>;\n delete(taskId: number, triggerId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport interface TaskRunParams {\n /** Run on behalf of this end-user. */\n user_id?: string;\n /**\n * Reuse this key to retry the same call safely — the server returns the run the\n * first attempt made instead of starting (and billing) a second one. One is\n * minted per call automatically; supply your own (e.g. a scheduler's job id)\n * only when a retry must survive a process restart. Sent as the\n * `Idempotency-Key` header, never in the body.\n */\n idempotencyKey?: string;\n}\n\nexport interface TasksResource {\n triggers: TriggersResource;\n create(params: TaskCreateParams): Promise<Task>;\n list(params?: TaskListParams): Promise<Page<Task>>;\n get(taskId: number, params?: { user_id?: string }): Promise<Task>;\n update(taskId: number, params: TaskUpdateParams & { user_id?: string }): Promise<Task>;\n delete(taskId: number, params?: { user_id?: string }): Promise<void>;\n /** Run the task now, streaming it. */\n run(taskId: number, params?: TaskRunParams, options?: RunStreamOptions): RunStream;\n /** Run the task now without streaming; poll `runs.get()` for the result. */\n runAsync(taskId: number, params?: TaskRunParams): Promise<Run>;\n /** `user_id` scopes to one end-user (404 on mismatch), like get/update/delete. */\n enableWebhook(taskId: number, params?: { user_id?: string }): Promise<WebhookToggle>;\n disableWebhook(taskId: number, params?: { user_id?: string }): Promise<void>;\n}\n\nexport function createTasksResource(http: Http): TasksResource {\n const triggers: TriggersResource = {\n create(taskId, params) {\n // user_id rides both channels on purpose: the query copy is the end-user\n // scope gate on the task (404 on mismatch); the body copy picks whose\n // connected account an app trigger arms.\n return http.request<Trigger>(\"POST\", `/tasks/${seg(taskId)}/triggers/`, {\n body: toBody({ timezone: \"UTC\", ...params }),\n query: toQuery({ user_id: params.user_id }),\n });\n },\n async list(taskId, params = {}) {\n const res = await http.request<{ data?: Trigger[] } | Trigger[]>(\n \"GET\",\n `/tasks/${seg(taskId)}/triggers/`,\n { query: toQuery(params) },\n );\n return Array.isArray(res) ? res : (res?.data ?? []);\n },\n update(taskId, triggerId, params) {\n const { user_id, ...patch } = params;\n return http.request<Trigger>(\"PATCH\", `/tasks/${seg(taskId)}/triggers/${seg(triggerId)}`, {\n body: toBody(patch),\n query: toQuery({ user_id }),\n });\n },\n async delete(taskId, triggerId, params = {}) {\n await http.request(\"DELETE\", `/tasks/${seg(taskId)}/triggers/${seg(triggerId)}`, {\n query: toQuery(params),\n });\n },\n };\n\n return {\n triggers,\n\n create(params) {\n const { agent_id, teammate_id, ...rest } = params;\n return http.request<Task>(\"POST\", \"/tasks/\", {\n body: toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) }),\n });\n },\n\n async list(params = {}) {\n const { agent_id, teammate_id, ...rest } = params;\n const q = toBody({ ...rest, teammate_id: resolveAgentId(teammate_id, agent_id) });\n const fetchPage = async (p: Record<string, unknown>): Promise<Page<Task>> => {\n const res = await http.request<{ data: Task[]; has_more?: boolean; next_starting_after?: string | number | null }>(\"GET\", \"/tasks/\", {\n query: toQuery(p),\n });\n return new Page<Task>(\n res?.data ?? [],\n res?.has_more ?? false,\n (starting_after) => fetchPage({ ...p, starting_after }),\n res?.next_starting_after,\n );\n };\n return fetchPage(q);\n },\n\n get(taskId, params = {}) {\n return http.request<Task>(\"GET\", `/tasks/${seg(taskId)}`, { query: toQuery(params) });\n },\n\n update(taskId, params) {\n const { user_id, ...patch } = params;\n return http.request<Task>(\"PATCH\", `/tasks/${seg(taskId)}`, {\n body: toBody(patch),\n query: toQuery({ user_id }),\n });\n },\n\n async delete(taskId, params = {}) {\n await http.request(\"DELETE\", `/tasks/${seg(taskId)}`, { query: toQuery(params) });\n },\n\n run(taskId, params = {}, options) {\n const { idempotencyKey, ...rest } = params;\n return new RunStream(\n http.stream(\"POST\", `/tasks/${seg(taskId)}/runs`, {\n body: toBody({ ...rest, stream: true }),\n headers: idempotencyHeaders(idempotencyKey),\n // Shares the create path's replay handling, so a fix on one side can\n // never silently miss the other.\n onReplay: replayJoin(http),\n }),\n options,\n );\n },\n\n runAsync(taskId, params = {}) {\n const { idempotencyKey, ...rest } = params;\n return http.request<Run>(\"POST\", `/tasks/${seg(taskId)}/runs`, {\n body: toBody({ ...rest, stream: false }),\n headers: idempotencyHeaders(idempotencyKey),\n });\n },\n\n enableWebhook(taskId, params = {}) {\n return http.request<WebhookToggle>(\"POST\", `/tasks/${seg(taskId)}/webhook`, {\n body: {},\n query: toQuery(params),\n });\n },\n\n async disableWebhook(taskId, params = {}) {\n await http.request(\"DELETE\", `/tasks/${seg(taskId)}/webhook`, { query: toQuery(params) });\n },\n };\n}\n","/**\n * `client.webhooks` — outbound event delivery, plus signature verification.\n *\n * `verifySignature` is the one function every webhook receiver needs, so it is\n * also exported standalone from the package root: verifying does not require a\n * client or an API key. Mirrors `sdk/py/m8tes/_resources/webhooks.py` byte for\n * byte on the signing scheme, so a payload verified by one SDK verifies in the\n * other.\n *\n * Scheme: HMAC-SHA256 over `\"{webhook-id}.{webhook-timestamp}.{raw body}\"`, hex,\n * prefixed `v1=`, compared in constant time.\n */\n\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { Http } from \"../http\";\nimport type { Page } from \"../pagination\";\nimport { seg } from \"../protocol/seg\";\nimport { toBody } from \"../params\";\nimport { pager } from \"./users\";\nimport type { Webhook, WebhookDelivery } from \"../types\";\n\nexport interface VerifySignatureOptions {\n /**\n * Reject signatures whose timestamp is older (or newer) than this many\n * seconds — replay protection. Omit to skip the check. 300 is a good default\n * for a public endpoint.\n */\n toleranceSeconds?: number;\n /** Injectable clock, for tests. Seconds since epoch. */\n now?: () => number;\n}\n\n/**\n * Verify a m8tes webhook signature.\n *\n * Pass the RAW request body — a parsed-and-restringified object will not match,\n * because JSON.stringify does not preserve key order or spacing.\n *\n * ```ts\n * const raw = await req.text();\n * if (!verifySignature(raw, Object.fromEntries(req.headers), secret, { toleranceSeconds: 300 })) {\n * return new Response(\"bad signature\", { status: 401 });\n * }\n * ```\n */\nexport function verifySignature(\n body: string | Uint8Array,\n headers: Record<string, string | string[] | undefined> | Headers,\n secret: string,\n options: VerifySignatureOptions = {},\n): boolean {\n const get = (name: string): string | undefined => {\n if (typeof (headers as Headers).get === \"function\") {\n return (headers as Headers).get(name) ?? undefined;\n }\n // Header names are case-insensitive on the wire; normalize before lookup.\n const lower = Object.fromEntries(\n Object.entries(headers as Record<string, string | string[] | undefined>).map(([k, v]) => [\n k.toLowerCase(),\n Array.isArray(v) ? v[0] : v,\n ]),\n );\n return lower[name];\n };\n\n const webhookId = get(\"webhook-id\");\n const timestamp = get(\"webhook-timestamp\");\n const signature = get(\"webhook-signature\");\n if (!webhookId || !timestamp || !signature) return false;\n\n if (options.toleranceSeconds !== undefined) {\n const ts = Number.parseInt(timestamp, 10);\n if (!Number.isFinite(ts)) return false;\n const now = options.now ? options.now() : Math.floor(Date.now() / 1000);\n if (Math.abs(now - ts) > options.toleranceSeconds) return false;\n }\n\n const raw = typeof body === \"string\" ? body : new TextDecoder().decode(body);\n const expected = `v1=${createHmac(\"sha256\", secret).update(`${webhookId}.${timestamp}.${raw}`).digest(\"hex\")}`;\n const a = Buffer.from(expected);\n const b = Buffer.from(signature);\n // timingSafeEqual throws on length mismatch; a length difference is already a\n // mismatch, so short-circuit rather than leak it as an exception.\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nexport interface WebhooksResource {\n verifySignature: typeof verifySignature;\n /** Register an endpoint. The signing secret is returned ONLY here — store it. */\n create(params: { url: string; events?: string[] }): Promise<Webhook>;\n list(params?: { limit?: number; starting_after?: number }): Promise<Page<Webhook>>;\n get(webhookId: number): Promise<Webhook>;\n update(\n webhookId: number,\n params: { url?: string; events?: string[]; active?: boolean },\n ): Promise<Webhook>;\n delete(webhookId: number): Promise<void>;\n /** Delivery attempts, for debugging a receiver that is not getting events. */\n listDeliveries(\n webhookId: number,\n params?: { limit?: number; starting_after?: number },\n ): Promise<Page<WebhookDelivery>>;\n}\n\nexport function createWebhooksResource(http: Http): WebhooksResource {\n return {\n verifySignature,\n\n create(params) {\n return http.request<Webhook>(\"POST\", \"/webhooks/\", { body: toBody({ ...params }) });\n },\n\n list(params = {}) {\n return pager<Webhook>(http, \"/webhooks/\")({ ...params });\n },\n\n get(webhookId) {\n return http.request<Webhook>(\"GET\", `/webhooks/${seg(webhookId)}`);\n },\n\n update(webhookId, params) {\n return http.request<Webhook>(\"PATCH\", `/webhooks/${seg(webhookId)}`, { body: toBody({ ...params }) });\n },\n\n async delete(webhookId) {\n await http.request(\"DELETE\", `/webhooks/${seg(webhookId)}`);\n },\n\n listDeliveries(webhookId, params = {}) {\n return pager<WebhookDelivery>(http, `/webhooks/${seg(webhookId)}/deliveries`)({ ...params });\n },\n };\n}\n","/**\n * `@m8tes/sdk` — TypeScript client for the m8tes API.\n *\n * ```ts\n * import { M8tes } from \"@m8tes/sdk\";\n *\n * const client = new M8tes(); // reads M8TES_API_KEY\n *\n * const run = client.runs.create({\n * message: \"A customer asked to cancel. Draft a warm reply offering to pause instead.\",\n * userId: \"customer_42\", // isolates this end-user's memory, history, and connections\n * });\n * for await (const chunk of run.iterText()) process.stdout.write(chunk);\n * ```\n *\n * SECURITY: this entry point holds your secret `m8_` key and is server-only.\n * Never import it from client-side code. To render an agent in a browser, use\n * `@m8tes/react` plus its server proxy, which keeps the key on your server.\n *\n * The streaming wire protocol lives in `@m8tes/sdk/protocol` (browser-safe, no\n * auth) so this package and `@m8tes/react` share one implementation.\n */\n\nimport { createHttp, DEFAULT_BASE_URL, type ClientOptions, type Http } from \"./http\";\nimport { createAgentsResource, type AgentsResource } from \"./resources/agents\";\nimport { createAppsResource, type AppsResource } from \"./resources/apps\";\nimport { createAccountResource, type AccountResource } from \"./resources/account\";\nimport { createBillingResource, type BillingResource } from \"./resources/billing\";\nimport { createMemoriesResource, type MemoriesResource } from \"./resources/memories\";\nimport { createModelsResource, type ModelsResource } from \"./resources/models\";\nimport {\n createModelConnectionsResource,\n type ModelConnectionsResource,\n} from \"./resources/model-connections\";\nimport { createPermissionsResource, type PermissionsResource } from \"./resources/permissions\";\nimport { createRunsResource, type RunsResource } from \"./resources/runs\";\nimport { createSettingsResource, type SettingsResource } from \"./resources/settings\";\nimport { createTasksResource, type TasksResource } from \"./resources/tasks\";\nimport { createUsersResource, type UsersResource } from \"./resources/users\";\nimport { createWebhooksResource, verifySignature, type WebhooksResource } from \"./resources/webhooks\";\n\n/** Kept in lockstep with package.json \"version\" — guarded by test/version.test.ts. */\nexport const M8TES_SDK_VERSION = \"0.1.0-alpha.4\";\n\nexport class M8tes {\n readonly runs: RunsResource;\n readonly agents: AgentsResource;\n /** Permanent alias for `agents` — the DB model and older docs say \"teammate\". */\n readonly teammates: AgentsResource;\n readonly tasks: TasksResource;\n readonly users: UsersResource;\n readonly apps: AppsResource;\n readonly webhooks: WebhooksResource;\n readonly settings: SettingsResource;\n readonly memories: MemoriesResource;\n readonly permissions: PermissionsResource;\n readonly models: ModelsResource;\n readonly modelConnections: ModelConnectionsResource;\n readonly billing: BillingResource;\n readonly account: AccountResource;\n /** The underlying transport. Use it to call an endpoint this version does not wrap yet. */\n readonly http: Http;\n\n constructor(options: ClientOptions = {}) {\n this.http = createHttp(options);\n this.runs = createRunsResource(this.http);\n this.agents = createAgentsResource(this.http);\n this.teammates = this.agents;\n this.tasks = createTasksResource(this.http);\n this.users = createUsersResource(this.http);\n this.apps = createAppsResource(this.http);\n this.webhooks = createWebhooksResource(this.http);\n this.settings = createSettingsResource(this.http);\n this.memories = createMemoriesResource(this.http);\n this.permissions = createPermissionsResource(this.http);\n this.models = createModelsResource(this.http);\n this.modelConnections = createModelConnectionsResource(this.http);\n this.billing = createBillingResource(this.http);\n this.account = createAccountResource(this.http);\n }\n}\n\n// No default export on purpose: mixing default + named exports makes the CJS\n// build ambiguous (`require(...)` consumers would need `.default`). The one\n// documented form is `import { M8tes } from \"@m8tes/sdk\"`.\n\n// Webhook verification needs no client and no key — import it directly in a\n// route handler that only receives events.\nexport { verifySignature, type VerifySignatureOptions } from \"./resources/webhooks\";\n\n// Transport + client options.\nexport { createHttp, DEFAULT_BASE_URL, type ClientOptions, type FetchLike, type Http } from \"./http\";\n\n// Streaming + pagination.\nexport { RunStream, type RunStreamOptions } from \"./streaming\";\n// Waiting on a run. The error classes are exported so `catch (e) { if (e\n// instanceof RunTimeoutError) ... }` works — without them a caller can only\n// match on a message string.\nexport {\n pollRun,\n waitForRun,\n isPlanApproval,\n planText,\n RunTimeoutError,\n RunPausedError,\n RunWaitAbortedError,\n TERMINAL_STATUSES,\n type PollOptions,\n type WaitOptions,\n} from \"./polling\";\nexport { Page, type ListResponse } from \"./pagination\";\n\n// Resource params + shapes.\nexport type {\n AgentsResource,\n AgentCreateParams,\n AgentUpdateParams,\n AgentListParams,\n} from \"./resources/agents\";\nexport type { AppsResource } from \"./resources/apps\";\nexport type { RunsResource, RunCreateParams, RunListParams } from \"./resources/runs\";\nexport type {\n TasksResource,\n TriggersResource,\n TaskCreateParams,\n TaskUpdateParams,\n TaskListParams,\n TaskRunParams,\n TriggerCreateParams,\n} from \"./resources/tasks\";\nexport type {\n UsersResource,\n EndUserCreateParams,\n EndUserUpdateParams,\n PageParams,\n} from \"./resources/users\";\nexport type { WebhooksResource } from \"./resources/webhooks\";\nexport type {\n SettingsResource,\n AccountSettings,\n AccountSettingsUpdateParams,\n} from \"./resources/settings\";\nexport type * from \"./resources/memories\";\nexport type * from \"./resources/permissions\";\nexport type * from \"./resources/models\";\nexport type * from \"./resources/model-connections\";\nexport type * from \"./resources/billing\";\nexport type * from \"./resources/account\";\nexport * from \"./types\";\n\n// The full wire protocol + typed errors, re-exported so a single import of\n// `@m8tes/sdk` is enough for the common case.\nexport * from \"./protocol/index\";\n"]}