@dialgem/sdk 0.1.0-beta.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +1 -1
- package/dist/index.cjs +16 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +65 -2
- package/dist/index.d.ts +65 -2
- package/dist/index.js +16 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/errors.ts","../src/version.ts","../src/core/http.ts","../src/resources/resource.ts","../src/resources/agents.ts","../src/core/pagination.ts","../src/resources/calls.ts","../src/resources/catalog.ts","../src/resources/account.ts","../src/resources/simulations.ts","../src/resources/web-calls.ts","../src/resources/contacts.ts","../src/resources/phone-numbers.ts","../src/resources/chats.ts","../src/resources/flows.ts","../src/resources/llms.ts","../src/webhooks.ts","../src/client.ts"],"names":["path"],"mappings":";;;AAyCO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA,GAAO,cAAA;AAClB;AAEO,IAAM,QAAA,GAAN,cAAuB,YAAA,CAAa;AAAA,EAChC,IAAA,GAAO,UAAA;AAAA;AAAA,EAEP,MAAA;AAAA;AAAA,EAEA,OAAA;AAAA;AAAA,EAEA,SAAA;AAAA;AAAA,EAEA,MAAA;AAAA;AAAA,EAEA,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAe,OAAA,EAAiB,OAAA,EAAsB;AAChF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,MAAM,QAAA,GAAW,WAAA,CAAY,IAAI,CAAA,GAAI,IAAA,GAAO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,IAAI,CAAA;AAC3B,IAAA,IAAA,CAAK,IAAA,GAAO,IAAI,IAAA,CAAK,IAAI,CAAA;AACzB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAI,MAAA,CAAO,IAAI,CAAA;AAC7B,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,QAAA,CAAS,IAAI,CAAA;AACjC,IAAA,IAAA,CAAK,YAAA,GAAe,IAAI,YAAA,CAAa,IAAI,CAAA;AACzC,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,QAAA,CAAS,IAAI,CAAA;AACjC,IAAA,IAAA,CAAK,WAAA,GAAc,IAAI,WAAA,CAAY,IAAI,CAAA;AAAA,EACzC;AACF;AAEA,SAAS,QAAQ,IAAA,EAAkC;AACjD,EAAA,MAAM,OAAQ,UAAA,CAA0E,OAAA;AACxF,EAAA,MAAM,KAAA,GAAQ,IAAA,EAAM,GAAA,GAAM,IAAI,GAAG,IAAA,EAAK;AACtC,EAAA,OAAO,QAAQ,KAAA,GAAQ,MAAA;AACzB;AAEA,SAAS,SAAA,GAAqB;AAC5B,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,OAAO,OAAO,CAAA,CAAE,MAAA,KAAW,WAAA,IAAe,OAAO,EAAE,QAAA,KAAa,WAAA;AAClE;AAEA,SAAS,YAAA,GAAsB;AAC7B,EAAA,MAAM,IAAK,UAAA,CAAmC,KAAA;AAC9C,EAAA,IAAI,OAAO,MAAM,UAAA,EAAY;AAC3B,IAAA,MAAM,IAAI,aAAa,uFAAuF,CAAA;AAAA,EAChH;AAGA,EAAA,OAAO,CAAC,GAAA,EAAK,IAAA,KAAU,EAAY,IAAA,CAAK,UAAA,EAAY,KAAK,IAAI,CAAA;AAC/D","file":"index.cjs","sourcesContent":["/**\n * Every failure the SDK raises is a `DialgemError`.\n *\n * HTTP failures are `APIError` subclasses chosen by status, so a caller can\n * `catch (e) { if (e instanceof NotFoundError) ... }`. Within a status, branch on\n * `errCode`: the API documents `err_code` as the one field clients\n * branch on, e.g. `flow_invalid`,\n * `flow_not_runnable`, `NOT_A_MEMBER`.\n */\n\n/**\n * One entry of `issues[]` (in an error body, or an agent's `flow_validation`): a\n * field error or a flow graph rule.\n */\nexport interface ErrorIssue {\n /** Stable machine-readable identifier of the rule. */\n code?: string\n severity?: \"error\" | \"warning\"\n message?: string\n node_id?: string | null\n edge_id?: string | null\n /** Path into the request body, for field errors. */\n loc?: (string | number)[] | null\n meta?: Record<string, unknown>\n [key: string]: unknown\n}\n\n/** The API's error envelope. */\nexport interface ErrorBody {\n err_code: string\n err_msg: string\n request_id: string\n issues?: ErrorIssue[]\n [key: string]: unknown\n}\n\n/** Minimal read-only view of response headers, independent of the fetch implementation. */\nexport interface HeadersLike {\n get(name: string): string | null\n}\n\nexport class DialgemError extends Error {\n override name = \"DialgemError\"\n}\n\nexport class APIError extends DialgemError {\n override name = \"APIError\"\n /** HTTP status code. */\n readonly status: number\n /** The service's `err_code`, e.g. `flow_invalid` or `HTTP_404`. Undefined if the body was not the envelope. */\n readonly errCode: string | undefined\n /** The service's `request_id`. Quote it when contacting support. */\n readonly requestId: string | undefined\n /** Field/graph diagnostics, present on validation failures. */\n readonly issues: readonly ErrorIssue[]\n /** Parsed JSON body, or the raw text if the body was not JSON. */\n readonly body: unknown\n readonly headers: HeadersLike\n\n constructor(status: number, body: unknown, message: string, headers: HeadersLike) {\n super(message)\n this.status = status\n this.body = body\n this.headers = headers\n const envelope = isErrorBody(body) ? body : undefined\n this.errCode = envelope?.err_code\n this.requestId = envelope?.request_id ?? headers.get(\"x-request-id\") ?? undefined\n this.issues = envelope?.issues ?? []\n }\n\n /** Build the subclass matching `status`. */\n static from(status: number, body: unknown, statusText: string, headers: HeadersLike): APIError {\n const envelope = isErrorBody(body) ? body : undefined\n const detail = envelope?.err_msg || (typeof body === \"string\" && body.trim() ? body.trim().slice(0, 500) : \"\")\n const message = detail ? `${status} ${detail}` : `${status} ${statusText || \"status code (no body)\"}`\n const Ctor = errorClassFor(status)\n return new Ctor(status, body, message, headers)\n }\n}\n\nexport class BadRequestError extends APIError {\n override name = \"BadRequestError\"\n}\nexport class AuthenticationError extends APIError {\n override name = \"AuthenticationError\"\n}\nexport class PermissionDeniedError extends APIError {\n override name = \"PermissionDeniedError\"\n}\nexport class NotFoundError extends APIError {\n override name = \"NotFoundError\"\n}\nexport class ConflictError extends APIError {\n override name = \"ConflictError\"\n}\nexport class UnprocessableEntityError extends APIError {\n override name = \"UnprocessableEntityError\"\n}\nexport class RateLimitError extends APIError {\n override name = \"RateLimitError\"\n}\nexport class InternalServerError extends APIError {\n override name = \"InternalServerError\"\n}\n\n/** The request never produced an HTTP response (DNS, TLS, reset, aborted by the caller). */\nexport class APIConnectionError extends DialgemError {\n override name = \"APIConnectionError\"\n constructor(message = \"Connection error.\", options?: { cause?: unknown }) {\n super(message, options)\n }\n}\n\n/** The caller's `signal` aborted the request. Never retried. */\nexport class APIUserAbortError extends DialgemError {\n override name = \"APIUserAbortError\"\n constructor(message = \"Request was aborted.\") {\n super(message)\n }\n}\n\n/** The request exceeded the configured `timeout`. */\nexport class APIConnectionTimeoutError extends APIConnectionError {\n override name = \"APIConnectionTimeoutError\"\n constructor(message = \"Request timed out.\") {\n super(message)\n }\n}\n\n/** A webhook's signature did not match its body. */\nexport class WebhookVerificationError extends DialgemError {\n override name = \"WebhookVerificationError\"\n}\n\nfunction errorClassFor(status: number): typeof APIError {\n switch (status) {\n case 400:\n return BadRequestError\n case 401:\n return AuthenticationError\n case 403:\n return PermissionDeniedError\n case 404:\n return NotFoundError\n case 409:\n return ConflictError\n case 422:\n return UnprocessableEntityError\n case 429:\n return RateLimitError\n default:\n return status >= 500 ? InternalServerError : APIError\n }\n}\n\nfunction isErrorBody(body: unknown): body is ErrorBody {\n return typeof body === \"object\" && body !== null && typeof (body as { err_code?: unknown }).err_code === \"string\"\n}\n","// Kept in step with package.json by tests/version.test.ts.\nexport const VERSION = \"0.1.0-beta.2\"\n","import {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIError,\n APIUserAbortError,\n DialgemError,\n type HeadersLike,\n} from \"./errors.js\"\nimport { VERSION } from \"../version.js\"\n\n/**\n * The slice of `fetch` the SDK uses. Declared structurally so any conforming\n * implementation (Node's global fetch, undici, node-fetch, a test double) fits,\n * without the SDK's public types depending on DOM lib typings.\n */\nexport type Fetch = (url: string, init: FetchInit) => Promise<FetchResponse>\n\nexport interface FetchInit {\n method: string\n headers: Record<string, string>\n /**\n * A JSON string, or a `FormData` for a file upload — in which case\n * `Content-Type` is deliberately absent, since only `fetch` knows the\n * multipart boundary it is about to generate.\n */\n body?: string | FormData\n signal: AbortSignal\n /**\n * Always `\"manual\"`. A followed redirect re-sends the API key to wherever the\n * `Location` points (fetch strips only `Authorization` cross-origin, not\n * `X-API-Key`), and turns a 301'd POST into a GET that \"succeeds\" with the\n * wrong body. The API never redirects, so a 3xx is surfaced as an `APIError`.\n */\n redirect: \"manual\"\n}\n\nexport interface FetchResponse {\n readonly status: number\n readonly statusText: string\n readonly headers: HeadersLike\n text(): Promise<string>\n}\n\n/** Per-call overrides, accepted as the last argument of every resource method. */\n// Every optional field also accepts an explicit `undefined`, so a caller compiling\n// with `exactOptionalPropertyTypes` can pass `{ signal: maybeSignal }` directly.\nexport interface RequestOptions {\n /** Milliseconds (> 0) before the attempt is aborted. Applies per attempt, not across retries. */\n timeout?: number | undefined\n /**\n * Retries on 408/429/5xx and connection failures.\n *\n * GET, PUT, PATCH and DELETE use the client's `maxRetries` unless overridden here.\n * **POST is never retried unless you set this explicitly**: most POSTs create\n * things, and an outbound call retried after an ambiguous 502 dials the person twice.\n */\n maxRetries?: number | undefined\n /** Abort the request. Surfaces as `APIUserAbortError`. */\n signal?: AbortSignal | undefined\n /** Extra headers for this request only. */\n headers?: Record<string, string> | undefined\n}\n\nexport type QueryScalar = string | number | boolean\n/** Arrays are sent as repeated parameters: `{ status: [\"a\", \"b\"] }` → `?status=a&status=b`. */\nexport type QueryValue = QueryScalar | QueryScalar[] | null | undefined\nexport type Query = Record<string, QueryValue>\n\nexport interface HttpClientOptions {\n apiKey: string\n baseURL: string\n timeout: number\n maxRetries: number\n fetch: Fetch\n defaultHeaders: Record<string, string>\n}\n\ntype Method = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\"\n\nconst RETRYABLE_METHODS: ReadonlySet<Method> = new Set([\"GET\", \"PUT\", \"PATCH\", \"DELETE\"])\nconst MAX_RETRY_DELAY_MS = 60_000\n\nexport class HttpClient {\n readonly baseURL: string\n readonly #apiKey: string\n readonly #timeout: number\n readonly #maxRetries: number\n readonly #fetch: Fetch\n readonly #defaultHeaders: Record<string, string>\n\n constructor(options: HttpClientOptions) {\n this.baseURL = options.baseURL.replace(/\\/+$/, \"\")\n this.#apiKey = options.apiKey\n this.#timeout = options.timeout\n this.#maxRetries = options.maxRetries\n this.#fetch = options.fetch\n this.#defaultHeaders = options.defaultHeaders\n }\n\n get<T>(path: string, query?: Query, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"GET\", path, { query, options })\n }\n\n post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"POST\", path, { body, options })\n }\n\n /**\n * POST a `FormData` body — file uploads.\n *\n * The body is sent as-is and `Content-Type` is left unset, because only\n * `fetch` knows the multipart boundary it is about to generate. Setting the\n * header ourselves produces a request no server can parse.\n */\n postForm<T>(path: string, form: FormData, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"POST\", path, { body: form, options })\n }\n\n put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"PUT\", path, { body, options })\n }\n\n patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"PATCH\", path, { body, options })\n }\n\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"DELETE\", path, { options })\n }\n\n async request<T>(\n method: Method,\n path: string,\n { query, body, options = {} }: { query?: Query | undefined; body?: unknown; options?: RequestOptions | undefined },\n ): Promise<T> {\n const url = this.buildURL(path, query)\n const isForm = isFormData(body)\n const headers = this.buildHeaders(body !== undefined && !isForm, options.headers)\n const payload = body === undefined ? undefined : isForm ? (body as FormData) : JSON.stringify(body)\n const timeout = options.timeout ?? this.#timeout\n // A multipart body is never retried, even on request. Its parts may be\n // one-shot streams, so a second attempt can send a truncated upload — and\n // the one thing worse than a failed clone is a clone built from half the\n // audio, which succeeds and sounds wrong.\n const maxRetries = isForm\n ? 0\n : options.maxRetries ?? (RETRYABLE_METHODS.has(method) ? this.#maxRetries : 0)\n assertTimeout(timeout)\n assertMaxRetries(maxRetries)\n\n for (let attempt = 0; ; attempt++) {\n const retriesLeft = maxRetries - attempt\n if (options.signal?.aborted) throw new APIUserAbortError()\n\n const outcome = await this.#attempt(url, method, headers, payload, timeout, options.signal)\n\n if (outcome.kind === \"response\") {\n const { status, statusText, headers: responseHeaders, text } = outcome\n if (status >= 200 && status < 300) return parseSuccess<T>(text, status)\n if (retriesLeft > 0 && isRetryableStatus(status)) {\n await sleep(retryAfterMs(responseHeaders) ?? backoffMs(attempt), options.signal)\n continue\n }\n throw APIError.from(status, parseErrorBody(text), statusText, responseHeaders)\n }\n\n if (options.signal?.aborted) throw new APIUserAbortError()\n if (retriesLeft > 0) {\n await sleep(backoffMs(attempt), options.signal)\n continue\n }\n throw outcome.error\n }\n }\n\n /** One HTTP attempt, with its own timeout. Never throws; timers and listeners are released before it returns. */\n async #attempt(\n url: string,\n method: Method,\n headers: Record<string, string>,\n payload: string | FormData | undefined,\n timeout: number,\n signal: AbortSignal | undefined,\n ): Promise<\n | { kind: \"response\"; status: number; statusText: string; headers: HeadersLike; text: string }\n | { kind: \"failure\"; error: APIConnectionError }\n > {\n const controller = new AbortController()\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort()\n }, timeout)\n const onUserAbort = () => controller.abort()\n signal?.addEventListener(\"abort\", onUserAbort, { once: true })\n\n try {\n const init: FetchInit = { method, headers, signal: controller.signal, redirect: \"manual\" }\n if (payload !== undefined) init.body = payload\n const response = await this.#fetch(url, init)\n // Read inside the timer: a server that sends headers then stalls the body\n // must still hit the timeout rather than hang the caller.\n const text = await response.text()\n return { kind: \"response\", status: response.status, statusText: response.statusText, headers: response.headers, text }\n } catch (err) {\n const error = timedOut\n ? new APIConnectionTimeoutError(`Request timed out after ${timeout}ms.`)\n : new APIConnectionError(`Connection error: ${describe(err)}`, { cause: err })\n return { kind: \"failure\", error }\n } finally {\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", onUserAbort)\n }\n }\n\n buildURL(path: string, query?: Query): string {\n const url = `${this.baseURL}${path.startsWith(\"/\") ? path : `/${path}`}`\n if (!query) return url\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue\n for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item))\n }\n const qs = params.toString()\n return qs ? `${url}?${qs}` : url\n }\n\n private buildHeaders(hasBody: boolean, extra?: Record<string, string>): Record<string, string> {\n // Merged case-insensitively, later layers winning. A plain object spread would\n // keep both `X-API-Key` and a caller's `x-api-key`, which fetch then joins\n // into one comma-separated value the service rejects.\n const merged = new Map<string, [name: string, value: string]>()\n const layer = (headers: Record<string, string> | undefined) => {\n for (const [name, value] of Object.entries(headers ?? {})) merged.set(name.toLowerCase(), [name, value])\n }\n layer({\n Accept: \"application/json\",\n // `X-API-Key`, not `Authorization: Bearer`: the API only tries a\n // Bearer value as a session JWT, so an org key sent that way is a 401.\n \"X-API-Key\": this.#apiKey,\n \"User-Agent\": userAgent(),\n })\n layer(this.#defaultHeaders)\n layer(extra)\n if (hasBody) layer({ \"Content-Type\": \"application/json\" })\n return Object.fromEntries(merged.values())\n }\n}\n\n/** `FormData` without assuming it exists — it does on every supported runtime. */\nfunction isFormData(value: unknown): value is FormData {\n return typeof FormData !== \"undefined\" && value instanceof FormData\n}\n\nexport function assertTimeout(value: number): void {\n // 0 is rejected rather than read as \"no timeout\": setTimeout(…, 0) would abort\n // every attempt immediately, and an unbounded request is never what a backend wants.\n if (!Number.isInteger(value) || value <= 0) {\n throw new DialgemError(`\\`timeout\\` must be a positive integer of milliseconds, got ${String(value)}.`)\n }\n}\n\nexport function assertMaxRetries(value: number): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new DialgemError(`\\`maxRetries\\` must be a non-negative integer, got ${String(value)}.`)\n }\n}\n\nfunction parseSuccess<T>(text: string, status: number): T {\n if (status === 204 || text.trim() === \"\") return undefined as T\n try {\n return JSON.parse(text) as T\n } catch (err) {\n throw new DialgemError(`Expected a JSON response (status ${status}) but could not parse it: ${describe(err)}`)\n }\n}\n\nfunction parseErrorBody(text: string): unknown {\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction isRetryableStatus(status: number): boolean {\n // Not 409: the API's 409s are real conflicts (a phone number already\n // registered), which a retry would only repeat.\n return status === 408 || status === 429 || status >= 500\n}\n\n/** Exponential backoff with jitter: ~0.5s, 1s, 2s, … capped at 8s. */\nfunction backoffMs(attempt: number): number {\n const base = Math.min(500 * 2 ** attempt, 8_000)\n return base * (1 - Math.random() * 0.25)\n}\n\n/** Honour `retry-after-ms`, then `Retry-After` (seconds or an HTTP date). */\nfunction retryAfterMs(headers: HeadersLike): number | undefined {\n const ms = Number(headers.get(\"retry-after-ms\"))\n if (Number.isFinite(ms) && ms > 0) return Math.min(ms, MAX_RETRY_DELAY_MS)\n const raw = headers.get(\"retry-after\")\n if (!raw) return undefined\n const seconds = Number(raw)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, MAX_RETRY_DELAY_MS)\n const date = Date.parse(raw)\n if (Number.isFinite(date)) return Math.min(Math.max(date - Date.now(), 0), MAX_RETRY_DELAY_MS)\n return undefined\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(new APIUserAbortError())\n const onAbort = () => {\n clearTimeout(timer)\n reject(new APIUserAbortError())\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort)\n resolve()\n }, ms)\n signal?.addEventListener(\"abort\", onAbort, { once: true })\n })\n}\n\nfunction userAgent(): string {\n const proc = (globalThis as { process?: { version?: string } }).process\n return proc?.version ? `dialgem-sdk-node/${VERSION} node/${proc.version}` : `dialgem-sdk-node/${VERSION}`\n}\n\nfunction describe(err: unknown): string {\n if (err instanceof Error) {\n const cause = (err as { cause?: unknown }).cause\n return cause instanceof Error ? `${err.message} (${cause.message})` : err.message\n }\n return String(err)\n}\n","import { DialgemError } from \"../core/errors.js\"\nimport type { HttpClient } from \"../core/http.js\"\n\nexport abstract class APIResource {\n protected readonly _client: HttpClient\n\n constructor(client: HttpClient) {\n this._client = client\n }\n}\n\n/**\n * Builds a path with each interpolated id URI-encoded.\n *\n * Rejects an empty id rather than sending it: `/v1/agents/${\"\"}` is\n * `/v1/agents/`, which a `retrieve(\"\")` would turn into a silent *list*\n * call, and a `delete(\"\")` into a confusing 405.\n */\nexport function path(strings: TemplateStringsArray, ...ids: string[]): string {\n let out = strings[0] ?? \"\"\n ids.forEach((id, i) => {\n if (typeof id !== \"string\" || id.trim() === \"\") {\n throw new DialgemError(`Expected a non-empty id in ${strings.join(\"{id}\")}, got ${JSON.stringify(id)}.`)\n }\n out += encodeURIComponent(id) + (strings[i + 1] ?? \"\")\n })\n return out\n}\n","import type { HttpClient, RequestOptions } from \"../core/http.js\"\nimport type { Agent, AgentDeleteResponse } from \"../types/agent.js\"\nimport type { AgentFunction, KnowledgeDocument, MCPServer, MCPServerTestResult, MCPToolList } from \"../types/agent-resources.js\"\nimport type {\n AgentVersion,\n AgentVersionListParams,\n AgentVersionListResponse,\n AgentVersionPublishParams,\n AgentVersionSummary,\n} from \"../types/agent-version.js\"\nimport type {\n AgentCreateParams,\n AgentUpdateParams,\n FunctionCreateParams,\n FunctionReorderParams,\n FunctionUpdateParams,\n KnowledgeDocumentCreateParams,\n MCPServerCreateParams,\n MCPServerUpdateParams,\n} from \"../types/params.js\"\nimport { DialgemError } from \"../core/errors.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class Agents extends APIResource {\n /** Tools (HTTP functions and built-ins like `end_call`) the agent can call. */\n readonly functions: AgentFunctions\n /** Text documents the agent retrieves from during the call. */\n readonly knowledge: AgentKnowledge\n /** Remote MCP servers whose tools are exposed to the agent. */\n readonly mcpServers: AgentMCPServers\n /** Frozen snapshots of the agent that a number or a call can pin. */\n readonly versions: AgentVersions\n\n constructor(client: HttpClient) {\n super(client)\n this.functions = new AgentFunctions(client)\n this.knowledge = new AgentKnowledge(client)\n this.mcpServers = new AgentMCPServers(client)\n this.versions = new AgentVersions(client)\n }\n\n /** Create an agent. Only `name` is required; everything else has a server default. */\n create(body: AgentCreateParams, options?: RequestOptions): Promise<Agent> {\n return this._client.post(\"/v1/agents\", body, options)\n }\n\n retrieve(agentId: string, options?: RequestOptions): Promise<Agent> {\n return this._client.get(path`/v1/agents/${agentId}`, undefined, options)\n }\n\n /** Every agent in the organization. `webhook_signing_secret` is `null` in this list. */\n list(options?: RequestOptions): Promise<Agent[]> {\n return this._client.get(\"/v1/agents\", undefined, options)\n }\n\n /** Partial update: only the fields you send change. */\n update(agentId: string, body: AgentUpdateParams, options?: RequestOptions): Promise<Agent> {\n return this._client.patch(path`/v1/agents/${agentId}`, body, options)\n }\n\n delete(agentId: string, options?: RequestOptions): Promise<AgentDeleteResponse> {\n return this._client.delete(path`/v1/agents/${agentId}`, options)\n }\n}\n\n/**\n * Published versions of an agent.\n *\n * The agent itself is the draft, version 0, and every call runs it unless a\n * number or a request pins a published version. Publishing takes a copy;\n * editing the agent afterwards changes only the draft.\n */\nexport class AgentVersions extends APIResource {\n /** Freeze the agent as it is now. Returns the new version, snapshot included. */\n publish(\n agentId: string,\n body: AgentVersionPublishParams = {},\n options?: RequestOptions,\n ): Promise<AgentVersion> {\n return this._client.post(path`/v1/agents/${agentId}/versions`, body, options)\n }\n\n/**\n * One page of published versions, newest first, without their snapshots.\n *\n * Returns the array. When you need to page — an agent published on every\n * deploy accumulates versions, and nothing prunes them — read `has_more` from\n * {@link listPage} instead and pass the last `version` as `before_version`.\n */\n async list(\n agentId: string,\n params?: AgentVersionListParams,\n options?: RequestOptions,\n ): Promise<AgentVersionSummary[]> {\n return (await this.listPage(agentId, params, options)).versions\n }\n\n /** {@link list} with the `has_more` flag, for paging. */\n listPage(\n agentId: string,\n params?: AgentVersionListParams,\n options?: RequestOptions,\n ): Promise<AgentVersionListResponse> {\n return this._client.get(\n path`/v1/agents/${agentId}/versions`,\n // Spread into a plain query record: an `interface` has no index\n // signature, so it does not structurally satisfy `Query`.\n { ...params },\n options,\n )\n }\n\n /** One version with its full snapshot. Version 0 is the draft: use `agents.retrieve`. */\n retrieve(agentId: string, version: number, options?: RequestOptions): Promise<AgentVersion> {\n return this._client.get(\n path`/v1/agents/${agentId}/versions/${versionSegment(version)}`,\n undefined,\n options,\n )\n }\n}\n\n/**\n * A version number as a path segment.\n *\n * Rejected here rather than sent: a fractional or negative number would 404 or\n * 422 from the server with nothing pointing at the caller's own value, and\n * `undefined` reaching the template would request the whole collection.\n */\nfunction versionSegment(version: number): string {\n if (!Number.isInteger(version) || version < 1) {\n throw new DialgemError(\n `Expected a published version number (a positive integer), got ${JSON.stringify(version)}. ` +\n \"Version 0 is the draft — read it with agents.retrieve().\",\n )\n }\n return String(version)\n}\n\nexport class AgentFunctions extends APIResource {\n list(agentId: string, options?: RequestOptions): Promise<AgentFunction[]> {\n return this._client.get(path`/v1/agents/${agentId}/functions`, undefined, options)\n }\n\n create(agentId: string, body: FunctionCreateParams, options?: RequestOptions): Promise<AgentFunction> {\n return this._client.post(path`/v1/agents/${agentId}/functions`, body, options)\n }\n\n update(\n agentId: string,\n functionId: string,\n body: FunctionUpdateParams,\n options?: RequestOptions,\n ): Promise<AgentFunction> {\n return this._client.patch(path`/v1/agents/${agentId}/functions/${functionId}`, body, options)\n }\n\n delete(agentId: string, functionId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/agents/${agentId}/functions/${functionId}`, options)\n }\n\n /** Set the order functions are offered to the LLM. `order` is function ids, first to last. */\n reorder(agentId: string, body: FunctionReorderParams, options?: RequestOptions): Promise<void> {\n return this._client.post(path`/v1/agents/${agentId}/functions/reorder`, body, options)\n }\n}\n\nexport class AgentKnowledge extends APIResource {\n list(agentId: string, options?: RequestOptions): Promise<KnowledgeDocument[]> {\n return this._client.get(path`/v1/agents/${agentId}/knowledge`, undefined, options)\n }\n\n /** Add a plain-text document (up to 500,000 characters). It is chunked and embedded server-side. */\n create(agentId: string, body: KnowledgeDocumentCreateParams, options?: RequestOptions): Promise<KnowledgeDocument> {\n return this._client.post(path`/v1/agents/${agentId}/knowledge`, body, options)\n }\n\n delete(agentId: string, sourceId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/agents/${agentId}/knowledge/${sourceId}`, options)\n }\n}\n\nexport class AgentMCPServers extends APIResource {\n list(agentId: string, options?: RequestOptions): Promise<MCPServer[]> {\n return this._client.get(path`/v1/agents/${agentId}/mcp-servers`, undefined, options)\n }\n\n create(agentId: string, body: MCPServerCreateParams, options?: RequestOptions): Promise<MCPServer> {\n return this._client.post(path`/v1/agents/${agentId}/mcp-servers`, body, options)\n }\n\n update(agentId: string, serverId: string, body: MCPServerUpdateParams, options?: RequestOptions): Promise<MCPServer> {\n return this._client.patch(path`/v1/agents/${agentId}/mcp-servers/${serverId}`, body, options)\n }\n\n delete(agentId: string, serverId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/agents/${agentId}/mcp-servers/${serverId}`, options)\n }\n\n /** Connect to the server now, list its tools, and store the result as `last_status`. */\n /**\n * What the server offers right now, with each tool's description and argument schema. Connects live like\n * `test`, but stores nothing. An unreachable server is not an error: `tools` is empty and `error` says why.\n */\n listTools(agentId: string, serverId: string, options?: RequestOptions): Promise<MCPToolList> {\n return this._client.get(path`/v1/agents/${agentId}/mcp-servers/${serverId}/tools`, undefined, options)\n }\n\n test(agentId: string, serverId: string, options?: RequestOptions): Promise<MCPServerTestResult> {\n return this._client.post(path`/v1/agents/${agentId}/mcp-servers/${serverId}/test`, undefined, options)\n }\n}\n","/**\n * Cursor pagination, as used by `GET /v1/calls`.\n *\n * `list()` returns a `PagePromise`, which is both awaitable (one page) and\n * async-iterable (every item across pages):\n *\n * const page = await client.calls.list({ limit: 50 })\n * for await (const call of client.calls.list({ status: \"completed\" })) { ... }\n *\n * Pages are keyset-based, so walking them is stable while new calls arrive: no\n * call is skipped or repeated because another one started mid-walk.\n */\nimport { DialgemError } from \"./errors.js\"\n\nexport interface PageData<T> {\n data: T[]\n has_more: boolean\n /** Pass to the next request to continue; `null` on the last page. */\n pagination_key: string | null\n}\n\nexport type PageFetcher<T> = (paginationKey: string | null) => Promise<PageData<T>>\n\nexport class Page<T> implements PageData<T> {\n readonly data: T[]\n readonly has_more: boolean\n readonly pagination_key: string | null\n readonly #fetchPage: PageFetcher<T>\n\n constructor(data: PageData<T>, fetchPage: PageFetcher<T>) {\n this.data = data.data\n this.has_more = data.has_more\n this.pagination_key = data.pagination_key\n this.#fetchPage = fetchPage\n }\n\n hasNextPage(): boolean {\n return this.has_more && this.pagination_key !== null\n }\n\n async getNextPage(): Promise<Page<T>> {\n if (!this.hasNextPage()) throw new DialgemError(\"No next page; check hasNextPage() first.\")\n return new Page(await this.#fetchPage(this.pagination_key), this.#fetchPage)\n }\n}\n\nexport class PagePromise<T> implements PromiseLike<Page<T>>, AsyncIterable<T> {\n readonly #fetchPage: PageFetcher<T>\n readonly #startKey: string | null\n #first: Promise<Page<T>> | undefined\n\n constructor(fetchPage: PageFetcher<T>, startKey: string | null = null) {\n this.#fetchPage = fetchPage\n this.#startKey = startKey\n }\n\n #firstPage(): Promise<Page<T>> {\n // Lazy and memoised: nothing is sent until awaited or iterated, and awaiting\n // then iterating the same PagePromise does not refetch page one.\n this.#first ??= this.#fetchPage(this.#startKey).then((data) => new Page(data, this.#fetchPage))\n return this.#first\n }\n\n then<R1 = Page<T>, R2 = never>(\n onfulfilled?: ((value: Page<T>) => R1 | PromiseLike<R1>) | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n return this.#firstPage().then(onfulfilled, onrejected)\n }\n\n catch<R = never>(onrejected?: ((reason: unknown) => R | PromiseLike<R>) | null): Promise<Page<T> | R> {\n return this.#firstPage().catch(onrejected)\n }\n\n finally(onfinally?: (() => void) | null): Promise<Page<T>> {\n return this.#firstPage().finally(onfinally)\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let page: Page<T> = await this.#firstPage()\n for (;;) {\n yield* page.data\n if (!page.hasNextPage()) return\n page = await page.getNextPage()\n }\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type {\n Call,\n CallDeleteResponse,\n CallListParams,\n CallRegisterResponse,\n CallStopResponse,\n CallUpdateParams,\n PhoneCallCreateResponse,\n} from \"../types/call.js\"\nimport type { CallCreatePhoneCallParams, CallRegisterParams } from \"../types/params.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface CallListEnvelope {\n calls: Call[]\n has_more: boolean\n pagination_key: string | null\n}\n\nexport class Calls extends APIResource {\n /**\n * Calls, newest first by default. Await for one page, or iterate for every call:\n *\n * const page = await dialgem.calls.list({ limit: 50 })\n * for await (const call of dialgem.calls.list({ status: \"completed\", start_after: since })) { ... }\n */\n list(params: CallListParams = {}, options?: RequestOptions): PagePromise<Call> {\n const query = toQuery(params)\n const fetchPage = async (paginationKey: string | null): Promise<PageData<Call>> => {\n const res = await this._client.get<CallListEnvelope>(\n \"/v1/calls\",\n { ...query, pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.calls, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n /** One call, including its transcript, analysis, latency and recording URL. */\n retrieve(callId: string, options?: RequestOptions): Promise<Call> {\n return this._client.get(path`/v1/calls/${callId}`, undefined, options)\n }\n\n /** Replace the call's `metadata`. */\n update(callId: string, body: CallUpdateParams, options?: RequestOptions): Promise<Call> {\n return this._client.patch(path`/v1/calls/${callId}`, body, options)\n }\n\n /**\n * Permanently delete a finished call: its record, transcript, analysis and\n * recording. A call still in progress is refused with `ConflictError`; stop it first.\n */\n delete(callId: string, options?: RequestOptions): Promise<CallDeleteResponse> {\n return this._client.delete(path`/v1/calls/${callId}`, options)\n }\n\n /**\n * Run a finished call's post-call analysis again, with the agent's *current* analysis\n * settings, and return the updated call. Use it after changing the fields or the model\n * and wanting an older call read the new way.\n *\n * It replaces `analysis`; it does not bill the call again and does not send `call_analyzed`\n * again, so read the result from this response or from `retrieve`. The model call can take\n * a while. `ConflictError` with `errCode` `call_in_progress` until the call has ended,\n * `no_transcript` when there is nothing to analyze, `agent_deleted` if the agent is gone.\n * Not retried by default.\n */\n rerunAnalysis(callId: string, options?: RequestOptions): Promise<Call> {\n return this._client.post(path`/v1/calls/${callId}/rerun-analysis`, undefined, options)\n }\n\n /**\n * End an ongoing call now, as if the agent had hung up. The call becomes\n * `completed` with `disconnection_reason: \"manual_stopped\"` a moment later, and\n * the usual `call_ended` webhook follows.\n *\n * `ConflictError` with `errCode` `call_not_ongoing` if it already ended, or\n * `call_not_connected` if no agent is on the call yet (e.g. still ringing).\n * Not retried by default.\n */\n stop(callId: string, options?: RequestOptions): Promise<CallStopResponse> {\n return this._client.post(path`/v1/calls/${callId}/stop`, undefined, options)\n }\n\n /**\n * Dial `to` from one of your organization's numbers, with `agent_id` (or the\n * number's outbound agent) on the line.\n *\n * Not retried by default: a retry after an ambiguous failure can place a\n * second call. Follow progress through webhooks or `retrieve(call_id)`.\n */\n createPhoneCall(body: CallCreatePhoneCallParams, options?: RequestOptions): Promise<PhoneCallCreateResponse> {\n return this._client.post(\"/v1/calls/outbound\", body, options)\n }\n\n /**\n * Bring-your-own-Twilio: call this from your Twilio voice webhook, then answer\n * Twilio with `<Response><Connect><Stream url=\"{stream_url}\"/></Connect></Response>`.\n * No Twilio credentials are shared with Dialgem.\n */\n register(body: CallRegisterParams, options?: RequestOptions): Promise<CallRegisterResponse> {\n return this._client.post(\"/v1/calls/register\", body, options)\n }\n}\n\nfunction toQuery(params: CallListParams): Query {\n const { metadata, ...rest } = params\n const query: Query = { ...rest }\n // `limit` selects cursor pagination server-side; without it the API answers in\n // its page-number mode, which this client does not read.\n query[\"limit\"] = params.limit ?? 10\n for (const [key, value] of Object.entries(metadata ?? {})) {\n query[`metadata.${key}`] = String(value)\n }\n return query\n}\n","import { DialgemError } from \"../core/errors.js\"\nimport type { Query, RequestOptions } from \"../core/http.js\"\nimport type {\n ExtractionModelList,\n FlowTemplate,\n FlowTemplateSummary,\n PromptTemplate,\n PromptTemplateSummary,\n TemplateListParams,\n Voice,\n VoiceCloneParams,\n VoiceDeleteResponse,\n VoiceListParams,\n} from \"../types/catalog.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class Voices extends APIResource {\n /**\n * Voices available to agents: the shared catalog plus the ones your\n * organization cloned, yours first. Put a voice's `provider_voice_id` in an\n * agent's `voice_id`.\n */\n list(params: VoiceListParams = {}, options?: RequestOptions): Promise<Voice[]> {\n return this._client.get(\"/v1/voices\", params as Query, options)\n }\n\n /**\n * Clone a voice from audio you upload. The new voice is private to your\n * organization and never appears in another one's catalog.\n *\n * Consent is required: you are asserting that you hold the rights to the\n * audio and have the speaker's consent, and that assertion is recorded\n * against your API identity.\n *\n * The upload is never retried, whatever `maxRetries` says — a retried\n * multipart body can send truncated audio, and a clone built from half the\n * recording succeeds and sounds wrong.\n */\n clone(params: VoiceCloneParams, options?: RequestOptions): Promise<Voice> {\n const { name, files, consent_confirmed, engine, description, language, filenames } = params\n if (!consent_confirmed) {\n throw new DialgemError(\n \"consent_confirmed must be true: you are asserting that you hold the rights \" +\n \"to this audio and have the speaker's consent to clone their voice.\",\n )\n }\n if (!files?.length) {\n throw new DialgemError(\"At least one audio file is required to clone a voice.\")\n }\n\n const form = new FormData()\n form.append(\"name\", name)\n form.append(\"consent_confirmed\", \"true\")\n if (engine) form.append(\"engine\", engine)\n if (description) form.append(\"description\", description)\n if (language) form.append(\"language\", language)\n files.forEach((file, i) => {\n // The provider infers the container from the extension, so every part is\n // given a name — the caller's, the Blob's own, or a generated one.\n const fallback = (file as File).name || `clip-${i + 1}.wav`\n form.append(\"files\", file, filenames?.[i] ?? fallback)\n })\n\n return this._client.postForm(\"/v1/voices/clone\", form, options)\n }\n\n /**\n * Delete a voice your organization cloned, at the provider and here.\n *\n * Only your own cloned voices: the shared catalog is not deletable, and a\n * voice an agent still uses is refused with a 409 rather than leaving that\n * agent without one.\n */\n delete(voiceId: string, options?: RequestOptions): Promise<VoiceDeleteResponse> {\n return this._client.delete(path`/v1/voices/${voiceId}`, options)\n }\n}\n\nexport class ExtractionModels extends APIResource {\n /** Models an agent may use for post-call analysis, with an estimated cost per session. */\n list(options?: RequestOptions): Promise<ExtractionModelList> {\n return this._client.get(\"/v1/models/extraction\", undefined, options)\n }\n}\n\nexport class FlowTemplates extends APIResource {\n /** Built-in conversation-flow templates (summaries, without `flow_config`). */\n list(params: TemplateListParams = {}, options?: RequestOptions): Promise<FlowTemplateSummary[]> {\n return this._client.get(\"/v1/flow-templates\", params as Query, options)\n }\n\n retrieve(templateId: string, options?: RequestOptions): Promise<FlowTemplate> {\n return this._client.get(path`/v1/flow-templates/${templateId}`, undefined, options)\n }\n}\n\nexport class PromptTemplates extends APIResource {\n /** Built-in prompt templates (summaries, without the prompt text). */\n list(params: TemplateListParams = {}, options?: RequestOptions): Promise<PromptTemplateSummary[]> {\n return this._client.get(\"/v1/prompt-templates\", params as Query, options)\n }\n\n retrieve(templateId: string, options?: RequestOptions): Promise<PromptTemplate> {\n return this._client.get(path`/v1/prompt-templates/${templateId}`, undefined, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type { ApiKeyInfo } from \"../types/api-key.js\"\nimport type {\n AgentSessionList,\n AgentSessionReleaseResult,\n AgentSessionSayParams,\n AgentSessionSayResult,\n AgentSessionUpdateParams,\n AgentSessionUpdateResult,\n} from \"../types/session.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class ApiKey extends APIResource {\n /**\n * Who this key is: your organization and the key's name, prefix, scopes, allowed addresses\n * and expiry. It answers for any valid key whatever its scopes, so an integration can check\n * what it was given. Never returns the secret.\n *\n * ```ts\n * const { key } = await dialgem.apiKey.retrieve()\n * if (key && !key.full_access) console.log(\"scoped to\", key.scopes)\n * ```\n */\n retrieve(options?: RequestOptions): Promise<ApiKeyInfo> {\n return this._client.get(\"/v1/api-key-info\", undefined, options)\n }\n}\n\nexport class Sessions extends APIResource {\n /**\n * The calls your organization has in progress right now, with a `count`.\n *\n * Live state read from the service's own registry — use it for a\n * concurrency check before placing a call. For finished calls use\n * `calls.list`; a call whose teardown never arrived is not counted here.\n */\n list(options?: RequestOptions): Promise<AgentSessionList> {\n return this._client.get(\"/v1/agent/sessions\", undefined, options)\n }\n\n /**\n * Change a live call's prompt and/or variables. It applies from the agent's **next turn**.\n *\n * `sessionId` is a session's `session_id` from `list`, or the call's own `call_id`. Only this call changes:\n * the agent, its published versions and other calls are untouched, and the change is gone when the call ends.\n * A turn already being spoken finishes as it was. `dynamic_variables` are merged over the call's variables;\n * `system_prompt` replaces the prompt for the rest of the call.\n *\n * The call may be on any service instance. `NotFoundError` if it is not live (or is another organization's),\n * `ConflictError` with `errCode` `session_ended` once it is over, `UnprocessableEntityError` with `errCode`\n * `flow_agent_prompt` for a flow agent's prompt (its variables can still change). Not retried by default.\n *\n * ```ts\n * await dialgem.sessions.update(callId, { dynamic_variables: { plan: \"pro\" } })\n * ```\n */\n update(sessionId: string, body: AgentSessionUpdateParams, options?: RequestOptions): Promise<AgentSessionUpdateResult> {\n return this._client.patch(path`/v1/agent/sessions/${sessionId}`, body, options)\n }\n\n /**\n * Make the agent say `text` on a live call, in its own voice. Answers at once; the line plays behind what the\n * agent is saying, or now with `interrupt: true`. The agent's conversation records it as something it said.\n *\n * Off unless the deployment enables live control: `ForbiddenError` with `errCode` `live_control_disabled`.\n * `ConflictError` `human_has_call` while a human has taken the call. Owners, admins and API keys only.\n * Not retried by default.\n *\n * ```ts\n * await dialgem.sessions.say(callId, { text: \"One moment while I check that.\" })\n * ```\n */\n say(sessionId: string, body: AgentSessionSayParams, options?: RequestOptions): Promise<AgentSessionSayResult> {\n return this._client.post(path`/v1/agent/sessions/${sessionId}/say`, body, options)\n }\n\n /**\n * Hand a taken-over call back to the agent, for when the socket that took it is gone. The agent is told a\n * human had the call and that it did not hear what was said. Same availability and limits as `say`.\n * Listening in and taking over run over a WebSocket (`/v1/agent/sessions/{id}/live`), which this SDK does not wrap.\n */\n release(sessionId: string, options?: RequestOptions): Promise<AgentSessionReleaseResult> {\n return this._client.post(path`/v1/agent/sessions/${sessionId}/release`, undefined, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type {\n SimulationCase,\n SimulationCaseInput,\n SimulationRun,\n SimulationRunCreateParams,\n SimulationRunDetail,\n SimulationRunList,\n SimulationSuite,\n SimulationSuiteCreateParams,\n SimulationSuiteDetail,\n SimulationSuiteList,\n SimulationSuiteUpdateParams,\n} from \"../types/simulation.js\"\nimport { APIResource, path } from \"./resource.js\"\n\n/**\n * Test your agent before a change reaches a caller. A **suite** holds **cases**; in each, a simulated caller\n * talks to the agent in text and your **checks** decide whether it passed.\n *\n * A simulation is not a call: nothing is dialled, recorded or billed, and the agent's tools are never really\n * called. Simulations spend model usage, so they are switched on per platform; until then every method answers\n * 403 `simulations_disabled`.\n *\n * const suite = await dialgem.simulations.createSuite({ agent_id, name: \"Refunds\" })\n * await dialgem.simulations.createCase(suite.id, {\n * name: \"Asks for a refund\",\n * caller: { mode: \"script\", turns: [\"I want my money back.\"] },\n * checks: [{ type: \"not_contains\", text: \"full refund\" }],\n * })\n * const run = await dialgem.simulations.run(suite.id)\n * // poll retrieveRun(run.id) until status is \"completed\"\n */\nexport class Simulations extends APIResource {\n /** Make a suite for one of your agents. */\n createSuite(body: SimulationSuiteCreateParams, options?: RequestOptions): Promise<SimulationSuite> {\n return this._client.post(\"/v1/simulations/suites\", body, options)\n }\n\n /** Your suites, newest first, each with its latest run. Pass `agent_id` for one agent's. */\n listSuites(params: { agent_id?: string } = {}, options?: RequestOptions): Promise<SimulationSuiteList> {\n return this._client.get(\"/v1/simulations/suites\", params, options)\n }\n\n /** One suite with its cases. */\n retrieveSuite(suiteId: string, options?: RequestOptions): Promise<SimulationSuiteDetail> {\n return this._client.get(path`/v1/simulations/suites/${suiteId}`, undefined, options)\n }\n\n /**\n * Rename a suite or set its publish gate: `off`, `warn` (publishing a version succeeds and lists the suites the draft\n * has not passed) or `block` (publishing is refused with 409 `simulation_required` until it has).\n */\n updateSuite(suiteId: string, body: SimulationSuiteUpdateParams, options?: RequestOptions): Promise<SimulationSuite> {\n return this._client.patch(path`/v1/simulations/suites/${suiteId}`, body, options)\n }\n\n /** Delete a suite and its cases. Past runs are deleted with it. */\n deleteSuite(suiteId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/simulations/suites/${suiteId}`, options)\n }\n\n /** Add a case (up to 50 per suite). 422 `invalid_case` says what to fix. */\n createCase(suiteId: string, body: SimulationCaseInput, options?: RequestOptions): Promise<SimulationCase> {\n return this._client.post(path`/v1/simulations/suites/${suiteId}/cases`, body, options)\n }\n\n /** Change a case. Fields you leave out keep their value. */\n updateCase(caseId: string, body: Partial<SimulationCaseInput>, options?: RequestOptions): Promise<SimulationCase> {\n return this._client.patch(path`/v1/simulations/cases/${caseId}`, body, options)\n }\n\n deleteCase(caseId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/simulations/cases/${caseId}`, options)\n }\n\n /**\n * Run every case of a suite against the draft, a published version or `\"latest_published\"`. Answers at once\n * (`202`); the run happens in the background, so poll `retrieveRun` until `status` is `completed`.\n *\n * 409 `suite_empty`, 422 `agent_type_not_supported` (multi-prompt agents), 429 `too_many_runs` or\n * `daily_run_limit`.\n */\n run(suiteId: string, body: SimulationRunCreateParams = {}, options?: RequestOptions): Promise<SimulationRun> {\n return this._client.post(path`/v1/simulations/suites/${suiteId}/runs`, body, options)\n }\n\n /** Runs, newest first. Pass `suite_id` for one suite's. */\n listRuns(params: { suite_id?: string; limit?: number } = {}, options?: RequestOptions): Promise<SimulationRunList> {\n return this._client.get(\"/v1/simulations/runs\", params, options)\n }\n\n /** A run with every case's transcript, tool calls and check results. */\n retrieveRun(runId: string, options?: RequestOptions): Promise<SimulationRunDetail> {\n return this._client.get(path`/v1/simulations/runs/${runId}`, undefined, options)\n }\n\n /** Stop a run that has not finished. Cases already under way finish; the rest are skipped. */\n cancelRun(runId: string, options?: RequestOptions): Promise<SimulationRun> {\n return this._client.post(path`/v1/simulations/runs/${runId}/cancel`, undefined, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type { WebCall, WebCallCreateParams, WebCallSettings, WebCallSettingsUpdateParams } from \"../types/web-call.js\"\nimport { APIResource } from \"./resource.js\"\n\n/**\n * Let a visitor talk to one of your agents from a web page, with `@dialgem/client`.\n *\n * Your **backend** calls `create` with your API key and gives the returned `access_token` to the page; the\n * page connects with that token alone. The key never reaches the browser. Before the first call, allow the\n * page's origin with `updateSettings`.\n */\nexport class WebCalls extends APIResource {\n /**\n * Create a call for one visitor and get its access token.\n *\n * const { access_token } = await dialgem.webCalls.create({ agent_id, metadata: { visitor: \"v_123\" } })\n *\n * `metadata` and `dialgem_llm_dynamic_variables` are fixed here, by you, and cannot be changed by the page.\n * 409 `web_origins_not_configured` until an origin is allowed; 402 if the organization cannot pay for calls;\n * 429 when more than `limits.tokens_per_minute` calls are created in a minute.\n */\n create(body: WebCallCreateParams, options?: RequestOptions): Promise<WebCall> {\n return this._client.post(\"/v1/calls/web\", body, options)\n }\n\n /** The origins browser calls may start from, and the limits that apply. */\n retrieveSettings(options?: RequestOptions): Promise<WebCallSettings> {\n return this._client.get(\"/v1/web-calls/settings\", undefined, options)\n }\n\n /**\n * Replace the allowed origins. Each is `scheme://host[:port]`; `https://*.example.com` allows any subdomain\n * (not the bare domain) and `*` allows any website. Tokens already issued keep the list they were issued with.\n */\n updateSettings(body: WebCallSettingsUpdateParams, options?: RequestOptions): Promise<WebCallSettings> {\n return this._client.put(\"/v1/web-calls/settings\", body, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type {\n Contact,\n ContactCallList,\n ContactCreateParams,\n ContactCsvInspection,\n ContactDeleteResponse,\n ContactImport,\n ContactImportCreateParams,\n ContactImportErrors,\n ContactImportList,\n ContactListCreateParams,\n ContactListDeleteResponse,\n ContactListMemberRemoveResponse,\n ContactListMembersAddResponse,\n ContactListParams,\n ContactListRecord,\n ContactListUpdateParams,\n ContactUpdateParams,\n} from \"../types/contact.js\"\nimport { APIResource, path } from \"./resource.js\"\nimport type { HttpClient } from \"../core/http.js\"\n\ninterface ContactListEnvelope {\n contacts: Contact[]\n total: number\n next_cursor: string | null\n}\n\n/**\n * The people your organization calls. A phone number identifies each one: it is stored\n * in international form however you write it, and each number can be a contact once.\n */\nexport class Contacts extends APIResource {\n /** Bulk import from CSV, with a dry-run preview. */\n readonly imports: ContactImports\n\n constructor(client: HttpClient) {\n super(client)\n this.imports = new ContactImports(client)\n }\n\n /**\n * Add a contact. `phone` is any way of writing a valid number; without a leading `+`\n * also pass `default_country` (`\"US\"`). A number that is already a contact answers 409\n * with its `contact_id`.\n */\n create(body: ContactCreateParams, options?: RequestOptions): Promise<Contact> {\n return this._client.post(\"/v1/contacts\", body, options)\n }\n\n /**\n * Contacts, newest first. Await for one page, or iterate for every contact:\n *\n */\n list(params: ContactListParams = {}, options?: RequestOptions): PagePromise<Contact> {\n const fetchPage = async (cursor: string | null): Promise<PageData<Contact>> => {\n const res = await this._client.get<ContactListEnvelope>(\n \"/v1/contacts\",\n { ...(params as Query), cursor: cursor ?? undefined },\n options,\n )\n return { data: res.contacts, has_more: res.next_cursor !== null, pagination_key: res.next_cursor }\n }\n return new PagePromise(fetchPage)\n }\n\n /**\n * The contact with this phone number. The number is matched as E.164, so\n * `(\"(212) 220-0001\", { default_country: \"US\" })` finds `+12122200001`. Throws\n * `NotFoundError` if you have no such contact, and `UnprocessableEntityError` if the text is\n * not a phone number.\n */\n retrieveByPhone(phone: string, params: { default_country?: string | undefined } = {}, options?: RequestOptions): Promise<Contact> {\n return this._client.get(path`/v1/contacts/by-phone/${phone}`, params as Query, options)\n }\n\n /** One contact, with its lists and how many calls it has had. */\n retrieve(contactId: string, options?: RequestOptions): Promise<Contact> {\n return this._client.get(path`/v1/contacts/${contactId}`, undefined, options)\n }\n\n /**\n * Partial update: only the fields you send change, and `null` clears a field.\n * `attributes` replaces the whole set, so send every field you want kept.\n */\n update(contactId: string, body: ContactUpdateParams, options?: RequestOptions): Promise<Contact> {\n return this._client.patch(path`/v1/contacts/${contactId}`, body, options)\n }\n\n /**\n * Erase a contact and its list memberships. Calls already made stay in the call log, and\n * a do-not-call entry for the number stays too, so forgetting a person never makes a number\n * that asked not to be called dialable again.\n */\n delete(contactId: string, options?: RequestOptions): Promise<ContactDeleteResponse> {\n return this._client.delete(path`/v1/contacts/${contactId}`, options)\n }\n\n /** Calls to or from the contact's number, newest first. Summaries, not transcripts. */\n calls(contactId: string, params: { limit?: number | undefined } = {}, options?: RequestOptions): Promise<ContactCallList> {\n return this._client.get(path`/v1/contacts/${contactId}/calls`, params as Query, options)\n }\n\n}\n\n/**\n * CSV import runs in the background. Typical flow: `inspect` to see the columns, `create`\n * with `dry_run: true`, poll `retrieve` until `previewed`, look at the counts (and `errors`),\n * then `commit` and poll until `completed`.\n *\n * The CSV text is sent in the request. Downloading the rejected rows as a CSV, and exporting\n * contacts, are available over the REST API (`GET /v1/contacts/imports/{id}/errors?format=csv`,\n * `GET /v1/contacts/export`).\n */\nexport class ContactImports extends APIResource {\n /** The file's headers, a guessed column mapping and a few rows. Imports nothing. */\n inspect(csv: string, options?: RequestOptions): Promise<ContactCsvInspection> {\n return this._client.post(\"/v1/contacts/imports/inspect\", { csv }, options)\n }\n\n /**\n * Start an import. Without `mapping` the columns are guessed from the headers. With\n * `dry_run: true` nothing is written: the import only validates and reports.\n */\n create(body: ContactImportCreateParams, options?: RequestOptions): Promise<ContactImport> {\n return this._client.post(\"/v1/contacts/imports\", body, options)\n }\n\n /** Recent imports, newest first. */\n list(options?: RequestOptions): Promise<ContactImportList> {\n return this._client.get(\"/v1/contacts/imports\", undefined, options)\n }\n\n /** Progress and counts. */\n retrieve(importId: string, options?: RequestOptions): Promise<ContactImport> {\n return this._client.get(path`/v1/contacts/imports/${importId}`, undefined, options)\n }\n\n /** The rows that were rejected, with the line, the reason and what each held. */\n errors(importId: string, params: { limit?: number | undefined } = {}, options?: RequestOptions): Promise<ContactImportErrors> {\n return this._client.get(path`/v1/contacts/imports/${importId}/errors`, params as Query, options)\n }\n\n /** Apply a previewed import: the file is read again, so what is applied is what was previewed. */\n commit(importId: string, options?: RequestOptions): Promise<ContactImport> {\n return this._client.post(path`/v1/contacts/imports/${importId}/commit`, undefined, options)\n }\n\n /** Stop an import that has not finished. Contacts a running import already wrote stay. */\n cancel(importId: string, options?: RequestOptions): Promise<ContactImport> {\n return this._client.delete(path`/v1/contacts/imports/${importId}`, options)\n }\n}\n\n/** Named groups of contacts. Deleting a list never deletes its contacts. */\nexport class ContactLists extends APIResource {\n list(options?: RequestOptions): Promise<{ lists: ContactListRecord[] }> {\n return this._client.get(\"/v1/contact-lists\", undefined, options)\n }\n\n /** Names are unique within your organization, ignoring case. */\n create(body: ContactListCreateParams, options?: RequestOptions): Promise<ContactListRecord> {\n return this._client.post(\"/v1/contact-lists\", body, options)\n }\n\n retrieve(listId: string, options?: RequestOptions): Promise<ContactListRecord> {\n return this._client.get(path`/v1/contact-lists/${listId}`, undefined, options)\n }\n\n update(listId: string, body: ContactListUpdateParams, options?: RequestOptions): Promise<ContactListRecord> {\n return this._client.patch(path`/v1/contact-lists/${listId}`, body, options)\n }\n\n delete(listId: string, options?: RequestOptions): Promise<ContactListDeleteResponse> {\n return this._client.delete(path`/v1/contact-lists/${listId}`, options)\n }\n\n /** Add up to 1000 of your contacts. Already-members are ignored; `added` says how many were new. */\n addContacts(listId: string, contactIds: string[], options?: RequestOptions): Promise<ContactListMembersAddResponse> {\n return this._client.post(path`/v1/contact-lists/${listId}/members`, { contact_ids: contactIds }, options)\n }\n\n removeContact(listId: string, contactId: string, options?: RequestOptions): Promise<ContactListMemberRemoveResponse> {\n return this._client.delete(path`/v1/contact-lists/${listId}/members/${contactId}`, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type { PhoneNumberAssignParams, PhoneNumberCreateParams, PhoneNumberUpdateParams } from \"../types/params.js\"\nimport type { InboundWebhookTestResult, PhoneNumber } from \"../types/phone-number.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class PhoneNumbers extends APIResource {\n /** Register a number you own (`phone_number` in E.164) with Dialgem. */\n create(body: PhoneNumberCreateParams, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.post(\"/v1/phone-numbers\", body, options)\n }\n\n /** Every active (not released) number in the organization, newest first. */\n list(options?: RequestOptions): Promise<PhoneNumber[]> {\n return this._client.get(\"/v1/phone-numbers\", undefined, options)\n }\n\n /**\n * One number by its E.164 value, e.g. `+14155550123`.\n *\n * Keyed on the number rather than on `id`, because the number is what you\n * have when you are asking whether it is registered at all. Throws\n * `NotFoundError` when it is not.\n */\n retrieve(phoneNumber: string, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.get(\n path`/v1/phone-numbers/by-number/${phoneNumber}`,\n undefined,\n options,\n )\n }\n\n /**\n * Partial update.\n *\n * `inbound_agent_id` is **ignored unless `set_inbound_agent: true`** is sent with\n * it, both to set an agent and to clear one (`null`). Same for the outbound pair.\n * `inbound_agents` / `outbound_agents` (weighted routing), when sent, take\n * precedence over the single-agent fields.\n */\n update(phoneNumberId: string, body: PhoneNumberUpdateParams, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.patch(path`/v1/phone-numbers/${phoneNumberId}`, body, options)\n }\n\n /** Set the number's **inbound** agent, or pass `agent_id: null` to clear it. For outbound, use `update`. */\n assign(phoneNumberId: string, body: PhoneNumberAssignParams, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.patch(path`/v1/phone-numbers/${phoneNumberId}/assign`, body, options)\n }\n\n /**\n * Send one signed test request to the number's inbound routing webhook and report what a real call would have done\n * with your answer: the status, how long you took against the time budget, and any field that would be ignored.\n * Throws a `ConflictError` (`inbound_webhook_not_set`) when the number has no `inbound_webhook_url`.\n */\n testInboundWebhook(phoneNumberId: string, options?: RequestOptions): Promise<InboundWebhookTestResult> {\n return this._client.post(path`/v1/phone-numbers/${phoneNumberId}/inbound-webhook/test`, undefined, options)\n }\n\n /**\n * Replace the inbound webhook's signing secret. The new secret is returned **once**, as `inbound_webhook_secret`\n * on the number; the old one stops working at once.\n */\n rotateInboundWebhookSecret(phoneNumberId: string, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.post(path`/v1/phone-numbers/${phoneNumberId}/inbound-webhook/rotate-secret`, undefined, options)\n }\n\n /** Release the number from Dialgem. It stops routing calls and disappears from `list()`; your carrier account is untouched. */\n delete(phoneNumberId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/phone-numbers/${phoneNumberId}`, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type {\n Chat,\n ChatCreateParams,\n ChatDeleteResponse,\n ChatListParams,\n ChatReply,\n ChatUpdateParams,\n} from \"../types/chat.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface ChatListEnvelope {\n chats: Chat[]\n has_more: boolean\n pagination_key: string | null\n}\n\n/**\n * Text conversations with one of your agents, from your backend.\n *\n * const chat = await dialgem.chats.create({ agent_id, dynamic_variables: { customer: \"Ada\" } })\n * const { messages } = await dialgem.chats.sendMessage(chat.id, \"Can I come in on Tuesday?\")\n * await dialgem.chats.end(chat.id)\n *\n * The agent is the one that answers your phone: same prompt, model and functions. Prompt agents only; an agent\n * that keeps no transcript cannot chat. Your API key stays on your server; to put a chat box on a web page,\n * have your backend call `sendMessage` for the visitor.\n */\nexport class Chats extends APIResource {\n /**\n * Start a chat. If the agent has a first message it is already in `messages`.\n *\n * `UnprocessableEntityError` with `errCode` `agent_type_not_supported` (flow agents) or `chat_requires_storage`.\n * Not retried by default.\n */\n create(body: ChatCreateParams, options?: RequestOptions): Promise<Chat> {\n return this._client.post(\"/v1/chats\", body, options)\n }\n\n /**\n * Chats, newest first. Await for one page, or iterate for every chat. Entries leave out `messages`;\n * `retrieve` a chat for them.\n */\n list(params: ChatListParams = {}, options?: RequestOptions): PagePromise<Chat> {\n const fetchPage = async (paginationKey: string | null): Promise<PageData<Chat>> => {\n const res = await this._client.get<ChatListEnvelope>(\n \"/v1/chats\",\n { ...(params as Query), pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.chats, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n /** One chat with all its messages. */\n retrieve(chatId: string, options?: RequestOptions): Promise<Chat> {\n return this._client.get(path`/v1/chats/${chatId}`, undefined, options)\n }\n\n /** Replace the chat's `metadata` (the whole object). */\n update(chatId: string, body: ChatUpdateParams, options?: RequestOptions): Promise<Chat> {\n return this._client.patch(path`/v1/chats/${chatId}`, body, options)\n }\n\n /** Delete a chat and its messages. */\n delete(chatId: string, options?: RequestOptions): Promise<ChatDeleteResponse> {\n return this._client.delete(path`/v1/chats/${chatId}`, options)\n }\n\n /**\n * Send the user's message and wait for the agent's reply. Returns only the new entries, in order: the user's\n * message, any tool use, the agent's reply.\n *\n * If the agent's model fails (`ServerError`, `errCode` `model_error`) nothing is stored and the same message\n * can be sent again. `ConflictError` with `errCode` `chat_busy` while another reply is in progress,\n * `chat_ended` after the end, `message_limit` at the cap. If the agent calls its end-call tool, the reply's\n * `chat_status` is `ended`.\n *\n * Not retried by default: a retry after an ambiguous failure could send the message twice.\n */\n sendMessage(chatId: string, content: string, options?: RequestOptions): Promise<ChatReply> {\n return this._client.post(path`/v1/chats/${chatId}/messages`, { content }, options)\n }\n\n /** End the chat. Ending twice is fine. The analysis arrives a moment later; read it with `retrieve`. */\n end(chatId: string, options?: RequestOptions): Promise<Chat> {\n return this._client.post(path`/v1/chats/${chatId}/end`, undefined, options)\n }\n\n /**\n * Analyse an ended chat again with the agent's current analysis settings and return it. `ConflictError` with\n * `errCode` `chat_in_progress` until it has ended, `no_transcript` when it has no messages.\n */\n rerunAnalysis(chatId: string, options?: RequestOptions): Promise<Chat> {\n return this._client.post(path`/v1/chats/${chatId}/rerun-analysis`, undefined, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type { Flow, FlowCreateParams, FlowDeleteResponse, FlowListParams, FlowUpdateParams } from \"../types/flow.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface FlowListEnvelope {\n flows: Flow[]\n has_more: boolean\n pagination_key: string | null\n}\n\n/**\n * Conversation flows you save once and attach to agents.\n *\n * const flow = await dialgem.flows.create({ name: \"Intake\", flow_config })\n * await dialgem.agents.create({ name: \"Front desk\", agent_type: \"flow\", flow_id: flow.id })\n *\n * A flow is checked the way an agent's `flow_config` is, so a saved flow is one that would have saved on an\n * agent. **Attaching copies it**: `agents.create` / `agents.update` with `flow_id` takes a snapshot, and editing\n * or deleting the flow afterwards changes no agent, no published version and no call.\n */\nexport class Flows extends APIResource {\n /** Validate and save a flow. `UnprocessableEntityError` (`errCode` `flow_invalid`) lists every problem. Not retried by default. */\n create(body: FlowCreateParams, options?: RequestOptions): Promise<Flow> {\n return this._client.post(\"/v1/flows\", body, options)\n }\n\n /** Flows, newest first. Await for one page, or iterate for every flow. Entries leave out `flow_config`. */\n list(params: FlowListParams = {}, options?: RequestOptions): PagePromise<Flow> {\n const fetchPage = async (paginationKey: string | null): Promise<PageData<Flow>> => {\n const res = await this._client.get<FlowListEnvelope>(\n \"/v1/flows\",\n { ...(params as Query), pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.flows, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n /** One flow with its `flow_config`. */\n retrieve(flowId: string, options?: RequestOptions): Promise<Flow> {\n return this._client.get(path`/v1/flows/${flowId}`, undefined, options)\n }\n\n /** Rename a flow and/or replace its `flow_config` (checked again). Agents it was attached to are not changed. */\n update(flowId: string, body: FlowUpdateParams, options?: RequestOptions): Promise<Flow> {\n return this._client.patch(path`/v1/flows/${flowId}`, body, options)\n }\n\n /** Delete a saved flow. Agents it was attached to keep their copy. */\n delete(flowId: string, options?: RequestOptions): Promise<FlowDeleteResponse> {\n return this._client.delete(path`/v1/flows/${flowId}`, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type { LLM, LLMCreateParams, LLMDeleteResponse, LLMListParams, LLMUpdateParams } from \"../types/llm.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface LLMListEnvelope {\n llms: LLM[]\n has_more: boolean\n pagination_key: string | null\n}\n\n/**\n * A prompt and model you set up once and attach to agents.\n *\n * const llm = await dialgem.llms.create({ name: \"Booking\", system_prompt, llm_model: \"gpt-4o-mini\" })\n * await dialgem.agents.create({ name: \"Front desk\", llm_id: llm.id })\n *\n * It holds `system_prompt`, `first_message`, `llm_provider`, `llm_model`, `temperature`, `max_tokens`, the\n * fallback pair and `default_dynamic_variables`. **Attaching copies it**: `agents.create` / `agents.update` with\n * `llm_id` writes those values into the agent, and editing or deleting the saved LLM afterwards changes no\n * agent, no published version and no call. Sending `llm_id` together with any of those fields is refused.\n */\nexport class LLMs extends APIResource {\n /** Save LLM settings. Anything left out takes the default a new agent gets. Not retried by default. */\n create(body: LLMCreateParams, options?: RequestOptions): Promise<LLM> {\n return this._client.post(\"/v1/llms\", body, options)\n }\n\n /** Saved LLMs, newest first. Await for one page, or iterate for every one. */\n list(params: LLMListParams = {}, options?: RequestOptions): PagePromise<LLM> {\n const fetchPage = async (paginationKey: string | null): Promise<PageData<LLM>> => {\n const res = await this._client.get<LLMListEnvelope>(\n \"/v1/llms\",\n { ...(params as Query), pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.llms, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n retrieve(llmId: string, options?: RequestOptions): Promise<LLM> {\n return this._client.get(path`/v1/llms/${llmId}`, undefined, options)\n }\n\n /** Change the fields you send. Agents it was attached to are not changed. */\n update(llmId: string, body: LLMUpdateParams, options?: RequestOptions): Promise<LLM> {\n return this._client.patch(path`/v1/llms/${llmId}`, body, options)\n }\n\n /** Delete saved LLM settings. Agents they were attached to keep their copy. */\n delete(llmId: string, options?: RequestOptions): Promise<LLMDeleteResponse> {\n return this._client.delete(path`/v1/llms/${llmId}`, options)\n }\n}\n","import { DialgemError, WebhookVerificationError } from \"./core/errors.js\"\nimport type { FunctionCallRequest, WebhookEvent } from \"./types/webhook.js\"\n\n/** Header carrying the request signature: `v=<timestamp_ms>,d=<hex>`. */\nexport const WEBHOOK_SIGNATURE_HEADER = \"x-dialgem-signature\"\n/** Header naming the event; the same value as the body's `event`. */\nexport const WEBHOOK_EVENT_HEADER = \"x-dialgem-event\"\n/**\n * During a signing-secret rotation overlap, the same body signed with the PREVIOUS\n * secret. Verify `x-dialgem-signature` with the new secret; a receiver that has not\n * switched yet can verify this one with the old secret instead.\n */\nexport const WEBHOOK_PREVIOUS_SIGNATURE_HEADER = \"x-dialgem-signature-previous\"\n/** Header with an id that stays the same across retries of one delivery. */\nexport const WEBHOOK_DELIVERY_HEADER = \"x-dialgem-delivery\"\n\n/** Signatures older or newer than this are rejected, so a captured request cannot be replayed. */\nexport const DEFAULT_SIGNATURE_TOLERANCE_MS = 5 * 60 * 1000\n\n/** The raw request body, byte-for-byte as received. Node `Buffer` is a `Uint8Array`. */\nexport type WebhookPayload = string | Uint8Array | ArrayBuffer\n\n/** A header value as Node's `IncomingHttpHeaders`, `Headers.get()` or a framework hands it over. */\nexport type SignatureHeader = string | string[] | null | undefined\n\nexport interface VerifyOptions {\n /** Maximum age (and clock skew) of a signature, in ms. Default 5 minutes. */\n toleranceMs?: number | undefined\n /** The current time in epoch ms. For tests; defaults to `Date.now()`. */\n now?: number | undefined\n}\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\nconst SIGNATURE_RE = /^v=(\\d{10,16}),d=([0-9a-f]{64})$/\n\n/**\n * Verifies and parses what Dialgem sends to your servers: event webhooks, and\n * requests to your custom functions. Both use one signature scheme:\n *\n * x-dialgem-signature: v=<timestamp_ms>,d=<hex>\n * hex = HMAC-SHA256(secret, raw_body + timestamp_ms)\n *\n * The secret is the agent's `webhook_signing_secret`.\n *\n * **Pass the raw body.** The signature covers the exact bytes Dialgem sent. A body\n * that was parsed and re-serialized (`express.json()`, `JSON.stringify(req.body)`)\n * will not match, even when the JSON is equal. Use `express.raw({ type: \"application/json\" })`,\n * Fastify's raw body, or `await request.text()` in a route handler.\n */\nexport class Webhooks {\n /**\n * Returns whether `signature` is a current, valid signature of `payload` under\n * `secret`. Constant-time. Returns `false` for a missing, malformed, tampered or\n * stale signature; throws only if `secret` is empty, which is a configuration\n * error rather than a bad request.\n */\n async verify(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions = {},\n ): Promise<boolean> {\n if (!secret) {\n throw new DialgemError(\n \"Webhook secret is empty. Set the agent's `webhook_signing_secret` and pass the same value here.\",\n )\n }\n const match = SIGNATURE_RE.exec(firstHeader(signature)?.trim().toLowerCase() ?? \"\")\n if (!match) return false\n const [, timestamp, received] = match as unknown as [string, string, string]\n const now = options.now ?? Date.now()\n if (Math.abs(now - Number(timestamp)) > (options.toleranceMs ?? DEFAULT_SIGNATURE_TOLERANCE_MS)) {\n return false\n }\n const body = toBytes(payload)\n const message = new Uint8Array(body.length + timestamp.length)\n message.set(body, 0)\n message.set(encoder.encode(timestamp), body.length)\n const expected = await hmacSha256Hex(secret, message)\n return timingSafeEqual(expected, received)\n }\n\n /**\n * Verifies a webhook's signature, then parses its body.\n *\n * @throws WebhookVerificationError if the signature is missing, invalid or stale.\n */\n async constructEvent(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions = {},\n ): Promise<WebhookEvent> {\n const parsed = await this.#verifiedJson(payload, signature, secret, options)\n if (typeof parsed !== \"object\" || parsed === null || typeof (parsed as { event?: unknown }).event !== \"string\") {\n throw new WebhookVerificationError(\"Webhook body has no `event` field.\")\n }\n return parsed as WebhookEvent\n }\n\n /**\n * Verifies a request Dialgem made to one of your custom functions, then parses\n * its body. For functions with `args_at_root`, the body is the arguments object\n * alone; use `verify` and parse it yourself.\n *\n * @throws WebhookVerificationError if the signature is missing, invalid or stale.\n */\n async constructFunctionCall<Args = Record<string, unknown>>(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions = {},\n ): Promise<FunctionCallRequest<Args>> {\n const parsed = await this.#verifiedJson(payload, signature, secret, options)\n const body = parsed as Partial<FunctionCallRequest<Args>> | null\n if (!body || typeof body.name !== \"string\" || typeof body.call !== \"object\" || body.call === null) {\n throw new WebhookVerificationError(\n \"Function request body has no `name` and `call`. Does this function have args_at_root set?\",\n )\n }\n return body as FunctionCallRequest<Args>\n }\n\n async #verifiedJson(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions,\n ): Promise<unknown> {\n if (!firstHeader(signature)) {\n throw new WebhookVerificationError(\n `Missing ${WEBHOOK_SIGNATURE_HEADER} header. Is a webhook_signing_secret set on the agent?`,\n )\n }\n if (!(await this.verify(payload, signature, secret, options))) {\n throw new WebhookVerificationError(\n \"Signature is invalid or older than the allowed tolerance. Check the secret, the server clock, and that the body was not re-serialized before verification.\",\n )\n }\n const text = typeof payload === \"string\" ? payload : decoder.decode(toBytes(payload))\n try {\n return JSON.parse(text)\n } catch {\n throw new WebhookVerificationError(\"Body is signed but is not valid JSON.\")\n }\n }\n}\n\nexport const webhooks = new Webhooks()\n\nfunction firstHeader(value: SignatureHeader): string | undefined {\n const v = Array.isArray(value) ? value[0] : value\n return v ?? undefined\n}\n\nfunction toBytes(payload: WebhookPayload): Uint8Array {\n if (typeof payload === \"string\") return encoder.encode(payload)\n if (payload instanceof Uint8Array) return payload\n return new Uint8Array(payload)\n}\n\nasync function hmacSha256Hex(secret: string, data: Uint8Array): Promise<string> {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new DialgemError(\"Web Crypto (globalThis.crypto.subtle) is unavailable. Node 20 or newer is required.\")\n }\n const key = await subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"])\n // Copy into a fresh ArrayBuffer-backed view: a Node Buffer can be a slice of a\n // larger pooled ArrayBuffer, and some Web Crypto implementations reject SharedArrayBuffer views.\n const signature = await subtle.sign(\"HMAC\", key, new Uint8Array(data))\n return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\n/** Compares two equal-format hex strings without an early exit. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n","import { DialgemError } from \"./core/errors.js\"\nimport { HttpClient, assertMaxRetries, assertTimeout, type Fetch } from \"./core/http.js\"\nimport { Agents } from \"./resources/agents.js\"\nimport { Calls } from \"./resources/calls.js\"\nimport { ExtractionModels, FlowTemplates, PromptTemplates, Voices } from \"./resources/catalog.js\"\nimport { ApiKey, Sessions } from \"./resources/account.js\"\nimport { Simulations } from \"./resources/simulations.js\"\nimport { WebCalls } from \"./resources/web-calls.js\"\nimport { ContactLists, Contacts } from \"./resources/contacts.js\"\nimport { PhoneNumbers } from \"./resources/phone-numbers.js\"\nimport { Chats } from \"./resources/chats.js\"\nimport { Flows } from \"./resources/flows.js\"\nimport { LLMs } from \"./resources/llms.js\"\nimport { Webhooks, webhooks } from \"./webhooks.js\"\n\n/** The Dialgem API. Fixed: the SDK talks to Dialgem and nothing else. */\nexport const BASE_URL = \"https://api.dialgem.com\"\nconst DEFAULT_TIMEOUT_MS = 60_000\nconst DEFAULT_MAX_RETRIES = 2\n\n// Optional fields accept an explicit `undefined` so `new Dialgem({ apiKey: process.env.X })`\n// compiles under `exactOptionalPropertyTypes`; undefined means \"use the default\".\nexport interface ClientOptions {\n /** Organization API key (`zk_…`). Defaults to `process.env.DIALGEM_API_KEY`. */\n apiKey?: string | undefined\n /** Per-attempt timeout in milliseconds (> 0). Default 60000. */\n timeout?: number | undefined\n /** Retries for GET/PATCH/DELETE on 408/429/5xx and connection errors. Default 2. POST is not retried. */\n maxRetries?: number | undefined\n /** Custom fetch implementation (a proxy agent, instrumentation, tests). Defaults to the global `fetch`. */\n fetch?: Fetch | undefined\n /** Headers sent with every request. */\n defaultHeaders?: Record<string, string> | undefined\n /**\n * The API key grants full access to your organization, so constructing the\n * client in a browser throws by default. Only set this for a trusted internal tool.\n */\n dangerouslyAllowBrowser?: boolean | undefined\n}\n\n/**\n * Dialgem API client, for use from your backend.\n *\n * ```ts\n * import { Dialgem } from \"@dialgem/sdk\"\n *\n * const dialgem = new Dialgem() // reads DIALGEM_API_KEY\n * const agent = await dialgem.agents.create({ name: \"Front desk\", system_prompt: \"…\" })\n * ```\n */\nexport class Dialgem {\n static readonly BASE_URL = BASE_URL\n /** Webhook verification without a client instance: `Dialgem.webhooks.constructEvent(...)`. */\n static readonly webhooks: Webhooks = webhooks\n\n readonly agents: Agents\n readonly calls: Calls\n readonly phoneNumbers: PhoneNumbers\n readonly voices: Voices\n /** Models available for post-call analysis. */\n readonly extractionModels: ExtractionModels\n readonly flowTemplates: FlowTemplates\n readonly promptTemplates: PromptTemplates\n /** Calls in progress right now. */\n readonly sessions: Sessions\n /** Text conversations with an agent. */\n readonly chats: Chats\n readonly flows: Flows\n readonly llms: LLMs\n /** What this API key is and may do. */\n readonly apiKey: ApiKey\n /**\n * Verify what Dialgem sends you: `dialgem.webhooks.constructEvent(rawBody, signatureHeader, secret)`.\n */\n readonly webhooks: Webhooks = webhooks\n /** The organization's webhook destinations: create, update, rotate the signing secret, test. */\n /** The people you call, with CSV import under `contacts.imports`. */\n readonly contacts: Contacts\n /** Named groups of contacts. */\n readonly contactLists: ContactLists\n /** Browser calls: tokens for `@dialgem/client`, and the origins allowed to start them. */\n readonly webCalls: WebCalls\n /** Saved test conversations for an agent, run in text, with an optional publish gate. */\n readonly simulations: Simulations\n\n /** Always `https://api.dialgem.com`. */\n readonly baseURL: string = BASE_URL\n\n constructor(options: ClientOptions = {}) {\n // `baseURL` was an option in 0.1.0-beta.0. Refused rather than ignored: a\n // caller still passing a staging or local URL would otherwise have its key\n // start hitting production with no sign anything had changed.\n if (\"baseURL\" in (options as Record<string, unknown>)) {\n throw new DialgemError(\n \"`baseURL` is not an option: the SDK always talks to https://api.dialgem.com. Remove it.\",\n )\n }\n\n if (isBrowser() && !options.dangerouslyAllowBrowser) {\n throw new DialgemError(\n \"The Dialgem SDK is for server-side use: running it in a browser exposes your API key to every visitor. \" +\n \"Call Dialgem from your backend instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.\",\n )\n }\n\n const apiKey = options.apiKey ?? readEnv(\"DIALGEM_API_KEY\")\n if (!apiKey) {\n throw new DialgemError(\n \"Missing API key. Pass `apiKey` to `new Dialgem({ apiKey })` or set the DIALGEM_API_KEY environment variable.\",\n )\n }\n\n const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n assertTimeout(timeout)\n assertMaxRetries(maxRetries)\n\n const fetchImpl = options.fetch ?? defaultFetch()\n\n const http = new HttpClient({\n apiKey,\n baseURL: BASE_URL,\n timeout,\n maxRetries,\n fetch: fetchImpl,\n defaultHeaders: options.defaultHeaders ?? {},\n })\n\n this.agents = new Agents(http)\n this.calls = new Calls(http)\n this.phoneNumbers = new PhoneNumbers(http)\n this.voices = new Voices(http)\n this.extractionModels = new ExtractionModels(http)\n this.flowTemplates = new FlowTemplates(http)\n this.promptTemplates = new PromptTemplates(http)\n this.sessions = new Sessions(http)\n this.chats = new Chats(http)\n this.flows = new Flows(http)\n this.llms = new LLMs(http)\n this.apiKey = new ApiKey(http)\n this.contacts = new Contacts(http)\n this.contactLists = new ContactLists(http)\n this.webCalls = new WebCalls(http)\n this.simulations = new Simulations(http)\n }\n}\n\nfunction readEnv(name: string): string | undefined {\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n const value = proc?.env?.[name]?.trim()\n return value ? value : undefined\n}\n\nfunction isBrowser(): boolean {\n const g = globalThis as { window?: unknown; document?: unknown }\n return typeof g.window !== \"undefined\" && typeof g.document !== \"undefined\"\n}\n\nfunction defaultFetch(): Fetch {\n const f = (globalThis as { fetch?: unknown }).fetch\n if (typeof f !== \"function\") {\n throw new DialgemError(\"No global `fetch` found. Use Node 20 or newer, or pass `fetch` in the client options.\")\n }\n // Bound per call rather than stored: some runtimes throw \"Illegal invocation\"\n // when fetch is called detached from globalThis.\n return (url, init) => (f as Fetch).call(globalThis, url, init)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/errors.ts","../src/version.ts","../src/core/http.ts","../src/resources/resource.ts","../src/resources/agents.ts","../src/core/pagination.ts","../src/resources/calls.ts","../src/resources/catalog.ts","../src/resources/account.ts","../src/resources/simulations.ts","../src/resources/web-calls.ts","../src/resources/contacts.ts","../src/resources/phone-numbers.ts","../src/resources/chats.ts","../src/resources/flows.ts","../src/resources/llms.ts","../src/webhooks.ts","../src/client.ts"],"names":["path"],"mappings":";;;AAyCO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA,GAAO,cAAA;AAClB;AAE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CAAK,WAAA,GAAc,IAAI,WAAA,CAAY,IAAI,CAAA;AAAA,EACzC;AACF;AAEA,SAAS,QAAQ,IAAA,EAAkC;AACjD,EAAA,MAAM,OAAQ,UAAA,CAA0E,OAAA;AACxF,EAAA,MAAM,KAAA,GAAQ,IAAA,EAAM,GAAA,GAAM,IAAI,GAAG,IAAA,EAAK;AACtC,EAAA,OAAO,QAAQ,KAAA,GAAQ,MAAA;AACzB;AAEA,SAAS,SAAA,GAAqB;AAC5B,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,OAAO,OAAO,CAAA,CAAE,MAAA,KAAW,WAAA,IAAe,OAAO,EAAE,QAAA,KAAa,WAAA;AAClE;AAEA,SAAS,YAAA,GAAsB;AAC7B,EAAA,MAAM,IAAK,UAAA,CAAmC,KAAA;AAC9C,EAAA,IAAI,OAAO,MAAM,UAAA,EAAY;AAC3B,IAAA,MAAM,IAAI,aAAa,uFAAuF,CAAA;AAAA,EAChH;AAGA,EAAA,OAAO,CAAC,GAAA,EAAK,IAAA,KAAU,EAAY,IAAA,CAAK,UAAA,EAAY,KAAK,IAAI,CAAA;AAC/D","file":"index.cjs","sourcesContent":["/**\n * Every failure the SDK raises is a `DialgemError`.\n *\n * HTTP failures are `APIError` subclasses chosen by status, so a caller can\n * `catch (e) { if (e instanceof NotFoundError) ... }`. Within a status, branch on\n * `errCode`: the API documents `err_code` as the one field clients\n * branch on, e.g. `flow_invalid`,\n * `flow_not_runnable`, `NOT_A_MEMBER`.\n */\n\n/**\n * One entry of `issues[]` (in an error body, or an agent's `flow_validation`): a\n * field error or a flow graph rule.\n */\nexport interface ErrorIssue {\n /** Stable machine-readable identifier of the rule. */\n code?: string\n severity?: \"error\" | \"warning\"\n message?: string\n node_id?: string | null\n edge_id?: string | null\n /** Path into the request body, for field errors. */\n loc?: (string | number)[] | null\n meta?: Record<string, unknown>\n [key: string]: unknown\n}\n\n/** The API's error envelope. */\nexport interface ErrorBody {\n err_code: string\n err_msg: string\n request_id: string\n issues?: ErrorIssue[]\n [key: string]: unknown\n}\n\n/** Minimal read-only view of response headers, independent of the fetch implementation. */\nexport interface HeadersLike {\n get(name: string): string | null\n}\n\nexport class DialgemError extends Error {\n override name = \"DialgemError\"\n}\n\nexport class APIError extends DialgemError {\n override name = \"APIError\"\n /** HTTP status code. */\n readonly status: number\n /** The service's `err_code`, e.g. `flow_invalid` or `HTTP_404`. Undefined if the body was not the envelope. */\n readonly errCode: string | undefined\n /** The service's `request_id`. Quote it when contacting support. */\n readonly requestId: string | undefined\n /** Field/graph diagnostics, present on validation failures. */\n readonly issues: readonly ErrorIssue[]\n /** Parsed JSON body, or the raw text if the body was not JSON. */\n readonly body: unknown\n readonly headers: HeadersLike\n\n constructor(status: number, body: unknown, message: string, headers: HeadersLike) {\n super(message)\n this.status = status\n this.body = body\n this.headers = headers\n const envelope = isErrorBody(body) ? body : undefined\n this.errCode = envelope?.err_code\n this.requestId = envelope?.request_id ?? headers.get(\"x-request-id\") ?? undefined\n this.issues = envelope?.issues ?? []\n }\n\n /** Build the subclass matching `status`. */\n static from(status: number, body: unknown, statusText: string, headers: HeadersLike): APIError {\n const envelope = isErrorBody(body) ? body : undefined\n const detail = envelope?.err_msg || (typeof body === \"string\" && body.trim() ? body.trim().slice(0, 500) : \"\")\n const message = detail ? `${status} ${detail}` : `${status} ${statusText || \"status code (no body)\"}`\n const Ctor = errorClassFor(status)\n return new Ctor(status, body, message, headers)\n }\n}\n\nexport class BadRequestError extends APIError {\n override name = \"BadRequestError\"\n}\nexport class AuthenticationError extends APIError {\n override name = \"AuthenticationError\"\n}\nexport class PermissionDeniedError extends APIError {\n override name = \"PermissionDeniedError\"\n}\nexport class NotFoundError extends APIError {\n override name = \"NotFoundError\"\n}\nexport class ConflictError extends APIError {\n override name = \"ConflictError\"\n}\nexport class UnprocessableEntityError extends APIError {\n override name = \"UnprocessableEntityError\"\n}\nexport class RateLimitError extends APIError {\n override name = \"RateLimitError\"\n}\nexport class InternalServerError extends APIError {\n override name = \"InternalServerError\"\n}\n\n/** The request never produced an HTTP response (DNS, TLS, reset, aborted by the caller). */\nexport class APIConnectionError extends DialgemError {\n override name = \"APIConnectionError\"\n constructor(message = \"Connection error.\", options?: { cause?: unknown }) {\n super(message, options)\n }\n}\n\n/** The caller's `signal` aborted the request. Never retried. */\nexport class APIUserAbortError extends DialgemError {\n override name = \"APIUserAbortError\"\n constructor(message = \"Request was aborted.\") {\n super(message)\n }\n}\n\n/** The request exceeded the configured `timeout`. */\nexport class APIConnectionTimeoutError extends APIConnectionError {\n override name = \"APIConnectionTimeoutError\"\n constructor(message = \"Request timed out.\") {\n super(message)\n }\n}\n\n/** A webhook's signature did not match its body. */\nexport class WebhookVerificationError extends DialgemError {\n override name = \"WebhookVerificationError\"\n}\n\nfunction errorClassFor(status: number): typeof APIError {\n switch (status) {\n case 400:\n return BadRequestError\n case 401:\n return AuthenticationError\n case 403:\n return PermissionDeniedError\n case 404:\n return NotFoundError\n case 409:\n return ConflictError\n case 422:\n return UnprocessableEntityError\n case 429:\n return RateLimitError\n default:\n return status >= 500 ? InternalServerError : APIError\n }\n}\n\nfunction isErrorBody(body: unknown): body is ErrorBody {\n return typeof body === \"object\" && body !== null && typeof (body as { err_code?: unknown }).err_code === \"string\"\n}\n","// Kept in step with package.json by tests/version.test.ts.\nexport const VERSION = \"1.0.0\"\n","import {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIError,\n APIUserAbortError,\n DialgemError,\n type HeadersLike,\n} from \"./errors.js\"\nimport { VERSION } from \"../version.js\"\n\n/**\n * The slice of `fetch` the SDK uses. Declared structurally so any conforming\n * implementation (Node's global fetch, undici, node-fetch, a test double) fits,\n * without the SDK's public types depending on DOM lib typings.\n */\nexport type Fetch = (url: string, init: FetchInit) => Promise<FetchResponse>\n\nexport interface FetchInit {\n method: string\n headers: Record<string, string>\n /**\n * A JSON string, or a `FormData` for a file upload — in which case\n * `Content-Type` is deliberately absent, since only `fetch` knows the\n * multipart boundary it is about to generate.\n */\n body?: string | FormData\n signal: AbortSignal\n /**\n * Always `\"manual\"`. A followed redirect re-sends the API key to wherever the\n * `Location` points (fetch strips only `Authorization` cross-origin, not\n * `X-API-Key`), and turns a 301'd POST into a GET that \"succeeds\" with the\n * wrong body. The API never redirects, so a 3xx is surfaced as an `APIError`.\n */\n redirect: \"manual\"\n}\n\nexport interface FetchResponse {\n readonly status: number\n readonly statusText: string\n readonly headers: HeadersLike\n text(): Promise<string>\n}\n\n/** Per-call overrides, accepted as the last argument of every resource method. */\n// Every optional field also accepts an explicit `undefined`, so a caller compiling\n// with `exactOptionalPropertyTypes` can pass `{ signal: maybeSignal }` directly.\nexport interface RequestOptions {\n /** Milliseconds (> 0) before the attempt is aborted. Applies per attempt, not across retries. */\n timeout?: number | undefined\n /**\n * Retries on 408/429/5xx and connection failures.\n *\n * GET, PUT, PATCH and DELETE use the client's `maxRetries` unless overridden here.\n * **POST is never retried unless you set this explicitly**: most POSTs create\n * things, and an outbound call retried after an ambiguous 502 dials the person twice.\n */\n maxRetries?: number | undefined\n /** Abort the request. Surfaces as `APIUserAbortError`. */\n signal?: AbortSignal | undefined\n /** Extra headers for this request only. */\n headers?: Record<string, string> | undefined\n}\n\nexport type QueryScalar = string | number | boolean\n/** Arrays are sent as repeated parameters: `{ status: [\"a\", \"b\"] }` → `?status=a&status=b`. */\nexport type QueryValue = QueryScalar | QueryScalar[] | null | undefined\nexport type Query = Record<string, QueryValue>\n\nexport interface HttpClientOptions {\n apiKey: string\n baseURL: string\n timeout: number\n maxRetries: number\n fetch: Fetch\n defaultHeaders: Record<string, string>\n}\n\ntype Method = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\"\n\nconst RETRYABLE_METHODS: ReadonlySet<Method> = new Set([\"GET\", \"PUT\", \"PATCH\", \"DELETE\"])\nconst MAX_RETRY_DELAY_MS = 60_000\n\nexport class HttpClient {\n readonly baseURL: string\n readonly #apiKey: string\n readonly #timeout: number\n readonly #maxRetries: number\n readonly #fetch: Fetch\n readonly #defaultHeaders: Record<string, string>\n\n constructor(options: HttpClientOptions) {\n this.baseURL = options.baseURL.replace(/\\/+$/, \"\")\n this.#apiKey = options.apiKey\n this.#timeout = options.timeout\n this.#maxRetries = options.maxRetries\n this.#fetch = options.fetch\n this.#defaultHeaders = options.defaultHeaders\n }\n\n get<T>(path: string, query?: Query, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"GET\", path, { query, options })\n }\n\n post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"POST\", path, { body, options })\n }\n\n /**\n * POST a `FormData` body — file uploads.\n *\n * The body is sent as-is and `Content-Type` is left unset, because only\n * `fetch` knows the multipart boundary it is about to generate. Setting the\n * header ourselves produces a request no server can parse.\n */\n postForm<T>(path: string, form: FormData, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"POST\", path, { body: form, options })\n }\n\n put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"PUT\", path, { body, options })\n }\n\n patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"PATCH\", path, { body, options })\n }\n\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(\"DELETE\", path, { options })\n }\n\n async request<T>(\n method: Method,\n path: string,\n { query, body, options = {} }: { query?: Query | undefined; body?: unknown; options?: RequestOptions | undefined },\n ): Promise<T> {\n const url = this.buildURL(path, query)\n const isForm = isFormData(body)\n const headers = this.buildHeaders(body !== undefined && !isForm, options.headers)\n const payload = body === undefined ? undefined : isForm ? (body as FormData) : JSON.stringify(body)\n const timeout = options.timeout ?? this.#timeout\n // A multipart body is never retried, even on request. Its parts may be\n // one-shot streams, so a second attempt can send a truncated upload — and\n // the one thing worse than a failed clone is a clone built from half the\n // audio, which succeeds and sounds wrong.\n const maxRetries = isForm\n ? 0\n : options.maxRetries ?? (RETRYABLE_METHODS.has(method) ? this.#maxRetries : 0)\n assertTimeout(timeout)\n assertMaxRetries(maxRetries)\n\n for (let attempt = 0; ; attempt++) {\n const retriesLeft = maxRetries - attempt\n if (options.signal?.aborted) throw new APIUserAbortError()\n\n const outcome = await this.#attempt(url, method, headers, payload, timeout, options.signal)\n\n if (outcome.kind === \"response\") {\n const { status, statusText, headers: responseHeaders, text } = outcome\n if (status >= 200 && status < 300) return parseSuccess<T>(text, status)\n if (retriesLeft > 0 && isRetryableStatus(status)) {\n await sleep(retryAfterMs(responseHeaders) ?? backoffMs(attempt), options.signal)\n continue\n }\n throw APIError.from(status, parseErrorBody(text), statusText, responseHeaders)\n }\n\n if (options.signal?.aborted) throw new APIUserAbortError()\n if (retriesLeft > 0) {\n await sleep(backoffMs(attempt), options.signal)\n continue\n }\n throw outcome.error\n }\n }\n\n /** One HTTP attempt, with its own timeout. Never throws; timers and listeners are released before it returns. */\n async #attempt(\n url: string,\n method: Method,\n headers: Record<string, string>,\n payload: string | FormData | undefined,\n timeout: number,\n signal: AbortSignal | undefined,\n ): Promise<\n | { kind: \"response\"; status: number; statusText: string; headers: HeadersLike; text: string }\n | { kind: \"failure\"; error: APIConnectionError }\n > {\n const controller = new AbortController()\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort()\n }, timeout)\n const onUserAbort = () => controller.abort()\n signal?.addEventListener(\"abort\", onUserAbort, { once: true })\n\n try {\n const init: FetchInit = { method, headers, signal: controller.signal, redirect: \"manual\" }\n if (payload !== undefined) init.body = payload\n const response = await this.#fetch(url, init)\n // Read inside the timer: a server that sends headers then stalls the body\n // must still hit the timeout rather than hang the caller.\n const text = await response.text()\n return { kind: \"response\", status: response.status, statusText: response.statusText, headers: response.headers, text }\n } catch (err) {\n const error = timedOut\n ? new APIConnectionTimeoutError(`Request timed out after ${timeout}ms.`)\n : new APIConnectionError(`Connection error: ${describe(err)}`, { cause: err })\n return { kind: \"failure\", error }\n } finally {\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", onUserAbort)\n }\n }\n\n buildURL(path: string, query?: Query): string {\n const url = `${this.baseURL}${path.startsWith(\"/\") ? path : `/${path}`}`\n if (!query) return url\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue\n for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item))\n }\n const qs = params.toString()\n return qs ? `${url}?${qs}` : url\n }\n\n private buildHeaders(hasBody: boolean, extra?: Record<string, string>): Record<string, string> {\n // Merged case-insensitively, later layers winning. A plain object spread would\n // keep both `X-API-Key` and a caller's `x-api-key`, which fetch then joins\n // into one comma-separated value the service rejects.\n const merged = new Map<string, [name: string, value: string]>()\n const layer = (headers: Record<string, string> | undefined) => {\n for (const [name, value] of Object.entries(headers ?? {})) merged.set(name.toLowerCase(), [name, value])\n }\n layer({\n Accept: \"application/json\",\n // `X-API-Key`, not `Authorization: Bearer`: the API only tries a\n // Bearer value as a session JWT, so an org key sent that way is a 401.\n \"X-API-Key\": this.#apiKey,\n \"User-Agent\": userAgent(),\n })\n layer(this.#defaultHeaders)\n layer(extra)\n if (hasBody) layer({ \"Content-Type\": \"application/json\" })\n return Object.fromEntries(merged.values())\n }\n}\n\n/** `FormData` without assuming it exists — it does on every supported runtime. */\nfunction isFormData(value: unknown): value is FormData {\n return typeof FormData !== \"undefined\" && value instanceof FormData\n}\n\nexport function assertTimeout(value: number): void {\n // 0 is rejected rather than read as \"no timeout\": setTimeout(…, 0) would abort\n // every attempt immediately, and an unbounded request is never what a backend wants.\n if (!Number.isInteger(value) || value <= 0) {\n throw new DialgemError(`\\`timeout\\` must be a positive integer of milliseconds, got ${String(value)}.`)\n }\n}\n\nexport function assertMaxRetries(value: number): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new DialgemError(`\\`maxRetries\\` must be a non-negative integer, got ${String(value)}.`)\n }\n}\n\nfunction parseSuccess<T>(text: string, status: number): T {\n if (status === 204 || text.trim() === \"\") return undefined as T\n try {\n return JSON.parse(text) as T\n } catch (err) {\n throw new DialgemError(`Expected a JSON response (status ${status}) but could not parse it: ${describe(err)}`)\n }\n}\n\nfunction parseErrorBody(text: string): unknown {\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction isRetryableStatus(status: number): boolean {\n // Not 409: the API's 409s are real conflicts (a phone number already\n // registered), which a retry would only repeat.\n return status === 408 || status === 429 || status >= 500\n}\n\n/** Exponential backoff with jitter: ~0.5s, 1s, 2s, … capped at 8s. */\nfunction backoffMs(attempt: number): number {\n const base = Math.min(500 * 2 ** attempt, 8_000)\n return base * (1 - Math.random() * 0.25)\n}\n\n/** Honour `retry-after-ms`, then `Retry-After` (seconds or an HTTP date). */\nfunction retryAfterMs(headers: HeadersLike): number | undefined {\n const ms = Number(headers.get(\"retry-after-ms\"))\n if (Number.isFinite(ms) && ms > 0) return Math.min(ms, MAX_RETRY_DELAY_MS)\n const raw = headers.get(\"retry-after\")\n if (!raw) return undefined\n const seconds = Number(raw)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, MAX_RETRY_DELAY_MS)\n const date = Date.parse(raw)\n if (Number.isFinite(date)) return Math.min(Math.max(date - Date.now(), 0), MAX_RETRY_DELAY_MS)\n return undefined\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(new APIUserAbortError())\n const onAbort = () => {\n clearTimeout(timer)\n reject(new APIUserAbortError())\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort)\n resolve()\n }, ms)\n signal?.addEventListener(\"abort\", onAbort, { once: true })\n })\n}\n\nfunction userAgent(): string {\n const proc = (globalThis as { process?: { version?: string } }).process\n return proc?.version ? `dialgem-sdk-node/${VERSION} node/${proc.version}` : `dialgem-sdk-node/${VERSION}`\n}\n\nfunction describe(err: unknown): string {\n if (err instanceof Error) {\n const cause = (err as { cause?: unknown }).cause\n return cause instanceof Error ? `${err.message} (${cause.message})` : err.message\n }\n return String(err)\n}\n","import { DialgemError } from \"../core/errors.js\"\nimport type { HttpClient } from \"../core/http.js\"\n\nexport abstract class APIResource {\n protected readonly _client: HttpClient\n\n constructor(client: HttpClient) {\n this._client = client\n }\n}\n\n/**\n * Builds a path with each interpolated id URI-encoded.\n *\n * Rejects an empty id rather than sending it: `/v1/agents/${\"\"}` is\n * `/v1/agents/`, which a `retrieve(\"\")` would turn into a silent *list*\n * call, and a `delete(\"\")` into a confusing 405.\n */\nexport function path(strings: TemplateStringsArray, ...ids: string[]): string {\n let out = strings[0] ?? \"\"\n ids.forEach((id, i) => {\n if (typeof id !== \"string\" || id.trim() === \"\") {\n throw new DialgemError(`Expected a non-empty id in ${strings.join(\"{id}\")}, got ${JSON.stringify(id)}.`)\n }\n out += encodeURIComponent(id) + (strings[i + 1] ?? \"\")\n })\n return out\n}\n","import type { HttpClient, RequestOptions } from \"../core/http.js\"\nimport type { Agent, AgentDeleteResponse } from \"../types/agent.js\"\nimport type { AgentFunction, KnowledgeDocument, MCPServer, MCPServerTestResult, MCPToolList } from \"../types/agent-resources.js\"\nimport type {\n AgentVersion,\n AgentVersionListParams,\n AgentVersionListResponse,\n AgentVersionPublishParams,\n AgentVersionSummary,\n} from \"../types/agent-version.js\"\nimport type {\n AgentCreateParams,\n AgentUpdateParams,\n FunctionCreateParams,\n FunctionReorderParams,\n FunctionUpdateParams,\n KnowledgeDocumentCreateParams,\n MCPServerCreateParams,\n MCPServerUpdateParams,\n} from \"../types/params.js\"\nimport { DialgemError } from \"../core/errors.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class Agents extends APIResource {\n /** Tools (HTTP functions and built-ins like `end_call`) the agent can call. */\n readonly functions: AgentFunctions\n /** Text documents the agent retrieves from during the call. */\n readonly knowledge: AgentKnowledge\n /** Remote MCP servers whose tools are exposed to the agent. */\n readonly mcpServers: AgentMCPServers\n /** Frozen snapshots of the agent that a number or a call can pin. */\n readonly versions: AgentVersions\n\n constructor(client: HttpClient) {\n super(client)\n this.functions = new AgentFunctions(client)\n this.knowledge = new AgentKnowledge(client)\n this.mcpServers = new AgentMCPServers(client)\n this.versions = new AgentVersions(client)\n }\n\n /** Create an agent. Only `name` is required; everything else has a server default. */\n create(body: AgentCreateParams, options?: RequestOptions): Promise<Agent> {\n return this._client.post(\"/v1/agents\", body, options)\n }\n\n retrieve(agentId: string, options?: RequestOptions): Promise<Agent> {\n return this._client.get(path`/v1/agents/${agentId}`, undefined, options)\n }\n\n /** Every agent in the organization. `webhook_signing_secret` is `null` in this list. */\n list(options?: RequestOptions): Promise<Agent[]> {\n return this._client.get(\"/v1/agents\", undefined, options)\n }\n\n /** Partial update: only the fields you send change. */\n update(agentId: string, body: AgentUpdateParams, options?: RequestOptions): Promise<Agent> {\n return this._client.patch(path`/v1/agents/${agentId}`, body, options)\n }\n\n delete(agentId: string, options?: RequestOptions): Promise<AgentDeleteResponse> {\n return this._client.delete(path`/v1/agents/${agentId}`, options)\n }\n}\n\n/**\n * Published versions of an agent.\n *\n * The agent itself is the draft, version 0, and every call runs it unless a\n * number or a request pins a published version. Publishing takes a copy;\n * editing the agent afterwards changes only the draft.\n */\nexport class AgentVersions extends APIResource {\n /** Freeze the agent as it is now. Returns the new version, snapshot included. */\n publish(\n agentId: string,\n body: AgentVersionPublishParams = {},\n options?: RequestOptions,\n ): Promise<AgentVersion> {\n return this._client.post(path`/v1/agents/${agentId}/versions`, body, options)\n }\n\n/**\n * One page of published versions, newest first, without their snapshots.\n *\n * Returns the array. When you need to page — an agent published on every\n * deploy accumulates versions, and nothing prunes them — read `has_more` from\n * {@link listPage} instead and pass the last `version` as `before_version`.\n */\n async list(\n agentId: string,\n params?: AgentVersionListParams,\n options?: RequestOptions,\n ): Promise<AgentVersionSummary[]> {\n return (await this.listPage(agentId, params, options)).versions\n }\n\n /** {@link list} with the `has_more` flag, for paging. */\n listPage(\n agentId: string,\n params?: AgentVersionListParams,\n options?: RequestOptions,\n ): Promise<AgentVersionListResponse> {\n return this._client.get(\n path`/v1/agents/${agentId}/versions`,\n // Spread into a plain query record: an `interface` has no index\n // signature, so it does not structurally satisfy `Query`.\n { ...params },\n options,\n )\n }\n\n /** One version with its full snapshot. Version 0 is the draft: use `agents.retrieve`. */\n retrieve(agentId: string, version: number, options?: RequestOptions): Promise<AgentVersion> {\n return this._client.get(\n path`/v1/agents/${agentId}/versions/${versionSegment(version)}`,\n undefined,\n options,\n )\n }\n}\n\n/**\n * A version number as a path segment.\n *\n * Rejected here rather than sent: a fractional or negative number would 404 or\n * 422 from the server with nothing pointing at the caller's own value, and\n * `undefined` reaching the template would request the whole collection.\n */\nfunction versionSegment(version: number): string {\n if (!Number.isInteger(version) || version < 1) {\n throw new DialgemError(\n `Expected a published version number (a positive integer), got ${JSON.stringify(version)}. ` +\n \"Version 0 is the draft — read it with agents.retrieve().\",\n )\n }\n return String(version)\n}\n\nexport class AgentFunctions extends APIResource {\n list(agentId: string, options?: RequestOptions): Promise<AgentFunction[]> {\n return this._client.get(path`/v1/agents/${agentId}/functions`, undefined, options)\n }\n\n create(agentId: string, body: FunctionCreateParams, options?: RequestOptions): Promise<AgentFunction> {\n return this._client.post(path`/v1/agents/${agentId}/functions`, body, options)\n }\n\n update(\n agentId: string,\n functionId: string,\n body: FunctionUpdateParams,\n options?: RequestOptions,\n ): Promise<AgentFunction> {\n return this._client.patch(path`/v1/agents/${agentId}/functions/${functionId}`, body, options)\n }\n\n delete(agentId: string, functionId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/agents/${agentId}/functions/${functionId}`, options)\n }\n\n /** Set the order functions are offered to the LLM. `order` is function ids, first to last. */\n reorder(agentId: string, body: FunctionReorderParams, options?: RequestOptions): Promise<void> {\n return this._client.post(path`/v1/agents/${agentId}/functions/reorder`, body, options)\n }\n}\n\nexport class AgentKnowledge extends APIResource {\n list(agentId: string, options?: RequestOptions): Promise<KnowledgeDocument[]> {\n return this._client.get(path`/v1/agents/${agentId}/knowledge`, undefined, options)\n }\n\n /** Add a plain-text document (up to 500,000 characters). It is chunked and embedded server-side. */\n create(agentId: string, body: KnowledgeDocumentCreateParams, options?: RequestOptions): Promise<KnowledgeDocument> {\n return this._client.post(path`/v1/agents/${agentId}/knowledge`, body, options)\n }\n\n delete(agentId: string, sourceId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/agents/${agentId}/knowledge/${sourceId}`, options)\n }\n}\n\nexport class AgentMCPServers extends APIResource {\n list(agentId: string, options?: RequestOptions): Promise<MCPServer[]> {\n return this._client.get(path`/v1/agents/${agentId}/mcp-servers`, undefined, options)\n }\n\n create(agentId: string, body: MCPServerCreateParams, options?: RequestOptions): Promise<MCPServer> {\n return this._client.post(path`/v1/agents/${agentId}/mcp-servers`, body, options)\n }\n\n update(agentId: string, serverId: string, body: MCPServerUpdateParams, options?: RequestOptions): Promise<MCPServer> {\n return this._client.patch(path`/v1/agents/${agentId}/mcp-servers/${serverId}`, body, options)\n }\n\n delete(agentId: string, serverId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/agents/${agentId}/mcp-servers/${serverId}`, options)\n }\n\n /** Connect to the server now, list its tools, and store the result as `last_status`. */\n /**\n * What the server offers right now, with each tool's description and argument schema. Connects live like\n * `test`, but stores nothing. An unreachable server is not an error: `tools` is empty and `error` says why.\n */\n listTools(agentId: string, serverId: string, options?: RequestOptions): Promise<MCPToolList> {\n return this._client.get(path`/v1/agents/${agentId}/mcp-servers/${serverId}/tools`, undefined, options)\n }\n\n test(agentId: string, serverId: string, options?: RequestOptions): Promise<MCPServerTestResult> {\n return this._client.post(path`/v1/agents/${agentId}/mcp-servers/${serverId}/test`, undefined, options)\n }\n}\n","/**\n * Cursor pagination, as used by `GET /v1/calls`.\n *\n * `list()` returns a `PagePromise`, which is both awaitable (one page) and\n * async-iterable (every item across pages):\n *\n * const page = await client.calls.list({ limit: 50 })\n * for await (const call of client.calls.list({ status: \"completed\" })) { ... }\n *\n * Pages are keyset-based, so walking them is stable while new calls arrive: no\n * call is skipped or repeated because another one started mid-walk.\n */\nimport { DialgemError } from \"./errors.js\"\n\nexport interface PageData<T> {\n data: T[]\n has_more: boolean\n /** Pass to the next request to continue; `null` on the last page. */\n pagination_key: string | null\n}\n\nexport type PageFetcher<T> = (paginationKey: string | null) => Promise<PageData<T>>\n\nexport class Page<T> implements PageData<T> {\n readonly data: T[]\n readonly has_more: boolean\n readonly pagination_key: string | null\n readonly #fetchPage: PageFetcher<T>\n\n constructor(data: PageData<T>, fetchPage: PageFetcher<T>) {\n this.data = data.data\n this.has_more = data.has_more\n this.pagination_key = data.pagination_key\n this.#fetchPage = fetchPage\n }\n\n hasNextPage(): boolean {\n return this.has_more && this.pagination_key !== null\n }\n\n async getNextPage(): Promise<Page<T>> {\n if (!this.hasNextPage()) throw new DialgemError(\"No next page; check hasNextPage() first.\")\n return new Page(await this.#fetchPage(this.pagination_key), this.#fetchPage)\n }\n}\n\nexport class PagePromise<T> implements PromiseLike<Page<T>>, AsyncIterable<T> {\n readonly #fetchPage: PageFetcher<T>\n readonly #startKey: string | null\n #first: Promise<Page<T>> | undefined\n\n constructor(fetchPage: PageFetcher<T>, startKey: string | null = null) {\n this.#fetchPage = fetchPage\n this.#startKey = startKey\n }\n\n #firstPage(): Promise<Page<T>> {\n // Lazy and memoised: nothing is sent until awaited or iterated, and awaiting\n // then iterating the same PagePromise does not refetch page one.\n this.#first ??= this.#fetchPage(this.#startKey).then((data) => new Page(data, this.#fetchPage))\n return this.#first\n }\n\n then<R1 = Page<T>, R2 = never>(\n onfulfilled?: ((value: Page<T>) => R1 | PromiseLike<R1>) | null,\n onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n return this.#firstPage().then(onfulfilled, onrejected)\n }\n\n catch<R = never>(onrejected?: ((reason: unknown) => R | PromiseLike<R>) | null): Promise<Page<T> | R> {\n return this.#firstPage().catch(onrejected)\n }\n\n finally(onfinally?: (() => void) | null): Promise<Page<T>> {\n return this.#firstPage().finally(onfinally)\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let page: Page<T> = await this.#firstPage()\n for (;;) {\n yield* page.data\n if (!page.hasNextPage()) return\n page = await page.getNextPage()\n }\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type {\n Call,\n CallDeleteResponse,\n CallListParams,\n CallRegisterResponse,\n CallStopResponse,\n CallUpdateParams,\n PhoneCallCreateResponse,\n} from \"../types/call.js\"\nimport type { CallCreatePhoneCallParams, CallRegisterParams } from \"../types/params.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface CallListEnvelope {\n calls: Call[]\n has_more: boolean\n pagination_key: string | null\n}\n\nexport class Calls extends APIResource {\n /**\n * Calls, newest first by default. Await for one page, or iterate for every call:\n *\n * const page = await dialgem.calls.list({ limit: 50 })\n * for await (const call of dialgem.calls.list({ status: \"completed\", start_after: since })) { ... }\n */\n list(params: CallListParams = {}, options?: RequestOptions): PagePromise<Call> {\n const query = toQuery(params)\n const fetchPage = async (paginationKey: string | null): Promise<PageData<Call>> => {\n const res = await this._client.get<CallListEnvelope>(\n \"/v1/calls\",\n { ...query, pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.calls, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n /** One call, including its transcript, analysis, latency and recording URL. */\n retrieve(callId: string, options?: RequestOptions): Promise<Call> {\n return this._client.get(path`/v1/calls/${callId}`, undefined, options)\n }\n\n /** Replace the call's `metadata`. */\n update(callId: string, body: CallUpdateParams, options?: RequestOptions): Promise<Call> {\n return this._client.patch(path`/v1/calls/${callId}`, body, options)\n }\n\n /**\n * Permanently delete a finished call: its record, transcript, analysis and\n * recording. A call still in progress is refused with `ConflictError`; stop it first.\n */\n delete(callId: string, options?: RequestOptions): Promise<CallDeleteResponse> {\n return this._client.delete(path`/v1/calls/${callId}`, options)\n }\n\n /**\n * Run a finished call's post-call analysis again, with the agent's *current* analysis\n * settings, and return the updated call. Use it after changing the fields or the model\n * and wanting an older call read the new way.\n *\n * It replaces `analysis`; it does not bill the call again and does not send `call_analyzed`\n * again, so read the result from this response or from `retrieve`. The model call can take\n * a while. `ConflictError` with `errCode` `call_in_progress` until the call has ended,\n * `no_transcript` when there is nothing to analyze, `agent_deleted` if the agent is gone.\n * Not retried by default.\n */\n rerunAnalysis(callId: string, options?: RequestOptions): Promise<Call> {\n return this._client.post(path`/v1/calls/${callId}/rerun-analysis`, undefined, options)\n }\n\n /**\n * End an ongoing call now, as if the agent had hung up. The call becomes\n * `completed` with `disconnection_reason: \"manual_stopped\"` a moment later, and\n * the usual `call_ended` webhook follows.\n *\n * `ConflictError` with `errCode` `call_not_ongoing` if it already ended, or\n * `call_not_connected` if no agent is on the call yet (e.g. still ringing).\n * Not retried by default.\n */\n stop(callId: string, options?: RequestOptions): Promise<CallStopResponse> {\n return this._client.post(path`/v1/calls/${callId}/stop`, undefined, options)\n }\n\n /**\n * Dial `to` from one of your organization's numbers, with `agent_id` (or the\n * number's outbound agent) on the line.\n *\n * Not retried by default: a retry after an ambiguous failure can place a\n * second call. Follow progress through webhooks or `retrieve(call_id)`.\n */\n createPhoneCall(body: CallCreatePhoneCallParams, options?: RequestOptions): Promise<PhoneCallCreateResponse> {\n return this._client.post(\"/v1/calls/outbound\", body, options)\n }\n\n /**\n * Bring-your-own-Twilio: call this from your Twilio voice webhook, then answer\n * Twilio with `<Response><Connect><Stream url=\"{stream_url}\"/></Connect></Response>`.\n * No Twilio credentials are shared with Dialgem.\n */\n register(body: CallRegisterParams, options?: RequestOptions): Promise<CallRegisterResponse> {\n return this._client.post(\"/v1/calls/register\", body, options)\n }\n}\n\nfunction toQuery(params: CallListParams): Query {\n const { metadata, ...rest } = params\n const query: Query = { ...rest }\n // `limit` selects cursor pagination server-side; without it the API answers in\n // its page-number mode, which this client does not read.\n query[\"limit\"] = params.limit ?? 10\n for (const [key, value] of Object.entries(metadata ?? {})) {\n query[`metadata.${key}`] = String(value)\n }\n return query\n}\n","import { DialgemError } from \"../core/errors.js\"\nimport type { Query, RequestOptions } from \"../core/http.js\"\nimport type {\n ExtractionModelList,\n FlowTemplate,\n FlowTemplateSummary,\n PromptTemplate,\n PromptTemplateSummary,\n TemplateListParams,\n Voice,\n VoiceCloneParams,\n VoiceDeleteResponse,\n VoiceListParams,\n} from \"../types/catalog.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class Voices extends APIResource {\n /**\n * Voices available to agents: the shared catalog plus the ones your\n * organization cloned, yours first. Put a voice's `provider_voice_id` in an\n * agent's `voice_id`.\n */\n list(params: VoiceListParams = {}, options?: RequestOptions): Promise<Voice[]> {\n return this._client.get(\"/v1/voices\", params as Query, options)\n }\n\n /**\n * Clone a voice from audio you upload. The new voice is private to your\n * organization and never appears in another one's catalog.\n *\n * Consent is required: you are asserting that you hold the rights to the\n * audio and have the speaker's consent, and that assertion is recorded\n * against your API identity.\n *\n * The upload is never retried, whatever `maxRetries` says — a retried\n * multipart body can send truncated audio, and a clone built from half the\n * recording succeeds and sounds wrong.\n */\n clone(params: VoiceCloneParams, options?: RequestOptions): Promise<Voice> {\n const { name, files, consent_confirmed, engine, description, language, filenames } = params\n if (!consent_confirmed) {\n throw new DialgemError(\n \"consent_confirmed must be true: you are asserting that you hold the rights \" +\n \"to this audio and have the speaker's consent to clone their voice.\",\n )\n }\n if (!files?.length) {\n throw new DialgemError(\"At least one audio file is required to clone a voice.\")\n }\n\n const form = new FormData()\n form.append(\"name\", name)\n form.append(\"consent_confirmed\", \"true\")\n if (engine) form.append(\"engine\", engine)\n if (description) form.append(\"description\", description)\n if (language) form.append(\"language\", language)\n files.forEach((file, i) => {\n // The provider infers the container from the extension, so every part is\n // given a name — the caller's, the Blob's own, or a generated one.\n const fallback = (file as File).name || `clip-${i + 1}.wav`\n form.append(\"files\", file, filenames?.[i] ?? fallback)\n })\n\n return this._client.postForm(\"/v1/voices/clone\", form, options)\n }\n\n /**\n * Delete a voice your organization cloned, at the provider and here.\n *\n * Only your own cloned voices: the shared catalog is not deletable, and a\n * voice an agent still uses is refused with a 409 rather than leaving that\n * agent without one.\n */\n delete(voiceId: string, options?: RequestOptions): Promise<VoiceDeleteResponse> {\n return this._client.delete(path`/v1/voices/${voiceId}`, options)\n }\n}\n\nexport class ExtractionModels extends APIResource {\n /** Models an agent may use for post-call analysis, with an estimated cost per session. */\n list(options?: RequestOptions): Promise<ExtractionModelList> {\n return this._client.get(\"/v1/models/extraction\", undefined, options)\n }\n}\n\nexport class FlowTemplates extends APIResource {\n /** Built-in conversation-flow templates (summaries, without `flow_config`). */\n list(params: TemplateListParams = {}, options?: RequestOptions): Promise<FlowTemplateSummary[]> {\n return this._client.get(\"/v1/flow-templates\", params as Query, options)\n }\n\n retrieve(templateId: string, options?: RequestOptions): Promise<FlowTemplate> {\n return this._client.get(path`/v1/flow-templates/${templateId}`, undefined, options)\n }\n}\n\nexport class PromptTemplates extends APIResource {\n /** Built-in prompt templates (summaries, without the prompt text). */\n list(params: TemplateListParams = {}, options?: RequestOptions): Promise<PromptTemplateSummary[]> {\n return this._client.get(\"/v1/prompt-templates\", params as Query, options)\n }\n\n retrieve(templateId: string, options?: RequestOptions): Promise<PromptTemplate> {\n return this._client.get(path`/v1/prompt-templates/${templateId}`, undefined, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type { ApiKeyInfo } from \"../types/api-key.js\"\nimport type {\n AgentSessionList,\n AgentSessionReleaseResult,\n AgentSessionSayParams,\n AgentSessionSayResult,\n AgentSessionUpdateParams,\n AgentSessionUpdateResult,\n} from \"../types/session.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class ApiKey extends APIResource {\n /**\n * Who this key is: your organization and the key's name, prefix, scopes, allowed addresses\n * and expiry. It answers for any valid key whatever its scopes, so an integration can check\n * what it was given. Never returns the secret.\n *\n * ```ts\n * const { key } = await dialgem.apiKey.retrieve()\n * if (key && !key.full_access) console.log(\"scoped to\", key.scopes)\n * ```\n */\n retrieve(options?: RequestOptions): Promise<ApiKeyInfo> {\n return this._client.get(\"/v1/api-key-info\", undefined, options)\n }\n}\n\nexport class Sessions extends APIResource {\n /**\n * The calls your organization has in progress right now, with a `count`.\n *\n * Live state read from the service's own registry — use it for a\n * concurrency check before placing a call. For finished calls use\n * `calls.list`; a call whose teardown never arrived is not counted here.\n */\n list(options?: RequestOptions): Promise<AgentSessionList> {\n return this._client.get(\"/v1/agent/sessions\", undefined, options)\n }\n\n /**\n * Change a live call's prompt and/or variables. It applies from the agent's **next turn**.\n *\n * `sessionId` is a session's `session_id` from `list`, or the call's own `call_id`. Only this call changes:\n * the agent, its published versions and other calls are untouched, and the change is gone when the call ends.\n * A turn already being spoken finishes as it was. `dynamic_variables` are merged over the call's variables;\n * `system_prompt` replaces the prompt for the rest of the call.\n *\n * The call may be on any service instance. `NotFoundError` if it is not live (or is another organization's),\n * `ConflictError` with `errCode` `session_ended` once it is over, `UnprocessableEntityError` with `errCode`\n * `flow_agent_prompt` for a flow agent's prompt (its variables can still change). Not retried by default.\n *\n * ```ts\n * await dialgem.sessions.update(callId, { dynamic_variables: { plan: \"pro\" } })\n * ```\n */\n update(sessionId: string, body: AgentSessionUpdateParams, options?: RequestOptions): Promise<AgentSessionUpdateResult> {\n return this._client.patch(path`/v1/agent/sessions/${sessionId}`, body, options)\n }\n\n /**\n * Make the agent say `text` on a live call, in its own voice. Answers at once; the line plays behind what the\n * agent is saying, or now with `interrupt: true`. The agent's conversation records it as something it said.\n *\n * Off unless the deployment enables live control: `ForbiddenError` with `errCode` `live_control_disabled`.\n * `ConflictError` `human_has_call` while a human has taken the call. Owners, admins and API keys only.\n * Not retried by default.\n *\n * ```ts\n * await dialgem.sessions.say(callId, { text: \"One moment while I check that.\" })\n * ```\n */\n say(sessionId: string, body: AgentSessionSayParams, options?: RequestOptions): Promise<AgentSessionSayResult> {\n return this._client.post(path`/v1/agent/sessions/${sessionId}/say`, body, options)\n }\n\n /**\n * Hand a taken-over call back to the agent, for when the socket that took it is gone. The agent is told a\n * human had the call and that it did not hear what was said. Same availability and limits as `say`.\n * Listening in and taking over run over a WebSocket (`/v1/agent/sessions/{id}/live`), which this SDK does not wrap.\n */\n release(sessionId: string, options?: RequestOptions): Promise<AgentSessionReleaseResult> {\n return this._client.post(path`/v1/agent/sessions/${sessionId}/release`, undefined, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type {\n SimulationCase,\n SimulationCaseInput,\n SimulationRun,\n SimulationRunCreateParams,\n SimulationRunDetail,\n SimulationRunList,\n SimulationSuite,\n SimulationSuiteCreateParams,\n SimulationSuiteDetail,\n SimulationSuiteList,\n SimulationSuiteUpdateParams,\n} from \"../types/simulation.js\"\nimport { APIResource, path } from \"./resource.js\"\n\n/**\n * Test your agent before a change reaches a caller. A **suite** holds **cases**; in each, a simulated caller\n * talks to the agent in text and your **checks** decide whether it passed.\n *\n * A simulation is not a call: nothing is dialled, recorded or billed, and the agent's tools are never really\n * called. Simulations spend model usage, so they are switched on per platform; until then every method answers\n * 403 `simulations_disabled`.\n *\n * const suite = await dialgem.simulations.createSuite({ agent_id, name: \"Refunds\" })\n * await dialgem.simulations.createCase(suite.id, {\n * name: \"Asks for a refund\",\n * caller: { mode: \"script\", turns: [\"I want my money back.\"] },\n * checks: [{ type: \"not_contains\", text: \"full refund\" }],\n * })\n * const run = await dialgem.simulations.run(suite.id)\n * // poll retrieveRun(run.id) until status is \"completed\"\n */\nexport class Simulations extends APIResource {\n /** Make a suite for one of your agents. */\n createSuite(body: SimulationSuiteCreateParams, options?: RequestOptions): Promise<SimulationSuite> {\n return this._client.post(\"/v1/simulations/suites\", body, options)\n }\n\n /** Your suites, newest first, each with its latest run. Pass `agent_id` for one agent's. */\n listSuites(params: { agent_id?: string } = {}, options?: RequestOptions): Promise<SimulationSuiteList> {\n return this._client.get(\"/v1/simulations/suites\", params, options)\n }\n\n /** One suite with its cases. */\n retrieveSuite(suiteId: string, options?: RequestOptions): Promise<SimulationSuiteDetail> {\n return this._client.get(path`/v1/simulations/suites/${suiteId}`, undefined, options)\n }\n\n /**\n * Rename a suite or set its publish gate: `off`, `warn` (publishing a version succeeds and lists the suites the draft\n * has not passed) or `block` (publishing is refused with 409 `simulation_required` until it has).\n */\n updateSuite(suiteId: string, body: SimulationSuiteUpdateParams, options?: RequestOptions): Promise<SimulationSuite> {\n return this._client.patch(path`/v1/simulations/suites/${suiteId}`, body, options)\n }\n\n /** Delete a suite and its cases. Past runs are deleted with it. */\n deleteSuite(suiteId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/simulations/suites/${suiteId}`, options)\n }\n\n /** Add a case (up to 50 per suite). 422 `invalid_case` says what to fix. */\n createCase(suiteId: string, body: SimulationCaseInput, options?: RequestOptions): Promise<SimulationCase> {\n return this._client.post(path`/v1/simulations/suites/${suiteId}/cases`, body, options)\n }\n\n /** Change a case. Fields you leave out keep their value. */\n updateCase(caseId: string, body: Partial<SimulationCaseInput>, options?: RequestOptions): Promise<SimulationCase> {\n return this._client.patch(path`/v1/simulations/cases/${caseId}`, body, options)\n }\n\n deleteCase(caseId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/simulations/cases/${caseId}`, options)\n }\n\n /**\n * Run every case of a suite against the draft, a published version or `\"latest_published\"`. Answers at once\n * (`202`); the run happens in the background, so poll `retrieveRun` until `status` is `completed`.\n *\n * 409 `suite_empty`, 422 `agent_type_not_supported` (multi-prompt agents), 429 `too_many_runs` or\n * `daily_run_limit`.\n */\n run(suiteId: string, body: SimulationRunCreateParams = {}, options?: RequestOptions): Promise<SimulationRun> {\n return this._client.post(path`/v1/simulations/suites/${suiteId}/runs`, body, options)\n }\n\n /** Runs, newest first. Pass `suite_id` for one suite's. */\n listRuns(params: { suite_id?: string; limit?: number } = {}, options?: RequestOptions): Promise<SimulationRunList> {\n return this._client.get(\"/v1/simulations/runs\", params, options)\n }\n\n /** A run with every case's transcript, tool calls and check results. */\n retrieveRun(runId: string, options?: RequestOptions): Promise<SimulationRunDetail> {\n return this._client.get(path`/v1/simulations/runs/${runId}`, undefined, options)\n }\n\n /** Stop a run that has not finished. Cases already under way finish; the rest are skipped. */\n cancelRun(runId: string, options?: RequestOptions): Promise<SimulationRun> {\n return this._client.post(path`/v1/simulations/runs/${runId}/cancel`, undefined, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type { WebCall, WebCallCreateParams, WebCallSettings, WebCallSettingsUpdateParams } from \"../types/web-call.js\"\nimport { APIResource } from \"./resource.js\"\n\n/**\n * Let a visitor talk to one of your agents from a web page, with `@dialgem/client`.\n *\n * Your **backend** calls `create` with your API key and gives the returned `access_token` to the page; the\n * page connects with that token alone. The key never reaches the browser. Before the first call, allow the\n * page's origin with `updateSettings`.\n */\nexport class WebCalls extends APIResource {\n /**\n * Create a call for one visitor and get its access token.\n *\n * const { access_token } = await dialgem.webCalls.create({ agent_id, metadata: { visitor: \"v_123\" } })\n *\n * `metadata` and `dialgem_llm_dynamic_variables` are fixed here, by you, and cannot be changed by the page.\n * 409 `web_origins_not_configured` until an origin is allowed; 402 if the organization cannot pay for calls;\n * 429 when more than `limits.tokens_per_minute` calls are created in a minute.\n */\n create(body: WebCallCreateParams, options?: RequestOptions): Promise<WebCall> {\n return this._client.post(\"/v1/calls/web\", body, options)\n }\n\n /** The origins browser calls may start from, and the limits that apply. */\n retrieveSettings(options?: RequestOptions): Promise<WebCallSettings> {\n return this._client.get(\"/v1/web-calls/settings\", undefined, options)\n }\n\n /**\n * Replace the allowed origins. Each is `scheme://host[:port]`; `https://*.example.com` allows any subdomain\n * (not the bare domain) and `*` allows any website. Tokens already issued keep the list they were issued with.\n */\n updateSettings(body: WebCallSettingsUpdateParams, options?: RequestOptions): Promise<WebCallSettings> {\n return this._client.put(\"/v1/web-calls/settings\", body, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type {\n Contact,\n ContactCallList,\n ContactCreateParams,\n ContactCsvInspection,\n ContactDeleteResponse,\n ContactImport,\n ContactImportCreateParams,\n ContactImportErrors,\n ContactImportList,\n ContactListCreateParams,\n ContactListDeleteResponse,\n ContactListMemberRemoveResponse,\n ContactListMembersAddResponse,\n ContactListParams,\n ContactListRecord,\n ContactListUpdateParams,\n ContactUpdateParams,\n} from \"../types/contact.js\"\nimport { APIResource, path } from \"./resource.js\"\nimport type { HttpClient } from \"../core/http.js\"\n\ninterface ContactListEnvelope {\n contacts: Contact[]\n total: number\n next_cursor: string | null\n}\n\n/**\n * The people your organization calls. A phone number identifies each one: it is stored\n * in international form however you write it, and each number can be a contact once.\n */\nexport class Contacts extends APIResource {\n /** Bulk import from CSV, with a dry-run preview. */\n readonly imports: ContactImports\n\n constructor(client: HttpClient) {\n super(client)\n this.imports = new ContactImports(client)\n }\n\n /**\n * Add a contact. `phone` is any way of writing a valid number; without a leading `+`\n * also pass `default_country` (`\"US\"`). A number that is already a contact answers 409\n * with its `contact_id`.\n */\n create(body: ContactCreateParams, options?: RequestOptions): Promise<Contact> {\n return this._client.post(\"/v1/contacts\", body, options)\n }\n\n /**\n * Contacts, newest first. Await for one page, or iterate for every contact:\n *\n */\n list(params: ContactListParams = {}, options?: RequestOptions): PagePromise<Contact> {\n const fetchPage = async (cursor: string | null): Promise<PageData<Contact>> => {\n const res = await this._client.get<ContactListEnvelope>(\n \"/v1/contacts\",\n { ...(params as Query), cursor: cursor ?? undefined },\n options,\n )\n return { data: res.contacts, has_more: res.next_cursor !== null, pagination_key: res.next_cursor }\n }\n return new PagePromise(fetchPage)\n }\n\n /**\n * The contact with this phone number. The number is matched as E.164, so\n * `(\"(212) 220-0001\", { default_country: \"US\" })` finds `+12122200001`. Throws\n * `NotFoundError` if you have no such contact, and `UnprocessableEntityError` if the text is\n * not a phone number.\n */\n retrieveByPhone(phone: string, params: { default_country?: string | undefined } = {}, options?: RequestOptions): Promise<Contact> {\n return this._client.get(path`/v1/contacts/by-phone/${phone}`, params as Query, options)\n }\n\n /** One contact, with its lists and how many calls it has had. */\n retrieve(contactId: string, options?: RequestOptions): Promise<Contact> {\n return this._client.get(path`/v1/contacts/${contactId}`, undefined, options)\n }\n\n /**\n * Partial update: only the fields you send change, and `null` clears a field.\n * `attributes` replaces the whole set, so send every field you want kept.\n */\n update(contactId: string, body: ContactUpdateParams, options?: RequestOptions): Promise<Contact> {\n return this._client.patch(path`/v1/contacts/${contactId}`, body, options)\n }\n\n /**\n * Erase a contact and its list memberships. Calls already made stay in the call log, and\n * a do-not-call entry for the number stays too, so forgetting a person never makes a number\n * that asked not to be called dialable again.\n */\n delete(contactId: string, options?: RequestOptions): Promise<ContactDeleteResponse> {\n return this._client.delete(path`/v1/contacts/${contactId}`, options)\n }\n\n /** Calls to or from the contact's number, newest first. Summaries, not transcripts. */\n calls(contactId: string, params: { limit?: number | undefined } = {}, options?: RequestOptions): Promise<ContactCallList> {\n return this._client.get(path`/v1/contacts/${contactId}/calls`, params as Query, options)\n }\n\n}\n\n/**\n * CSV import runs in the background. Typical flow: `inspect` to see the columns, `create`\n * with `dry_run: true`, poll `retrieve` until `previewed`, look at the counts (and `errors`),\n * then `commit` and poll until `completed`.\n *\n * The CSV text is sent in the request. Downloading the rejected rows as a CSV, and exporting\n * contacts, are available over the REST API (`GET /v1/contacts/imports/{id}/errors?format=csv`,\n * `GET /v1/contacts/export`).\n */\nexport class ContactImports extends APIResource {\n /** The file's headers, a guessed column mapping and a few rows. Imports nothing. */\n inspect(csv: string, options?: RequestOptions): Promise<ContactCsvInspection> {\n return this._client.post(\"/v1/contacts/imports/inspect\", { csv }, options)\n }\n\n /**\n * Start an import. Without `mapping` the columns are guessed from the headers. With\n * `dry_run: true` nothing is written: the import only validates and reports.\n */\n create(body: ContactImportCreateParams, options?: RequestOptions): Promise<ContactImport> {\n return this._client.post(\"/v1/contacts/imports\", body, options)\n }\n\n /** Recent imports, newest first. */\n list(options?: RequestOptions): Promise<ContactImportList> {\n return this._client.get(\"/v1/contacts/imports\", undefined, options)\n }\n\n /** Progress and counts. */\n retrieve(importId: string, options?: RequestOptions): Promise<ContactImport> {\n return this._client.get(path`/v1/contacts/imports/${importId}`, undefined, options)\n }\n\n /** The rows that were rejected, with the line, the reason and what each held. */\n errors(importId: string, params: { limit?: number | undefined } = {}, options?: RequestOptions): Promise<ContactImportErrors> {\n return this._client.get(path`/v1/contacts/imports/${importId}/errors`, params as Query, options)\n }\n\n /** Apply a previewed import: the file is read again, so what is applied is what was previewed. */\n commit(importId: string, options?: RequestOptions): Promise<ContactImport> {\n return this._client.post(path`/v1/contacts/imports/${importId}/commit`, undefined, options)\n }\n\n /** Stop an import that has not finished. Contacts a running import already wrote stay. */\n cancel(importId: string, options?: RequestOptions): Promise<ContactImport> {\n return this._client.delete(path`/v1/contacts/imports/${importId}`, options)\n }\n}\n\n/** Named groups of contacts. Deleting a list never deletes its contacts. */\nexport class ContactLists extends APIResource {\n list(options?: RequestOptions): Promise<{ lists: ContactListRecord[] }> {\n return this._client.get(\"/v1/contact-lists\", undefined, options)\n }\n\n /** Names are unique within your organization, ignoring case. */\n create(body: ContactListCreateParams, options?: RequestOptions): Promise<ContactListRecord> {\n return this._client.post(\"/v1/contact-lists\", body, options)\n }\n\n retrieve(listId: string, options?: RequestOptions): Promise<ContactListRecord> {\n return this._client.get(path`/v1/contact-lists/${listId}`, undefined, options)\n }\n\n update(listId: string, body: ContactListUpdateParams, options?: RequestOptions): Promise<ContactListRecord> {\n return this._client.patch(path`/v1/contact-lists/${listId}`, body, options)\n }\n\n delete(listId: string, options?: RequestOptions): Promise<ContactListDeleteResponse> {\n return this._client.delete(path`/v1/contact-lists/${listId}`, options)\n }\n\n /** Add up to 1000 of your contacts. Already-members are ignored; `added` says how many were new. */\n addContacts(listId: string, contactIds: string[], options?: RequestOptions): Promise<ContactListMembersAddResponse> {\n return this._client.post(path`/v1/contact-lists/${listId}/members`, { contact_ids: contactIds }, options)\n }\n\n removeContact(listId: string, contactId: string, options?: RequestOptions): Promise<ContactListMemberRemoveResponse> {\n return this._client.delete(path`/v1/contact-lists/${listId}/members/${contactId}`, options)\n }\n}\n","import type { RequestOptions } from \"../core/http.js\"\nimport type {\n PhoneNumberAssignParams,\n PhoneNumberBuyParams,\n PhoneNumberCreateParams,\n PhoneNumberSearchParams,\n PhoneNumberUpdateParams,\n} from \"../types/params.js\"\nimport type {\n AvailablePhoneNumbers,\n InboundWebhookTestResult,\n PhoneNumber,\n PurchasedPhoneNumber,\n} from \"../types/phone-number.js\"\nimport { APIResource, path } from \"./resource.js\"\n\nexport class PhoneNumbers extends APIResource {\n /** Register a number you own (`phone_number` in E.164) with Dialgem. */\n create(body: PhoneNumberCreateParams, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.post(\"/v1/phone-numbers\", body, options)\n }\n\n /**\n * Numbers that can be bought, with the monthly price. Throws `NotFoundError` (`number_purchase_disabled`) when the\n * deployment has not switched buying on.\n */\n search(params?: PhoneNumberSearchParams, options?: RequestOptions): Promise<AvailablePhoneNumbers> {\n return this._client.get(\"/v1/phone-numbers/available\", { ...params }, options)\n }\n\n /**\n * Buy one of the numbers `search` returned. **Spends the organization's credit**: the first month is debited now and\n * the rental renews monthly until the number is released. Throws on insufficient credit, or if the carrier no longer\n * has the number; nothing is charged in either case.\n */\n buy(body: PhoneNumberBuyParams, options?: RequestOptions): Promise<PurchasedPhoneNumber> {\n return this._client.post(\"/v1/phone-numbers/buy\", body, options)\n }\n\n /** Every active (not released) number in the organization, newest first. */\n list(options?: RequestOptions): Promise<PhoneNumber[]> {\n return this._client.get(\"/v1/phone-numbers\", undefined, options)\n }\n\n /**\n * One number by its E.164 value, e.g. `+14155550123`.\n *\n * Keyed on the number rather than on `id`, because the number is what you\n * have when you are asking whether it is registered at all. Throws\n * `NotFoundError` when it is not.\n */\n retrieve(phoneNumber: string, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.get(\n path`/v1/phone-numbers/by-number/${phoneNumber}`,\n undefined,\n options,\n )\n }\n\n /**\n * Partial update.\n *\n * `inbound_agent_id` is **ignored unless `set_inbound_agent: true`** is sent with\n * it, both to set an agent and to clear one (`null`). Same for the outbound pair.\n * `inbound_agents` / `outbound_agents` (weighted routing), when sent, take\n * precedence over the single-agent fields.\n */\n update(phoneNumberId: string, body: PhoneNumberUpdateParams, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.patch(path`/v1/phone-numbers/${phoneNumberId}`, body, options)\n }\n\n /** Set the number's **inbound** agent, or pass `agent_id: null` to clear it. For outbound, use `update`. */\n assign(phoneNumberId: string, body: PhoneNumberAssignParams, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.patch(path`/v1/phone-numbers/${phoneNumberId}/assign`, body, options)\n }\n\n /**\n * Send one signed test request to the number's inbound routing webhook and report what a real call would have done\n * with your answer: the status, how long you took against the time budget, and any field that would be ignored.\n * Throws a `ConflictError` (`inbound_webhook_not_set`) when the number has no `inbound_webhook_url`.\n */\n testInboundWebhook(phoneNumberId: string, options?: RequestOptions): Promise<InboundWebhookTestResult> {\n return this._client.post(path`/v1/phone-numbers/${phoneNumberId}/inbound-webhook/test`, undefined, options)\n }\n\n /**\n * Replace the inbound webhook's signing secret. The new secret is returned **once**, as `inbound_webhook_secret`\n * on the number; the old one stops working at once.\n */\n rotateInboundWebhookSecret(phoneNumberId: string, options?: RequestOptions): Promise<PhoneNumber> {\n return this._client.post(path`/v1/phone-numbers/${phoneNumberId}/inbound-webhook/rotate-secret`, undefined, options)\n }\n\n /** Release the number from Dialgem. It stops routing calls and disappears from `list()`; your carrier account is untouched. */\n delete(phoneNumberId: string, options?: RequestOptions): Promise<void> {\n return this._client.delete(path`/v1/phone-numbers/${phoneNumberId}`, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type {\n Chat,\n ChatCreateParams,\n ChatDeleteResponse,\n ChatListParams,\n ChatReply,\n ChatUpdateParams,\n} from \"../types/chat.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface ChatListEnvelope {\n chats: Chat[]\n has_more: boolean\n pagination_key: string | null\n}\n\n/**\n * Text conversations with one of your agents, from your backend.\n *\n * const chat = await dialgem.chats.create({ agent_id, dynamic_variables: { customer: \"Ada\" } })\n * const { messages } = await dialgem.chats.sendMessage(chat.id, \"Can I come in on Tuesday?\")\n * await dialgem.chats.end(chat.id)\n *\n * The agent is the one that answers your phone: same prompt, model and functions. Prompt agents only; an agent\n * that keeps no transcript cannot chat. Your API key stays on your server; to put a chat box on a web page,\n * have your backend call `sendMessage` for the visitor.\n */\nexport class Chats extends APIResource {\n /**\n * Start a chat. If the agent has a first message it is already in `messages`.\n *\n * `UnprocessableEntityError` with `errCode` `agent_type_not_supported` (flow agents) or `chat_requires_storage`.\n * Not retried by default.\n */\n create(body: ChatCreateParams, options?: RequestOptions): Promise<Chat> {\n return this._client.post(\"/v1/chats\", body, options)\n }\n\n /**\n * Chats, newest first. Await for one page, or iterate for every chat. Entries leave out `messages`;\n * `retrieve` a chat for them.\n */\n list(params: ChatListParams = {}, options?: RequestOptions): PagePromise<Chat> {\n const fetchPage = async (paginationKey: string | null): Promise<PageData<Chat>> => {\n const res = await this._client.get<ChatListEnvelope>(\n \"/v1/chats\",\n { ...(params as Query), pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.chats, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n /** One chat with all its messages. */\n retrieve(chatId: string, options?: RequestOptions): Promise<Chat> {\n return this._client.get(path`/v1/chats/${chatId}`, undefined, options)\n }\n\n /** Replace the chat's `metadata` (the whole object). */\n update(chatId: string, body: ChatUpdateParams, options?: RequestOptions): Promise<Chat> {\n return this._client.patch(path`/v1/chats/${chatId}`, body, options)\n }\n\n /** Delete a chat and its messages. */\n delete(chatId: string, options?: RequestOptions): Promise<ChatDeleteResponse> {\n return this._client.delete(path`/v1/chats/${chatId}`, options)\n }\n\n /**\n * Send the user's message and wait for the agent's reply. Returns only the new entries, in order: the user's\n * message, any tool use, the agent's reply.\n *\n * If the agent's model fails (`ServerError`, `errCode` `model_error`) nothing is stored and the same message\n * can be sent again. `ConflictError` with `errCode` `chat_busy` while another reply is in progress,\n * `chat_ended` after the end, `message_limit` at the cap. If the agent calls its end-call tool, the reply's\n * `chat_status` is `ended`.\n *\n * Not retried by default: a retry after an ambiguous failure could send the message twice.\n */\n sendMessage(chatId: string, content: string, options?: RequestOptions): Promise<ChatReply> {\n return this._client.post(path`/v1/chats/${chatId}/messages`, { content }, options)\n }\n\n /** End the chat. Ending twice is fine. The analysis arrives a moment later; read it with `retrieve`. */\n end(chatId: string, options?: RequestOptions): Promise<Chat> {\n return this._client.post(path`/v1/chats/${chatId}/end`, undefined, options)\n }\n\n /**\n * Analyse an ended chat again with the agent's current analysis settings and return it. `ConflictError` with\n * `errCode` `chat_in_progress` until it has ended, `no_transcript` when it has no messages.\n */\n rerunAnalysis(chatId: string, options?: RequestOptions): Promise<Chat> {\n return this._client.post(path`/v1/chats/${chatId}/rerun-analysis`, undefined, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type { Flow, FlowCreateParams, FlowDeleteResponse, FlowListParams, FlowUpdateParams } from \"../types/flow.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface FlowListEnvelope {\n flows: Flow[]\n has_more: boolean\n pagination_key: string | null\n}\n\n/**\n * Conversation flows you save once and attach to agents.\n *\n * const flow = await dialgem.flows.create({ name: \"Intake\", flow_config })\n * await dialgem.agents.create({ name: \"Front desk\", agent_type: \"flow\", flow_id: flow.id })\n *\n * A flow is checked the way an agent's `flow_config` is, so a saved flow is one that would have saved on an\n * agent. **Attaching copies it**: `agents.create` / `agents.update` with `flow_id` takes a snapshot, and editing\n * or deleting the flow afterwards changes no agent, no published version and no call.\n */\nexport class Flows extends APIResource {\n /** Validate and save a flow. `UnprocessableEntityError` (`errCode` `flow_invalid`) lists every problem. Not retried by default. */\n create(body: FlowCreateParams, options?: RequestOptions): Promise<Flow> {\n return this._client.post(\"/v1/flows\", body, options)\n }\n\n /** Flows, newest first. Await for one page, or iterate for every flow. Entries leave out `flow_config`. */\n list(params: FlowListParams = {}, options?: RequestOptions): PagePromise<Flow> {\n const fetchPage = async (paginationKey: string | null): Promise<PageData<Flow>> => {\n const res = await this._client.get<FlowListEnvelope>(\n \"/v1/flows\",\n { ...(params as Query), pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.flows, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n /** One flow with its `flow_config`. */\n retrieve(flowId: string, options?: RequestOptions): Promise<Flow> {\n return this._client.get(path`/v1/flows/${flowId}`, undefined, options)\n }\n\n /** Rename a flow and/or replace its `flow_config` (checked again). Agents it was attached to are not changed. */\n update(flowId: string, body: FlowUpdateParams, options?: RequestOptions): Promise<Flow> {\n return this._client.patch(path`/v1/flows/${flowId}`, body, options)\n }\n\n /** Delete a saved flow. Agents it was attached to keep their copy. */\n delete(flowId: string, options?: RequestOptions): Promise<FlowDeleteResponse> {\n return this._client.delete(path`/v1/flows/${flowId}`, options)\n }\n}\n","import type { Query, RequestOptions } from \"../core/http.js\"\nimport { PagePromise, type PageData } from \"../core/pagination.js\"\nimport type { LLM, LLMCreateParams, LLMDeleteResponse, LLMListParams, LLMUpdateParams } from \"../types/llm.js\"\nimport { APIResource, path } from \"./resource.js\"\n\ninterface LLMListEnvelope {\n llms: LLM[]\n has_more: boolean\n pagination_key: string | null\n}\n\n/**\n * A prompt and model you set up once and attach to agents.\n *\n * const llm = await dialgem.llms.create({ name: \"Booking\", system_prompt, llm_model: \"gpt-4o-mini\" })\n * await dialgem.agents.create({ name: \"Front desk\", llm_id: llm.id })\n *\n * It holds `system_prompt`, `first_message`, `llm_provider`, `llm_model`, `temperature`, `max_tokens`, the\n * fallback pair and `default_dynamic_variables`. **Attaching copies it**: `agents.create` / `agents.update` with\n * `llm_id` writes those values into the agent, and editing or deleting the saved LLM afterwards changes no\n * agent, no published version and no call. Sending `llm_id` together with any of those fields is refused.\n */\nexport class LLMs extends APIResource {\n /** Save LLM settings. Anything left out takes the default a new agent gets. Not retried by default. */\n create(body: LLMCreateParams, options?: RequestOptions): Promise<LLM> {\n return this._client.post(\"/v1/llms\", body, options)\n }\n\n /** Saved LLMs, newest first. Await for one page, or iterate for every one. */\n list(params: LLMListParams = {}, options?: RequestOptions): PagePromise<LLM> {\n const fetchPage = async (paginationKey: string | null): Promise<PageData<LLM>> => {\n const res = await this._client.get<LLMListEnvelope>(\n \"/v1/llms\",\n { ...(params as Query), pagination_key: paginationKey ?? undefined },\n options,\n )\n return { data: res.llms, has_more: res.has_more, pagination_key: res.pagination_key }\n }\n return new PagePromise(fetchPage)\n }\n\n retrieve(llmId: string, options?: RequestOptions): Promise<LLM> {\n return this._client.get(path`/v1/llms/${llmId}`, undefined, options)\n }\n\n /** Change the fields you send. Agents it was attached to are not changed. */\n update(llmId: string, body: LLMUpdateParams, options?: RequestOptions): Promise<LLM> {\n return this._client.patch(path`/v1/llms/${llmId}`, body, options)\n }\n\n /** Delete saved LLM settings. Agents they were attached to keep their copy. */\n delete(llmId: string, options?: RequestOptions): Promise<LLMDeleteResponse> {\n return this._client.delete(path`/v1/llms/${llmId}`, options)\n }\n}\n","import { DialgemError, WebhookVerificationError } from \"./core/errors.js\"\nimport type { FunctionCallRequest, WebhookEvent } from \"./types/webhook.js\"\n\n/** Header carrying the request signature: `v=<timestamp_ms>,d=<hex>`. */\nexport const WEBHOOK_SIGNATURE_HEADER = \"x-dialgem-signature\"\n/** Header naming the event; the same value as the body's `event`. */\nexport const WEBHOOK_EVENT_HEADER = \"x-dialgem-event\"\n/**\n * During a signing-secret rotation overlap, the same body signed with the PREVIOUS\n * secret. Verify `x-dialgem-signature` with the new secret; a receiver that has not\n * switched yet can verify this one with the old secret instead.\n */\nexport const WEBHOOK_PREVIOUS_SIGNATURE_HEADER = \"x-dialgem-signature-previous\"\n/** Header with an id that stays the same across retries of one delivery. */\nexport const WEBHOOK_DELIVERY_HEADER = \"x-dialgem-delivery\"\n\n/** Signatures older or newer than this are rejected, so a captured request cannot be replayed. */\nexport const DEFAULT_SIGNATURE_TOLERANCE_MS = 5 * 60 * 1000\n\n/** The raw request body, byte-for-byte as received. Node `Buffer` is a `Uint8Array`. */\nexport type WebhookPayload = string | Uint8Array | ArrayBuffer\n\n/** A header value as Node's `IncomingHttpHeaders`, `Headers.get()` or a framework hands it over. */\nexport type SignatureHeader = string | string[] | null | undefined\n\nexport interface VerifyOptions {\n /** Maximum age (and clock skew) of a signature, in ms. Default 5 minutes. */\n toleranceMs?: number | undefined\n /** The current time in epoch ms. For tests; defaults to `Date.now()`. */\n now?: number | undefined\n}\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\nconst SIGNATURE_RE = /^v=(\\d{10,16}),d=([0-9a-f]{64})$/\n\n/**\n * Verifies and parses what Dialgem sends to your servers: event webhooks, and\n * requests to your custom functions. Both use one signature scheme:\n *\n * x-dialgem-signature: v=<timestamp_ms>,d=<hex>\n * hex = HMAC-SHA256(secret, raw_body + timestamp_ms)\n *\n * The secret is the agent's `webhook_signing_secret`.\n *\n * **Pass the raw body.** The signature covers the exact bytes Dialgem sent. A body\n * that was parsed and re-serialized (`express.json()`, `JSON.stringify(req.body)`)\n * will not match, even when the JSON is equal. Use `express.raw({ type: \"application/json\" })`,\n * Fastify's raw body, or `await request.text()` in a route handler.\n */\nexport class Webhooks {\n /**\n * Returns whether `signature` is a current, valid signature of `payload` under\n * `secret`. Constant-time. Returns `false` for a missing, malformed, tampered or\n * stale signature; throws only if `secret` is empty, which is a configuration\n * error rather than a bad request.\n */\n async verify(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions = {},\n ): Promise<boolean> {\n if (!secret) {\n throw new DialgemError(\n \"Webhook secret is empty. Set the agent's `webhook_signing_secret` and pass the same value here.\",\n )\n }\n const match = SIGNATURE_RE.exec(firstHeader(signature)?.trim().toLowerCase() ?? \"\")\n if (!match) return false\n const [, timestamp, received] = match as unknown as [string, string, string]\n const now = options.now ?? Date.now()\n if (Math.abs(now - Number(timestamp)) > (options.toleranceMs ?? DEFAULT_SIGNATURE_TOLERANCE_MS)) {\n return false\n }\n const body = toBytes(payload)\n const message = new Uint8Array(body.length + timestamp.length)\n message.set(body, 0)\n message.set(encoder.encode(timestamp), body.length)\n const expected = await hmacSha256Hex(secret, message)\n return timingSafeEqual(expected, received)\n }\n\n /**\n * Verifies a webhook's signature, then parses its body.\n *\n * @throws WebhookVerificationError if the signature is missing, invalid or stale.\n */\n async constructEvent(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions = {},\n ): Promise<WebhookEvent> {\n const parsed = await this.#verifiedJson(payload, signature, secret, options)\n if (typeof parsed !== \"object\" || parsed === null || typeof (parsed as { event?: unknown }).event !== \"string\") {\n throw new WebhookVerificationError(\"Webhook body has no `event` field.\")\n }\n return parsed as WebhookEvent\n }\n\n /**\n * Verifies a request Dialgem made to one of your custom functions, then parses\n * its body. For functions with `args_at_root`, the body is the arguments object\n * alone; use `verify` and parse it yourself.\n *\n * @throws WebhookVerificationError if the signature is missing, invalid or stale.\n */\n async constructFunctionCall<Args = Record<string, unknown>>(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions = {},\n ): Promise<FunctionCallRequest<Args>> {\n const parsed = await this.#verifiedJson(payload, signature, secret, options)\n const body = parsed as Partial<FunctionCallRequest<Args>> | null\n if (!body || typeof body.name !== \"string\" || typeof body.call !== \"object\" || body.call === null) {\n throw new WebhookVerificationError(\n \"Function request body has no `name` and `call`. Does this function have args_at_root set?\",\n )\n }\n return body as FunctionCallRequest<Args>\n }\n\n async #verifiedJson(\n payload: WebhookPayload,\n signature: SignatureHeader,\n secret: string,\n options: VerifyOptions,\n ): Promise<unknown> {\n if (!firstHeader(signature)) {\n throw new WebhookVerificationError(\n `Missing ${WEBHOOK_SIGNATURE_HEADER} header. Is a webhook_signing_secret set on the agent?`,\n )\n }\n if (!(await this.verify(payload, signature, secret, options))) {\n throw new WebhookVerificationError(\n \"Signature is invalid or older than the allowed tolerance. Check the secret, the server clock, and that the body was not re-serialized before verification.\",\n )\n }\n const text = typeof payload === \"string\" ? payload : decoder.decode(toBytes(payload))\n try {\n return JSON.parse(text)\n } catch {\n throw new WebhookVerificationError(\"Body is signed but is not valid JSON.\")\n }\n }\n}\n\nexport const webhooks = new Webhooks()\n\nfunction firstHeader(value: SignatureHeader): string | undefined {\n const v = Array.isArray(value) ? value[0] : value\n return v ?? undefined\n}\n\nfunction toBytes(payload: WebhookPayload): Uint8Array {\n if (typeof payload === \"string\") return encoder.encode(payload)\n if (payload instanceof Uint8Array) return payload\n return new Uint8Array(payload)\n}\n\nasync function hmacSha256Hex(secret: string, data: Uint8Array): Promise<string> {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new DialgemError(\"Web Crypto (globalThis.crypto.subtle) is unavailable. Node 20 or newer is required.\")\n }\n const key = await subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"])\n // Copy into a fresh ArrayBuffer-backed view: a Node Buffer can be a slice of a\n // larger pooled ArrayBuffer, and some Web Crypto implementations reject SharedArrayBuffer views.\n const signature = await subtle.sign(\"HMAC\", key, new Uint8Array(data))\n return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\n/** Compares two equal-format hex strings without an early exit. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n","import { DialgemError } from \"./core/errors.js\"\nimport { HttpClient, assertMaxRetries, assertTimeout, type Fetch } from \"./core/http.js\"\nimport { Agents } from \"./resources/agents.js\"\nimport { Calls } from \"./resources/calls.js\"\nimport { ExtractionModels, FlowTemplates, PromptTemplates, Voices } from \"./resources/catalog.js\"\nimport { ApiKey, Sessions } from \"./resources/account.js\"\nimport { Simulations } from \"./resources/simulations.js\"\nimport { WebCalls } from \"./resources/web-calls.js\"\nimport { ContactLists, Contacts } from \"./resources/contacts.js\"\nimport { PhoneNumbers } from \"./resources/phone-numbers.js\"\nimport { Chats } from \"./resources/chats.js\"\nimport { Flows } from \"./resources/flows.js\"\nimport { LLMs } from \"./resources/llms.js\"\nimport { Webhooks, webhooks } from \"./webhooks.js\"\n\n/** The Dialgem API. Fixed: the SDK talks to Dialgem and nothing else. */\nexport const BASE_URL = \"https://api.dialgem.com\"\nconst DEFAULT_TIMEOUT_MS = 60_000\nconst DEFAULT_MAX_RETRIES = 2\n\n// Optional fields accept an explicit `undefined` so `new Dialgem({ apiKey: process.env.X })`\n// compiles under `exactOptionalPropertyTypes`; undefined means \"use the default\".\nexport interface ClientOptions {\n /** Organization API key (`zk_…`). Defaults to `process.env.DIALGEM_API_KEY`. */\n apiKey?: string | undefined\n /** Per-attempt timeout in milliseconds (> 0). Default 60000. */\n timeout?: number | undefined\n /** Retries for GET/PATCH/DELETE on 408/429/5xx and connection errors. Default 2. POST is not retried. */\n maxRetries?: number | undefined\n /** Custom fetch implementation (a proxy agent, instrumentation, tests). Defaults to the global `fetch`. */\n fetch?: Fetch | undefined\n /** Headers sent with every request. */\n defaultHeaders?: Record<string, string> | undefined\n /**\n * The API key grants full access to your organization, so constructing the\n * client in a browser throws by default. Only set this for a trusted internal tool.\n */\n dangerouslyAllowBrowser?: boolean | undefined\n}\n\n/**\n * Dialgem API client, for use from your backend.\n *\n * ```ts\n * import { Dialgem } from \"@dialgem/sdk\"\n *\n * const dialgem = new Dialgem() // reads DIALGEM_API_KEY\n * const agent = await dialgem.agents.create({ name: \"Front desk\", system_prompt: \"…\" })\n * ```\n */\nexport class Dialgem {\n static readonly BASE_URL = BASE_URL\n /** Webhook verification without a client instance: `Dialgem.webhooks.constructEvent(...)`. */\n static readonly webhooks: Webhooks = webhooks\n\n readonly agents: Agents\n readonly calls: Calls\n readonly phoneNumbers: PhoneNumbers\n readonly voices: Voices\n /** Models available for post-call analysis. */\n readonly extractionModels: ExtractionModels\n readonly flowTemplates: FlowTemplates\n readonly promptTemplates: PromptTemplates\n /** Calls in progress right now. */\n readonly sessions: Sessions\n /** Text conversations with an agent. */\n readonly chats: Chats\n readonly flows: Flows\n readonly llms: LLMs\n /** What this API key is and may do. */\n readonly apiKey: ApiKey\n /**\n * Verify what Dialgem sends you: `dialgem.webhooks.constructEvent(rawBody, signatureHeader, secret)`.\n */\n readonly webhooks: Webhooks = webhooks\n /** The organization's webhook destinations: create, update, rotate the signing secret, test. */\n /** The people you call, with CSV import under `contacts.imports`. */\n readonly contacts: Contacts\n /** Named groups of contacts. */\n readonly contactLists: ContactLists\n /** Browser calls: tokens for `@dialgem/client`, and the origins allowed to start them. */\n readonly webCalls: WebCalls\n /** Saved test conversations for an agent, run in text, with an optional publish gate. */\n readonly simulations: Simulations\n\n /** Always `https://api.dialgem.com`. */\n readonly baseURL: string = BASE_URL\n\n constructor(options: ClientOptions = {}) {\n // `baseURL` was an option in 0.1.0-beta.0. Refused rather than ignored: a\n // caller still passing a staging or local URL would otherwise have its key\n // start hitting production with no sign anything had changed.\n if (\"baseURL\" in (options as Record<string, unknown>)) {\n throw new DialgemError(\n \"`baseURL` is not an option: the SDK always talks to https://api.dialgem.com. Remove it.\",\n )\n }\n\n if (isBrowser() && !options.dangerouslyAllowBrowser) {\n throw new DialgemError(\n \"The Dialgem SDK is for server-side use: running it in a browser exposes your API key to every visitor. \" +\n \"Call Dialgem from your backend instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.\",\n )\n }\n\n const apiKey = options.apiKey ?? readEnv(\"DIALGEM_API_KEY\")\n if (!apiKey) {\n throw new DialgemError(\n \"Missing API key. Pass `apiKey` to `new Dialgem({ apiKey })` or set the DIALGEM_API_KEY environment variable.\",\n )\n }\n\n const timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n assertTimeout(timeout)\n assertMaxRetries(maxRetries)\n\n const fetchImpl = options.fetch ?? defaultFetch()\n\n const http = new HttpClient({\n apiKey,\n baseURL: BASE_URL,\n timeout,\n maxRetries,\n fetch: fetchImpl,\n defaultHeaders: options.defaultHeaders ?? {},\n })\n\n this.agents = new Agents(http)\n this.calls = new Calls(http)\n this.phoneNumbers = new PhoneNumbers(http)\n this.voices = new Voices(http)\n this.extractionModels = new ExtractionModels(http)\n this.flowTemplates = new FlowTemplates(http)\n this.promptTemplates = new PromptTemplates(http)\n this.sessions = new Sessions(http)\n this.chats = new Chats(http)\n this.flows = new Flows(http)\n this.llms = new LLMs(http)\n this.apiKey = new ApiKey(http)\n this.contacts = new Contacts(http)\n this.contactLists = new ContactLists(http)\n this.webCalls = new WebCalls(http)\n this.simulations = new Simulations(http)\n }\n}\n\nfunction readEnv(name: string): string | undefined {\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n const value = proc?.env?.[name]?.trim()\n return value ? value : undefined\n}\n\nfunction isBrowser(): boolean {\n const g = globalThis as { window?: unknown; document?: unknown }\n return typeof g.window !== \"undefined\" && typeof g.document !== \"undefined\"\n}\n\nfunction defaultFetch(): Fetch {\n const f = (globalThis as { fetch?: unknown }).fetch\n if (typeof f !== \"function\") {\n throw new DialgemError(\"No global `fetch` found. Use Node 20 or newer, or pass `fetch` in the client options.\")\n }\n // Bound per call rather than stored: some runtimes throw \"Illegal invocation\"\n // when fetch is called detached from globalThis.\n return (url, init) => (f as Fetch).call(globalThis, url, init)\n}\n"]}
|