@simple-ai-lab/sdk 0.4.0 → 0.8.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.
Files changed (78) hide show
  1. package/README.md +79 -1
  2. package/dist/actions.cjs +452 -0
  3. package/dist/actions.d.cts +348 -0
  4. package/dist/actions.d.ts +348 -0
  5. package/dist/actions.js +443 -0
  6. package/dist/agents.cjs +1176 -0
  7. package/dist/agents.d.cts +1138 -0
  8. package/dist/agents.d.ts +1138 -0
  9. package/dist/agents.js +1166 -0
  10. package/dist/built-in-actions.cjs +456 -0
  11. package/dist/built-in-actions.d.cts +53 -0
  12. package/dist/built-in-actions.d.ts +53 -0
  13. package/dist/built-in-actions.js +453 -0
  14. package/dist/client.cjs +29 -0
  15. package/dist/client.d.cts +15 -0
  16. package/dist/client.d.ts +15 -0
  17. package/dist/client.js +25 -0
  18. package/dist/code-action/defaults.cjs +11 -0
  19. package/dist/code-action/defaults.d.cts +7 -0
  20. package/dist/code-action/defaults.d.ts +7 -0
  21. package/dist/code-action/defaults.js +8 -0
  22. package/dist/code-action/define-action.cjs +78 -0
  23. package/dist/code-action/define-action.d.cts +99 -0
  24. package/dist/code-action/define-action.d.ts +99 -0
  25. package/dist/code-action/define-action.js +73 -0
  26. package/dist/code-action/index.cjs +11 -0
  27. package/dist/code-action/index.d.cts +4 -0
  28. package/dist/code-action/index.d.ts +4 -0
  29. package/dist/code-action/index.js +3 -0
  30. package/dist/code-action/llm.cjs +34 -0
  31. package/dist/code-action/llm.d.cts +28 -0
  32. package/dist/code-action/llm.d.ts +28 -0
  33. package/dist/code-action/llm.js +31 -0
  34. package/dist/code-action/types.cjs +14 -0
  35. package/dist/code-action/types.d.cts +19 -0
  36. package/dist/code-action/types.d.ts +19 -0
  37. package/dist/code-action/types.js +11 -0
  38. package/dist/code-action/workflow.cjs +29 -0
  39. package/dist/code-action/workflow.d.cts +53 -0
  40. package/dist/code-action/workflow.d.ts +53 -0
  41. package/dist/code-action/workflow.js +26 -0
  42. package/dist/data.cjs +98 -0
  43. package/dist/data.d.cts +44 -0
  44. package/dist/data.d.ts +44 -0
  45. package/dist/data.js +94 -0
  46. package/dist/http.cjs +72 -0
  47. package/dist/http.d.cts +14 -0
  48. package/dist/http.d.ts +14 -0
  49. package/dist/http.js +69 -0
  50. package/dist/index.cjs +71 -1597
  51. package/dist/index.d.cts +12 -780
  52. package/dist/index.d.ts +12 -780
  53. package/dist/index.js +10 -1311
  54. package/dist/projects.cjs +234 -0
  55. package/dist/projects.d.cts +24 -0
  56. package/dist/projects.d.ts +24 -0
  57. package/dist/projects.js +228 -0
  58. package/dist/schemas.cjs +50 -0
  59. package/dist/schemas.d.cts +81 -0
  60. package/dist/schemas.d.ts +81 -0
  61. package/dist/schemas.js +47 -0
  62. package/dist/shared/errors.cjs +31 -0
  63. package/dist/shared/errors.d.cts +22 -0
  64. package/dist/shared/errors.d.ts +22 -0
  65. package/dist/shared/errors.js +26 -0
  66. package/package.json +27 -31
  67. package/dist/chunk-V4E5PSKB.js +0 -267
  68. package/dist/chunk-V4E5PSKB.js.map +0 -1
  69. package/dist/code-action-CDt77m7I.d.cts +0 -191
  70. package/dist/code-action-CDt77m7I.d.ts +0 -191
  71. package/dist/code-action.cjs +0 -282
  72. package/dist/code-action.cjs.map +0 -1
  73. package/dist/code-action.d.cts +0 -2
  74. package/dist/code-action.d.ts +0 -2
  75. package/dist/code-action.js +0 -9
  76. package/dist/code-action.js.map +0 -1
  77. package/dist/index.cjs.map +0 -1
  78. package/dist/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/code-action.ts","../src/schemas.ts","../src/data.ts","../src/errors.ts","../src/http.ts","../src/client.ts","../src/define-action.ts"],"sourcesContent":["export {\n type ActionContext,\n type ActionHandler,\n defineAction,\n SIMPLE_ACTION_BRAND,\n} from './define-action';\n","import { z } from 'zod';\n\n/**\n * Request wire schemas for the Simple AI public REST API (`/api/v1`).\n *\n * These deliberately mirror the server's own schemas (see\n * `projects/server-v2/src/domains/data/query-schemas.ts` and\n * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two\n * in sync. Responses are typed but not strictly validated, so additive server\n * changes never break deployed SDK consumers.\n */\n\n/** Hard cap on hits a single query may return. */\nexport const MAX_QUERY_SIZE = 50;\n/** Maximum rows accepted by a single batch-upsert chunk. */\nexport const MAX_BATCH_ROWS = 1000;\n\nexport const tableNameSchema = z.string().regex(/^[a-z0-9_]+$/, 'Table names are lowercase snake_case identifiers');\n\nexport const filterValueSchema = z.union([z.string(), z.number(), z.boolean()]);\n\n// Mirrors the server's customDataFacetAttributePathSchema: dot-separated\n// column paths with no empty segments (OBJECT leaves are parent.child).\nexport const dataColumnPathSchema = z\n .string()\n .trim()\n .min(1)\n .max(1024)\n .refine((path) => path.split('.').every((segment) => segment.length > 0), {\n message: 'Must be a dot-separated column path with no empty segments',\n });\n\nexport const dataFilterSchema = z.object({\n column: dataColumnPathSchema,\n values: z.array(filterValueSchema),\n});\nexport type DataFilter = z.infer<typeof dataFilterSchema>;\n\nexport const queryInputSchema = z.object({\n tableName: tableNameSchema,\n filters: z.array(dataFilterSchema).optional(),\n text: z.string().max(5000).optional(),\n size: z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),\n from: z.number().int().min(0).optional(),\n});\nexport type QueryInput = z.input<typeof queryInputSchema>;\n\nexport const listOptionsSchema = z.object({\n page: z.number().int().min(1).optional(),\n perPage: z.number().int().min(1).max(200).optional(),\n orderBy: z.string().optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n /** Column-name → value equality filters applied server-side. */\n filters: z.record(z.string(), z.string()).optional(),\n});\nexport type ListOptions = z.input<typeof listOptionsSchema>;\n\nexport const recordPayloadSchema = z.record(z.string(), z.unknown());\nexport type RecordPayload = z.infer<typeof recordPayloadSchema>;\n\nexport const batchUpsertRowsSchema = z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);\n\n// ---------------------------------------------------------------------------\n// Response types (typed, tolerantly parsed)\n// ---------------------------------------------------------------------------\n\nexport type DataRecord = Record<string, unknown>;\n\nexport type QueryResult = {\n records: DataRecord[];\n total: number;\n};\n\nexport type ListResult = {\n records: DataRecord[];\n total_count: number;\n page: number;\n per_page: number;\n};\n\nexport type RecordResult = {\n record: DataRecord;\n};\n\nexport type DeleteResult = {\n success: boolean;\n message: string;\n};\n\nexport type BatchUpsertResult = {\n ingestBatchId: string;\n status: string;\n};\n\nexport type IngestBatchStatus = {\n id: string;\n tableName: string;\n status: string;\n rowCount: number;\n upsertedCount: number | null;\n errorMessage: string | null;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n};\n\nexport type FacetsResult = Record<string, unknown>;\n","import type { HttpClient } from './http';\nimport {\n type BatchUpsertResult,\n batchUpsertRowsSchema,\n type DataRecord,\n type DeleteResult,\n type FacetsResult,\n type IngestBatchStatus,\n type ListOptions,\n type ListResult,\n listOptionsSchema,\n type QueryInput,\n queryInputSchema,\n type RecordPayload,\n type RecordResult,\n recordPayloadSchema,\n tableNameSchema,\n} from './schemas';\n\nfunction encodeTable(tableName: string): string {\n return encodeURIComponent(tableNameSchema.parse(tableName));\n}\n\n/**\n * Custom data tables — query, read, and write your organization's records.\n * Wraps the `/api/v1/data` REST endpoints.\n */\nexport class DataClient {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */\n async query<TRecord extends DataRecord = DataRecord>(\n input: QueryInput\n ): Promise<{ records: TRecord[]; total: number }> {\n const parsed = queryInputSchema.parse(input);\n const result = await this.#http.request({ method: 'POST', path: '/data/query', body: parsed });\n return result as { records: TRecord[]; total: number };\n }\n\n /** Facet values for an indexed table. */\n async facets(tableName: string): Promise<FacetsResult> {\n const result = await this.#http.request({ method: 'GET', path: `/data/facets/${encodeTable(tableName)}` });\n return result as FacetsResult;\n }\n\n /** Paginated listing straight from the relational store. */\n async list<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n options: ListOptions = {}\n ): Promise<{ records: TRecord[]; total_count: number; page: number; per_page: number }> {\n const parsed = listOptionsSchema.parse(options);\n const query: Record<string, string> = { ...(parsed.filters ?? {}) };\n if (parsed.page !== undefined) {\n query.page = String(parsed.page);\n }\n if (parsed.perPage !== undefined) {\n query.per_page = String(parsed.perPage);\n }\n if (parsed.orderBy !== undefined) {\n query.order_by = parsed.orderBy;\n }\n if (parsed.orderDirection !== undefined) {\n query.order_direction = parsed.orderDirection;\n }\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}`, query });\n return result as ListResult & { records: TRecord[] };\n }\n\n async get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{ record: TRecord }> {\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as RecordResult & { record: TRecord };\n }\n\n async create<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async update<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n id: number,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PATCH',\n path: `/data/${encodeTable(tableName)}/${id}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async delete(tableName: string, id: number): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as DeleteResult;\n }\n\n /** Deletes every record in the table. Irreversible. */\n async deleteAll(tableName: string): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}` });\n return result as DeleteResult;\n }\n\n /**\n * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW\n * REPLACE on key conflict — omitted columns are cleared, not preserved.\n * Returns a batch handle; poll `getBatch` for completion.\n */\n async batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}/batch`,\n body: { rows: batchUpsertRowsSchema.parse(rows) },\n });\n return result as BatchUpsertResult;\n }\n\n /** Status of an async upsert batch created by `batchUpsert`. */\n async getBatch(ingestBatchId: string): Promise<IngestBatchStatus> {\n const result = await this.#http.request({\n method: 'GET',\n path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`,\n });\n return result as IngestBatchStatus;\n }\n}\n","/** Error thrown for any non-2xx response from the Simple AI API. */\nexport class SimpleAIError extends Error {\n /** HTTP status code, or 0 when the request never reached the API. */\n readonly status: number;\n /** Machine-readable error code from the API body, when present. */\n readonly code: string | null;\n /** The parsed response body (JSON when possible, otherwise raw text). */\n readonly body: unknown;\n\n constructor({\n message,\n status,\n code,\n body,\n cause,\n }: {\n message: string;\n status: number;\n code: string | null;\n body: unknown;\n cause?: unknown;\n }) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'SimpleAIError';\n this.status = status;\n this.code = code;\n this.body = body;\n }\n}\n","import { SimpleAIError } from './errors';\n\nexport type FetchLike = (url: string, init: RequestInit) => Promise<Response>;\n\nexport type HttpClient = {\n request: (args: {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, string>;\n body?: unknown;\n }) => Promise<unknown>;\n};\n\nfunction parseBody(text: string): unknown {\n if (text.length === 0) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorDetails(body: unknown): { code: string | null; message: string | null } {\n if (body !== null && typeof body === 'object') {\n const record = body as { code?: unknown; error?: unknown; message?: unknown };\n const code = typeof record.code === 'string' ? record.code : null;\n const message =\n typeof record.message === 'string' ? record.message : typeof record.error === 'string' ? record.error : null;\n return { code, message };\n }\n return { code: null, message: typeof body === 'string' && body.length > 0 ? body : null };\n}\n\nexport function createHttpClient({\n baseUrl,\n apiKey,\n fetchImplementation,\n}: {\n baseUrl: string;\n apiKey: string;\n fetchImplementation: FetchLike;\n}): HttpClient {\n const normalizedBase = baseUrl.replace(/\\/+$/, '');\n\n return {\n request: async ({ method, path, query, body }) => {\n const queryString =\n query === undefined || Object.keys(query).length === 0 ? '' : `?${new URLSearchParams(query).toString()}`;\n const url = `${normalizedBase}${path}${queryString}`;\n\n let response: Response;\n try {\n response = await fetchImplementation(url, {\n method,\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json',\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n } catch (e) {\n throw new SimpleAIError({\n message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,\n status: 0,\n code: 'network_error',\n body: null,\n cause: e,\n });\n }\n\n const parsed = parseBody(await response.text());\n if (!response.ok) {\n const { code, message } = errorDetails(parsed);\n throw new SimpleAIError({\n message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,\n status: response.status,\n code,\n body: parsed,\n });\n }\n return parsed;\n },\n };\n}\n","import { DataClient } from './data';\nimport type { FetchLike } from './http';\nimport { createHttpClient } from './http';\n\nconst DEFAULT_BASE_URL = 'https://api.prod.usesimple.ai/api/v1';\n\nexport type SimpleAIOptions = {\n /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */\n apiKey?: string;\n /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */\n baseUrl?: string;\n /** Custom fetch implementation (for testing or instrumentation). */\n fetch?: FetchLike;\n};\n\nfunction envVar(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) {\n return undefined;\n }\n const value = process.env[name];\n return value === undefined || value === '' ? undefined : value;\n}\n\nexport class SimpleAI {\n /** Custom data tables — query, read, and write records. */\n readonly data: DataClient;\n\n constructor(options: SimpleAIOptions = {}) {\n const apiKey = options.apiKey ?? envVar('SIMPLE_API_KEY');\n if (apiKey === undefined) {\n throw new Error(\n 'Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. ' +\n 'Inside Simple AI code actions the key is injected automatically.'\n );\n }\n const baseUrl = options.baseUrl ?? envVar('SIMPLE_BASE_URL') ?? DEFAULT_BASE_URL;\n const fetchImplementation: FetchLike = options.fetch ?? ((url, init) => fetch(url, init));\n\n const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });\n this.data = new DataClient(http);\n }\n}\n","import { SimpleAI } from './client';\n\n/**\n * Brand the code-action runner uses to recognize `defineAction` handlers. The\n * runner calls the default export with `{ inputs, config }` either way; the\n * wrapper adds the authenticated `client` to the handler's context.\n */\nexport const SIMPLE_ACTION_BRAND = Symbol.for('simple-ai.action');\nconst SIMPLE_ACTION_RUNTIME = Symbol.for('simple-ai.action-runtime');\n\ntype ActionRuntime = {\n apiKey: string;\n baseUrl: string;\n};\n\nexport type ActionContext<TInputs = Record<string, unknown>> = {\n /** The Action's declared inputs, already validated against its input schema. */\n inputs: TInputs;\n /** Your organization's configuration variables. */\n config: Record<string, string>;\n /** The Simple AI SDK, authenticated for your organization. */\n client: SimpleAI;\n};\n\nexport type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {\n inputs: TInputs;\n config: Record<string, string>;\n [SIMPLE_ACTION_RUNTIME]?: ActionRuntime;\n}) => Promise<TResult>) & { [SIMPLE_ACTION_BRAND]: true };\n\n/**\n * Define a code action with a typed context and an org-authenticated SDK\n * client. The returned value must be your module's default export.\n *\n * ```ts\n * import { defineAction } from '@simple-ai-lab/sdk';\n *\n * export default defineAction(async ({ inputs, config, client }) => {\n * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });\n * return { found: records.length > 0 };\n * });\n * ```\n */\nexport function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(\n handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult\n): ActionHandler<TInputs, TResult> {\n const wrapped = async (invocation: {\n inputs: TInputs;\n config: Record<string, string>;\n [SIMPLE_ACTION_RUNTIME]?: ActionRuntime;\n }): Promise<TResult> => {\n const { inputs, config } = invocation;\n const runtime = invocation[SIMPLE_ACTION_RUNTIME];\n // The Dynamic Worker runner supplies a non-secret API identity. The\n // outbound Worker injects the real short-lived credential after the\n // request has crossed the untrusted isolate boundary.\n const client = runtime === undefined ? new SimpleAI() : new SimpleAI(runtime);\n return handler({ inputs, config, client });\n };\n const brand: { [SIMPLE_ACTION_BRAND]: true } = { [SIMPLE_ACTION_BRAND]: true };\n return Object.assign(wrapped, brand);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAaX,IAAM,iBAAiB;AAEvB,IAAM,iBAAiB;AAEvB,IAAM,kBAAkB,aAAE,OAAO,EAAE,MAAM,gBAAgB,kDAAkD;AAE3G,IAAM,oBAAoB,aAAE,MAAM,CAAC,aAAE,OAAO,GAAG,aAAE,OAAO,GAAG,aAAE,QAAQ,CAAC,CAAC;AAIvE,IAAM,uBAAuB,aACjC,OAAO,EACP,KAAK,EACL,IAAI,CAAC,EACL,IAAI,IAAI,EACR,OAAO,CAAC,SAAS,KAAK,MAAM,GAAG,EAAE,MAAM,CAAC,YAAY,QAAQ,SAAS,CAAC,GAAG;AAAA,EACxE,SAAS;AACX,CAAC;AAEI,IAAM,mBAAmB,aAAE,OAAO;AAAA,EACvC,QAAQ;AAAA,EACR,QAAQ,aAAE,MAAM,iBAAiB;AACnC,CAAC;AAGM,IAAM,mBAAmB,aAAE,OAAO;AAAA,EACvC,WAAW;AAAA,EACX,SAAS,aAAE,MAAM,gBAAgB,EAAE,SAAS;AAAA,EAC5C,MAAM,aAAE,OAAO,EAAE,IAAI,GAAI,EAAE,SAAS;AAAA,EACpC,MAAM,aAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,cAAc,EAAE,SAAS;AAAA,EAC3D,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E,WAAO,QAAQ,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAAA,EAC3C;AACA,QAAM,QAAyC,EAAE,CAAC,mBAAmB,GAAG,KAAK;AAC7E,SAAO,OAAO,OAAO,SAAS,KAAK;AACrC;","names":[]}
@@ -1,2 +0,0 @@
1
- export { A as ActionContext, a as ActionHandler, S as SIMPLE_ACTION_BRAND, n as defineAction } from './code-action-CDt77m7I.cjs';
2
- import 'zod';
@@ -1,2 +0,0 @@
1
- export { A as ActionContext, a as ActionHandler, S as SIMPLE_ACTION_BRAND, n as defineAction } from './code-action-CDt77m7I.js';
2
- import 'zod';
@@ -1,9 +0,0 @@
1
- import {
2
- SIMPLE_ACTION_BRAND,
3
- defineAction
4
- } from "./chunk-V4E5PSKB.js";
5
- export {
6
- SIMPLE_ACTION_BRAND,
7
- defineAction
8
- };
9
- //# sourceMappingURL=code-action.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/actions.ts","../src/agents.ts","../src/schemas.ts","../src/data.ts","../src/errors.ts","../src/http.ts","../src/client.ts","../src/define-action.ts","../src/projects.ts"],"sourcesContent":["export {\n type ActionCompileOptions,\n type ActionDefinition,\n type ActionOutputParameters,\n type ActionRunDefinition,\n type ActionsIoSchema,\n type ActionsIoSchemaNode,\n type ActionVersionValues,\n type AgentActionInput,\n action,\n actionsIoSchemaFromZod,\n type CallableActionDefinition,\n compileAction,\n type InlineActionDefinition,\n type ReferencedActionDefinition,\n type SourceFileReference,\n sourceFile,\n} from './actions';\nexport {\n type AbTestNodeDefinition,\n type ActionNodeDefinition,\n type AgentCompileOptions,\n type AgentDefinition,\n type AgentDefinitionInput,\n type AgentIdentityKind,\n type AgentV2CommitContentWire,\n type AgentV2ConfigWire,\n type AgentV2EdgeWire,\n type AgentV2NodeWire,\n type BackgroundNoise,\n type CompiledAgentProject,\n canonicalAuthoringKey,\n canonicalAuthoringKeys,\n compileAgent,\n defineAgent,\n type EdgeDefinition,\n type EnabledWithDescription,\n type EndCallNodeDefinition,\n type ExtractionField,\n type ExtractNodeDefinition,\n type GlobalNodeDefinition,\n type HttpNodeDefinition,\n type InterruptionMode,\n type NodeDefinition,\n node,\n type PromptNodeDefinition,\n type PromptReference,\n prompt,\n type RemoteReference,\n type RouteNodeDefinition,\n reference,\n type SayNodeDefinition,\n type ToolUseSiteWire,\n type TransferCapability,\n type TransferChatNodeDefinition,\n type TransferNodeDefinition,\n} from './agents';\nexport { SimpleAI, type SimpleAIOptions } from './client';\nexport { DataClient } from './data';\nexport {\n type ActionContext,\n type ActionHandler,\n defineAction,\n SIMPLE_ACTION_BRAND,\n} from './define-action';\nexport { SimpleAIError } from './errors';\nexport {\n type AgentProjectSource,\n type AgentSnapshotDefinition,\n collectActionVersionUuids,\n compileAgentProject,\n defineAgentSnapshot,\n type SnapshotAction,\n} from './projects';\nexport type {\n BatchUpsertResult,\n DataFilter,\n DataRecord,\n DeleteResult,\n FacetsResult,\n IngestBatchStatus,\n ListOptions,\n ListResult,\n QueryInput,\n QueryResult,\n RecordPayload,\n RecordResult,\n} from './schemas';\nexport {\n batchUpsertRowsSchema,\n dataColumnPathSchema,\n dataFilterSchema,\n listOptionsSchema,\n MAX_BATCH_ROWS,\n MAX_QUERY_SIZE,\n queryInputSchema,\n recordPayloadSchema,\n tableNameSchema,\n} from './schemas';\n","import { z } from 'zod';\n\nexport type ActionsIoScalarType = 'string' | 'number' | 'boolean';\n\nexport type ActionsIoSchemaNode =\n | {\n type: ActionsIoScalarType;\n description: string;\n nullable: boolean;\n }\n | {\n type: 'object';\n description: string;\n nullable: boolean;\n properties: Record<string, ActionsIoSchemaNode>;\n required: string[];\n additionalProperties: boolean;\n }\n | {\n type: 'array';\n description: string;\n nullable: boolean;\n items?: ActionsIoSchemaNode;\n };\n\nexport type ActionsIoSchema = {\n type: 'object';\n description: string;\n properties: Record<string, ActionsIoSchemaNode>;\n required: string[];\n additionalProperties: boolean;\n};\n\nexport type HttpActionValues = {\n actionType: 'http';\n name: string;\n description: string;\n inputSchema: ActionsIoSchema;\n outputSchema: ActionsIoSchema;\n outputMappings: Record<string, string>;\n operation: {\n type: 'request';\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n urlTemplate: string;\n headers: { name: string; valueTemplate: string }[];\n bodyTemplate: string | null;\n };\n};\n\nexport type CodeActionValues = {\n actionType: 'code';\n name: string;\n description: string;\n inputSchema: ActionsIoSchema;\n outputSchema: ActionsIoSchema;\n outputMappings: Record<string, string>;\n operation: {\n type: 'execute';\n language: 'typescript';\n source: string;\n compiledJs: string | null;\n runtime: 'cloudflare-worker';\n timeoutMs: number;\n };\n};\n\nexport type CustomDataActionValues = {\n actionType: 'custom_data';\n name: string;\n description: string;\n inputSchema: ActionsIoSchema;\n outputSchema: ActionsIoSchema;\n outputMappings: Record<string, string>;\n operation: { type: 'query'; sql: string } | { type: 'search'; table: string; bodyTemplate: string };\n};\n\nexport type KnowledgeBaseActionValues = {\n actionType: 'knowledge_base';\n name: string;\n description: string;\n inputSchema: ActionsIoSchema;\n outputSchema: ActionsIoSchema;\n outputMappings: Record<string, string>;\n operation: {\n type: 'search';\n knowledgeBaseIds: string[];\n bodyTemplate: string;\n };\n};\n\nexport type ActionVersionValues =\n | HttpActionValues\n | CodeActionValues\n | CustomDataActionValues\n | KnowledgeBaseActionValues;\n\ntype ActionContract = {\n inputSchema: ActionsIoSchema;\n outputSchema: ActionsIoSchema;\n};\n\nexport type InlineActionDefinition = {\n kind: 'inline';\n key: string;\n contract: ActionContract;\n compile: (options: ActionCompileOptions) => ActionVersionValues;\n};\n\nexport type ReferencedActionDefinition = {\n kind: 'reference';\n key: string;\n versionUuid: string;\n contract: ActionContract | null;\n};\n\nexport type ActionDefinition = InlineActionDefinition | ReferencedActionDefinition;\n\nexport type AgentActionInput = { source: 'agent'; description: string } | { source: 'template'; value: string };\n\n/** Maps each Action output name to the Agent parameter that should receive its value. */\nexport type ActionOutputParameters = Record<string, string>;\n\nexport type CallableActionDefinition = {\n kind: 'callable';\n key: string;\n action: ActionDefinition;\n name: string;\n description: string;\n inputs: Record<string, AgentActionInput>;\n outputParameters: ActionOutputParameters;\n};\n\nexport type ActionRunDefinition = {\n kind: 'run';\n key: string;\n action: ActionDefinition;\n inputs: Record<string, string>;\n outputParameters: ActionOutputParameters;\n};\n\nexport type SourceFileReference = {\n kind: 'source-file';\n path: string;\n};\n\ntype SchemaPair<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape> = {\n input: z.ZodObject<TInputShape>;\n output: z.ZodObject<TOutputShape>;\n};\n\ntype CommonActionConfig<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape> = {\n key: string;\n name: string;\n description: string;\n input: z.ZodObject<TInputShape>;\n output: z.ZodObject<TOutputShape>;\n outputMappings: Record<string, string>;\n};\n\ntype HttpActionConfig<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape> = CommonActionConfig<\n TInputShape,\n TOutputShape\n> & {\n request: {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n url: string;\n headers?: Record<string, string>;\n body?: string | null;\n };\n};\n\ntype CodeActionConfig<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape> = CommonActionConfig<\n TInputShape,\n TOutputShape\n> & {\n source: string | SourceFileReference;\n timeoutMs?: number;\n};\n\ntype CustomDataQueryActionConfig<\n TInputShape extends z.ZodRawShape,\n TOutputShape extends z.ZodRawShape,\n> = CommonActionConfig<TInputShape, TOutputShape> & {\n sql: string;\n};\n\ntype CustomDataSearchActionConfig<\n TInputShape extends z.ZodRawShape,\n TOutputShape extends z.ZodRawShape,\n> = CommonActionConfig<TInputShape, TOutputShape> & {\n table: string;\n body: string;\n};\n\ntype KnowledgeBaseSearchActionConfig<\n TInputShape extends z.ZodRawShape,\n TOutputShape extends z.ZodRawShape,\n> = CommonActionConfig<TInputShape, TOutputShape> & {\n knowledgeBaseIds: string[];\n body: string;\n};\n\nexport type ActionCompileOptions = {\n readSourceFile?: (path: string) => string;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction nullableJsonSchema(value: Record<string, unknown>): {\n schema: Record<string, unknown>;\n nullable: boolean;\n} {\n const type = value.type;\n if (Array.isArray(type)) {\n const nonNullTypes = type.filter((item) => item !== 'null');\n if (nonNullTypes.length === 1 && typeof nonNullTypes[0] === 'string') {\n return { schema: { ...value, type: nonNullTypes[0] }, nullable: type.includes('null') };\n }\n }\n\n const anyOf = value.anyOf;\n if (Array.isArray(anyOf)) {\n const schemas = anyOf.filter(isRecord);\n const nonNullSchemas = schemas.filter((schema) => schema.type !== 'null');\n const containsNull = schemas.some((schema) => schema.type === 'null');\n if (containsNull && nonNullSchemas.length === 1) {\n const nonNullSchema = nonNullSchemas[0] ?? {};\n return {\n schema: {\n ...nonNullSchema,\n ...(typeof value.description === 'string' ? { description: value.description } : {}),\n },\n nullable: true,\n };\n }\n }\n\n return { schema: value, nullable: false };\n}\n\nfunction schemaDescription(schema: Record<string, unknown>): string {\n return typeof schema.description === 'string' ? schema.description : '';\n}\n\nfunction convertJsonSchemaNode(value: unknown, path: string): ActionsIoSchemaNode {\n if (!isRecord(value)) {\n throw new Error(`${path} is not a representable Zod schema`);\n }\n\n const { schema, nullable } = nullableJsonSchema(value);\n if (schema.enum !== undefined || schema.const !== undefined) {\n throw new Error(`${path} uses enum/const, which Actions I/O schemas do not support`);\n }\n\n switch (schema.type) {\n case 'string':\n case 'number':\n case 'boolean':\n return {\n type: schema.type,\n description: schemaDescription(schema),\n nullable,\n };\n case 'object': {\n const rawProperties = isRecord(schema.properties) ? schema.properties : {};\n const properties: Record<string, ActionsIoSchemaNode> = {};\n for (const [name, child] of Object.entries(rawProperties)) {\n if (!/^[A-Za-z_]\\w*$/.test(name) || ['__proto__', 'constructor', 'prototype'].includes(name)) {\n throw new Error(`${path}.${name} is not a valid Actions I/O property name`);\n }\n properties[name] = convertJsonSchemaNode(child, `${path}.${name}`);\n }\n const required = Array.isArray(schema.required)\n ? schema.required.filter((name): name is string => typeof name === 'string')\n : [];\n const additionalProperties = schema.additionalProperties === true;\n return {\n type: 'object',\n description: schemaDescription(schema),\n nullable,\n properties,\n required,\n additionalProperties,\n };\n }\n case 'array':\n return {\n type: 'array',\n description: schemaDescription(schema),\n nullable,\n ...(schema.items === undefined ? {} : { items: convertJsonSchemaNode(schema.items, `${path}[]`) }),\n };\n case 'integer':\n return {\n type: 'number',\n description: schemaDescription(schema),\n nullable,\n };\n default:\n throw new Error(`${path} uses unsupported Zod/JSON Schema type \"${String(schema.type)}\"`);\n }\n}\n\nexport function actionsIoSchemaFromZod<TShape extends z.ZodRawShape>(schema: z.ZodObject<TShape>): ActionsIoSchema {\n const converted = convertJsonSchemaNode(z.toJSONSchema(schema), 'schema');\n if (converted.type !== 'object') {\n throw new Error('Action input and output schemas must be Zod objects');\n }\n return {\n type: 'object',\n description: converted.description,\n properties: converted.properties,\n required: converted.required,\n additionalProperties: converted.additionalProperties,\n };\n}\n\nfunction pointerForName(name: string): string {\n const escaped = name.replace(/~/g, '~0').replace(/\\//g, '~1');\n return `/${escaped}`;\n}\n\nfunction normalizeOutputMappings({\n mappings,\n outputSchema,\n}: {\n mappings: Record<string, string>;\n outputSchema: ActionsIoSchema;\n}): Record<string, string> {\n const normalized = Object.fromEntries(\n Object.entries(mappings).map(([name, template]) => [name.startsWith('/') ? name : pointerForName(name), template])\n );\n for (const name of Object.keys(outputSchema.properties)) {\n const pointer = pointerForName(name);\n if (normalized[pointer] === undefined) {\n throw new Error(`Action output \"${name}\" needs an output mapping`);\n }\n }\n for (const pointer of Object.keys(normalized)) {\n const firstToken = pointer.slice(1).split('/')[0]?.replace(/~1/g, '/').replace(/~0/g, '~');\n if (firstToken === undefined || outputSchema.properties[firstToken] === undefined) {\n throw new Error(`Action output mapping \"${pointer}\" does not reference a declared output`);\n }\n }\n return normalized;\n}\n\nfunction compileContracts<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>({\n input,\n output,\n}: SchemaPair<TInputShape, TOutputShape>): ActionContract {\n return {\n inputSchema: actionsIoSchemaFromZod(input),\n outputSchema: actionsIoSchemaFromZod(output),\n };\n}\n\nfunction requireSourceFile({\n reference,\n options,\n}: {\n reference: SourceFileReference;\n options: ActionCompileOptions;\n}): string {\n if (options.readSourceFile === undefined) {\n throw new Error(`Action source file \"${reference.path}\" requires a readSourceFile compiler option`);\n }\n return options.readSourceFile(reference.path);\n}\n\nfunction compileHttpAction<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: HttpActionConfig<TInputShape, TOutputShape>\n): InlineActionDefinition {\n const contract = compileContracts(config);\n return {\n kind: 'inline',\n key: config.key,\n contract,\n compile: () => ({\n actionType: 'http',\n name: config.name,\n description: config.description,\n ...contract,\n outputMappings: normalizeOutputMappings({\n mappings: config.outputMappings,\n outputSchema: contract.outputSchema,\n }),\n operation: {\n type: 'request',\n method: config.request.method,\n urlTemplate: config.request.url,\n headers: Object.entries(config.request.headers ?? {}).map(([name, valueTemplate]) => ({\n name,\n valueTemplate,\n })),\n bodyTemplate: config.request.body ?? null,\n },\n }),\n };\n}\n\nfunction compileCodeAction<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: CodeActionConfig<TInputShape, TOutputShape>\n): InlineActionDefinition {\n const contract = compileContracts(config);\n return {\n kind: 'inline',\n key: config.key,\n contract,\n compile: (options) => ({\n actionType: 'code',\n name: config.name,\n description: config.description,\n ...contract,\n outputMappings: normalizeOutputMappings({\n mappings: config.outputMappings,\n outputSchema: contract.outputSchema,\n }),\n operation: {\n type: 'execute',\n language: 'typescript',\n source:\n typeof config.source === 'string' ? config.source : requireSourceFile({ reference: config.source, options }),\n compiledJs: null,\n runtime: 'cloudflare-worker',\n timeoutMs: config.timeoutMs ?? 30_000,\n },\n }),\n };\n}\n\nfunction compileCustomDataQueryAction<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: CustomDataQueryActionConfig<TInputShape, TOutputShape>\n): InlineActionDefinition {\n const contract = compileContracts(config);\n return {\n kind: 'inline',\n key: config.key,\n contract,\n compile: () => ({\n actionType: 'custom_data',\n name: config.name,\n description: config.description,\n ...contract,\n outputMappings: normalizeOutputMappings({\n mappings: config.outputMappings,\n outputSchema: contract.outputSchema,\n }),\n operation: { type: 'query', sql: config.sql },\n }),\n };\n}\n\nfunction compileCustomDataSearchAction<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: CustomDataSearchActionConfig<TInputShape, TOutputShape>\n): InlineActionDefinition {\n const contract = compileContracts(config);\n return {\n kind: 'inline',\n key: config.key,\n contract,\n compile: () => ({\n actionType: 'custom_data',\n name: config.name,\n description: config.description,\n ...contract,\n outputMappings: normalizeOutputMappings({\n mappings: config.outputMappings,\n outputSchema: contract.outputSchema,\n }),\n operation: { type: 'search', table: config.table, bodyTemplate: config.body },\n }),\n };\n}\n\nfunction compileKnowledgeBaseSearchAction<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: KnowledgeBaseSearchActionConfig<TInputShape, TOutputShape>\n): InlineActionDefinition {\n const contract = compileContracts(config);\n return {\n kind: 'inline',\n key: config.key,\n contract,\n compile: () => ({\n actionType: 'knowledge_base',\n name: config.name,\n description: config.description,\n ...contract,\n outputMappings: normalizeOutputMappings({\n mappings: config.outputMappings,\n outputSchema: contract.outputSchema,\n }),\n operation: {\n type: 'search',\n knowledgeBaseIds: config.knowledgeBaseIds,\n bodyTemplate: config.body,\n },\n }),\n };\n}\n\nexport const action = {\n http<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: HttpActionConfig<TInputShape, TOutputShape>\n ): InlineActionDefinition {\n return compileHttpAction(config);\n },\n\n code<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: CodeActionConfig<TInputShape, TOutputShape>\n ): InlineActionDefinition {\n return compileCodeAction(config);\n },\n\n customDataQuery<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: CustomDataQueryActionConfig<TInputShape, TOutputShape>\n ): InlineActionDefinition {\n return compileCustomDataQueryAction(config);\n },\n\n customDataSearch<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: CustomDataSearchActionConfig<TInputShape, TOutputShape>\n ): InlineActionDefinition {\n return compileCustomDataSearchAction(config);\n },\n\n knowledgeBaseSearch<TInputShape extends z.ZodRawShape, TOutputShape extends z.ZodRawShape>(\n config: KnowledgeBaseSearchActionConfig<TInputShape, TOutputShape>\n ): InlineActionDefinition {\n return compileKnowledgeBaseSearchAction(config);\n },\n\n ref(config: { key: string; versionUuid: string; contract?: ActionContract }): ReferencedActionDefinition {\n return {\n kind: 'reference',\n key: config.key,\n versionUuid: config.versionUuid,\n contract: config.contract ?? null,\n };\n },\n\n callable(config: Omit<CallableActionDefinition, 'kind'>): CallableActionDefinition {\n return { kind: 'callable', ...config };\n },\n\n run(config: Omit<ActionRunDefinition, 'kind'>): ActionRunDefinition {\n return { kind: 'run', ...config };\n },\n\n fromAgent(description: string): AgentActionInput {\n return { source: 'agent', description };\n },\n\n from(value: string): AgentActionInput {\n return { source: 'template', value };\n },\n};\n\nexport function compileAction(\n definition: InlineActionDefinition,\n options: ActionCompileOptions = {}\n): ActionVersionValues {\n return definition.compile(options);\n}\n\nexport function sourceFile(path: string): SourceFileReference {\n return { kind: 'source-file', path };\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport type {\n ActionDefinition,\n ActionOutputParameters,\n ActionRunDefinition,\n ActionVersionValues,\n CallableActionDefinition,\n InlineActionDefinition,\n} from './actions';\nimport { compileAction } from './actions';\n\nexport type BackgroundNoise =\n | 'office'\n | 'coffee_shop'\n | 'driving'\n | 'restaurant'\n | 'street'\n | 'airport'\n | 'shopping_mall'\n | 'park'\n | 'off';\n\nexport type InterruptionMode = 'harder' | 'medium' | 'easier' | 'always';\n\nexport type RemoteReference = {\n uuid: string;\n};\n\nexport type PromptReference =\n | { kind: 'inline'; text: string | null; example: string | null; generatedExamples?: unknown }\n | { kind: 'file'; path: string; example: string | null }\n | { kind: 'version'; versionId: string };\n\nexport type ExtractionField = {\n name: string;\n type: string;\n description: string;\n required: boolean;\n enum?: (string | number | boolean)[];\n items?: ExtractionField;\n properties?: ExtractionField[];\n};\n\nexport type AgentV2EdgeWire = {\n uuid: string;\n toNodeUuid: string;\n description: string;\n priority: number;\n condition: {\n variable: string;\n operator: string;\n value: string;\n } | null;\n};\n\nexport type EnabledWithDescription = {\n enabled: boolean;\n description: string | null;\n};\n\nexport type TransferCapability = {\n enabled: boolean;\n phoneNumber: string | null;\n timeout: number;\n mode: 'cold' | 'warm';\n description: string | null;\n voicemailMessage: string | null;\n};\n\ntype NodeBuiltInCapabilities = {\n alwaysAvailable?: EnabledWithDescription;\n transfer?: TransferCapability;\n};\n\ntype PromptWire =\n | {\n type: 'inline';\n prompt: string | null;\n example: string | null;\n generatedExamples?: unknown;\n }\n | {\n type: 'reference';\n promptVersionId: string;\n };\n\ntype ActionUseSiteWire = {\n actionUseSiteUuid: string;\n actionVersionUuid: string;\n inputMappings: Record<string, string>;\n outputParameterMappings: Record<string, string>;\n};\n\nexport type ToolUseSiteWire = ActionUseSiteWire & {\n name: string;\n description: string;\n inputDescriptions: Record<string, string>;\n};\n\nexport type AgentV2ConfigWire = {\n voice: {\n voiceUuid: string | null;\n backgroundNoise: BackgroundNoise;\n };\n llm: {\n model: string;\n llmModelUuid: string | null;\n temperature: number;\n };\n speech: {\n language: string;\n keyterms: string[];\n };\n call: {\n agentSpeaksFirst: boolean;\n firstSentence: string | null;\n maxCallLengthSeconds: number;\n record: boolean;\n checkInAfterSilence: {\n enabled: boolean;\n prompt: string | null;\n };\n endCallAfterExtendedSilence: boolean;\n pciEnabled: boolean;\n backgroundNoise?: {\n trackName: string;\n gainMultiplier?: number;\n };\n interruptionConfig?: {\n mode: InterruptionMode;\n } | null;\n };\n preCallWebhook: {\n enabled: boolean;\n url: string | null;\n authToken: string | null;\n timeout: number;\n parameters: string[];\n };\n builtInTools: {\n dtmf: EnabledWithDescription;\n hangup: {\n enabled: boolean;\n description: string | null;\n message: string | null;\n };\n transfer: TransferCapability;\n };\n assignedToolIds: string[];\n toolUseSites?: ToolUseSiteWire[];\n automaticActions: {\n beforeCallStart: (ActionUseSiteWire & { trigger: 'before_call_start' }) | null;\n };\n knowledgeBaseIds: string[];\n abTestGroupIds: string[];\n};\n\ntype AgentV2NodeBaseWire = {\n uuid: string;\n name: string;\n isRoot: boolean;\n position: { x: number; y: number };\n behavior: { waitAfterExecuting: number; [key: string]: number | undefined };\n edges: AgentV2EdgeWire[];\n builtInTools?: NodeBuiltInCapabilities;\n};\n\nexport type AgentV2NodeWire =\n | (AgentV2NodeBaseWire & {\n type: 'global';\n prompt: PromptWire;\n })\n | (AgentV2NodeBaseWire & {\n type: 'standard';\n prompt: PromptWire;\n toolUuids: string[];\n toolUseSiteUuids?: string[];\n knowledgeBaseUuids: string[];\n customDataTableNames: string[];\n builtInTools: NodeBuiltInCapabilities;\n sopSpec: unknown;\n overrides: {\n voice?: { voiceUuid: string | null };\n llm?: { model: string | null; llmModelUuid: string | null; temperature: number | null };\n };\n perTurnWebhook?: {\n enabled: boolean;\n url: string;\n authToken?: string | null;\n } | null;\n perTurnExtractionFields?: ExtractionField[] | null;\n perTurnAction?: (ActionUseSiteWire & { trigger: 'every_turn' }) | null;\n })\n | (AgentV2NodeBaseWire & {\n type: 'http';\n url: string;\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n headers: Record<string, string>;\n body: unknown;\n responseSelectors: { name: string; value: string }[];\n runInBackground: boolean;\n backgroundMessage: string | null;\n executionMessage: string | null;\n mockResponseData: unknown;\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'action_node';\n actionVersionUuid: string;\n inputMappings: Record<string, string>;\n outputParameterMappings: Record<string, string>;\n runInBackground: boolean;\n backgroundMessage: string | null;\n executionMessage: string | null;\n mockResponseData: unknown;\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'extract';\n fields: ExtractionField[];\n executionMessage: string | null;\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'say';\n executionMessage: string | null;\n overrides: { voice?: { voiceUuid: string | null } };\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'end_call';\n executionMessage: string | null;\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'routing';\n description: string;\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'ab_test';\n abTestGroupUuid: string;\n builtInTools: NodeBuiltInCapabilities;\n })\n | (AgentV2NodeBaseWire & {\n type: 'transfer';\n executionMessage: string | null;\n builtInTools: NodeBuiltInCapabilities & { transfer: TransferCapability };\n })\n | (AgentV2NodeBaseWire & {\n type: 'transfer_chat';\n executionMessage?: string | null;\n mode?: 'five9' | 'teammate_handoff';\n five9TenantName: string;\n five9CampaignName: string;\n five9ContactMapping: Record<string, unknown>;\n five9AttributesMapping: Record<string, unknown>[];\n builtInTools: NodeBuiltInCapabilities;\n });\n\nexport type AgentV2CommitContentWire = {\n config: AgentV2ConfigWire;\n nodes: AgentV2NodeWire[];\n summaryPrompt: string | null;\n};\n\nexport type EdgeDefinition = {\n key?: string;\n to: string;\n when: string;\n priority?: number;\n condition?: {\n variable: string;\n operator: string;\n value: string;\n } | null;\n};\n\ntype NodeBaseDefinition = {\n key: string;\n name: string;\n root?: boolean;\n position?: { x: number; y: number };\n waitAfterExecuting?: number;\n edges?: EdgeDefinition[];\n alwaysAvailable?: EnabledWithDescription;\n};\n\nexport type GlobalNodeDefinition = NodeBaseDefinition & {\n type: 'global';\n prompt: PromptReference;\n};\n\nexport type PromptNodeDefinition = NodeBaseDefinition & {\n type: 'prompt';\n prompt: PromptReference;\n actions?: CallableActionDefinition[];\n knowledgeBases?: RemoteReference[];\n customDataTables?: string[];\n sopSpec?: unknown;\n voiceOverride?: { voiceUuid: string | null };\n llmOverride?: { model: string | null; modelUuid: string | null; temperature: number | null };\n vadMinSilenceDuration?: number;\n waitAfterTransfer?: number;\n perTurnWebhook?: {\n enabled: boolean;\n url: string;\n authToken?: string | null;\n } | null;\n perTurnExtraction?: z.ZodObject<z.ZodRawShape> | null;\n perTurnAction?: ActionRunDefinition | null;\n transfer?: Pick<TransferCapability, 'enabled'> & Partial<Omit<TransferCapability, 'enabled'>>;\n};\n\nexport type ActionNodeDefinition = NodeBaseDefinition & {\n type: 'action';\n action: ActionDefinition;\n inputs: Record<string, string>;\n outputParameters?: ActionOutputParameters;\n runInBackground?: boolean;\n backgroundMessage?: string | null;\n executionMessage?: string | null;\n mockResponseData?: unknown;\n};\n\n/**\n * An HTTP request node in the Agent graph.\n *\n * Prefer `action.http(...)` plus `node.action(...)` for new work: Actions are\n * versioned and reusable, HTTP nodes are neither. This exists so Agents that\n * already contain HTTP nodes can be pulled into, edited as, and published from\n * real source instead of an opaque snapshot.\n */\nexport type HttpNodeDefinition = NodeBaseDefinition & {\n type: 'http';\n url: string;\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n headers?: Record<string, string>;\n body?: unknown;\n responseSelectors?: { name: string; value: string }[];\n runInBackground?: boolean;\n backgroundMessage?: string | null;\n executionMessage?: string | null;\n mockResponseData?: unknown;\n};\n\nexport type ExtractNodeDefinition = NodeBaseDefinition & {\n type: 'extract';\n schema: z.ZodObject<z.ZodRawShape>;\n message?: string | null;\n};\n\nexport type SayNodeDefinition = NodeBaseDefinition & {\n type: 'say';\n /** `null` for a say node that has not been given its line yet. */\n text: string | null;\n voiceUuid?: string | null;\n waitAfterSay?: number;\n};\n\nexport type EndCallNodeDefinition = NodeBaseDefinition & {\n type: 'end-call';\n message?: string | null;\n};\n\nexport type RouteNodeDefinition = NodeBaseDefinition & {\n type: 'route';\n description: string;\n};\n\nexport type AbTestNodeDefinition = NodeBaseDefinition & {\n type: 'ab-test';\n abTestGroupUuid: string;\n};\n\nexport type TransferNodeDefinition = NodeBaseDefinition & {\n type: 'transfer';\n message?: string | null;\n phoneNumber: string;\n mode?: 'cold' | 'warm';\n timeout?: number;\n description?: string | null;\n voicemailMessage?: string | null;\n waitAfterTransfer?: number;\n};\n\nexport type TransferChatNodeDefinition = NodeBaseDefinition & {\n type: 'transfer-chat';\n message?: string | null;\n mode: 'five9' | 'teammate_handoff';\n five9TenantName?: string;\n five9CampaignName?: string;\n five9ContactMapping?: Record<string, unknown>;\n five9AttributesMapping?: Record<string, unknown>[];\n};\n\nexport type NodeDefinition =\n | GlobalNodeDefinition\n | PromptNodeDefinition\n | ActionNodeDefinition\n | HttpNodeDefinition\n | ExtractNodeDefinition\n | SayNodeDefinition\n | EndCallNodeDefinition\n | RouteNodeDefinition\n | AbTestNodeDefinition\n | TransferNodeDefinition\n | TransferChatNodeDefinition;\n\nexport type AgentDefinition = {\n kind: 'agent-definition';\n key: string;\n name: string;\n description: string | null;\n branch: string;\n modality: 'voice' | 'text';\n folderUuid: string | null;\n analyzerUuids: string[];\n tagUuids: string[];\n containmentConfig: unknown;\n voice: {\n voiceUuid: string | null;\n backgroundNoise: BackgroundNoise;\n };\n llm: {\n model: string;\n modelUuid: string | null;\n temperature: number;\n };\n speech: {\n language: string;\n keyterms: string[];\n };\n call: {\n agentSpeaksFirst: boolean;\n firstSentence: string | null;\n maxCallLengthSeconds: number;\n record: boolean;\n checkInAfterSilence: { enabled: boolean; prompt: string | null };\n endCallAfterExtendedSilence: boolean;\n pciEnabled: boolean;\n /**\n * Background noise track, when it differs from `voice.backgroundNoise`.\n *\n * The product keeps the selected track after noise is switched off, so the\n * two can legitimately disagree (`voice: 'off'`, track: `'coffee_shop'`).\n * `null` mirrors `voice.backgroundNoise`, which is the common case.\n */\n backgroundNoiseTrack: BackgroundNoise | null;\n /** `null` omits the gain entirely rather than sending a default. */\n backgroundNoiseGain: number | null;\n /** `null` omits interruption config entirely rather than defaulting it. */\n interruptionMode: InterruptionMode | null;\n };\n preCallWebhook: {\n enabled: boolean;\n url: string | null;\n authToken: string | null;\n timeout: number;\n parameters: string[];\n };\n capabilities: {\n dtmf: EnabledWithDescription;\n hangup: EnabledWithDescription & { message: string | null };\n transfer: TransferCapability;\n };\n knowledgeBases: RemoteReference[];\n beforeCallAction: ActionRunDefinition | null;\n summaryPrompt: string | null;\n /**\n * A/B test groups on the Agent.\n *\n * `null` derives the set from `ab-test` nodes, which is what authoring in code\n * produces. Pulled Agents can carry groups with no corresponding node, so they\n * set this explicitly.\n */\n abTestGroupIds: string[] | null;\n nodes: NodeDefinition[];\n};\n\nexport type AgentDefinitionInput = {\n key: string;\n name: string;\n description?: string | null;\n branch: string;\n modality?: 'voice' | 'text';\n folderUuid?: string | null;\n analyzerUuids?: string[];\n tagUuids?: string[];\n containmentConfig?: unknown;\n voice?: {\n voiceUuid?: string | null;\n backgroundNoise?: BackgroundNoise;\n };\n llm?: {\n model?: string;\n modelUuid?: string | null;\n temperature?: number;\n };\n speech?: {\n language?: string;\n keyterms?: string[];\n };\n call?: Partial<AgentDefinition['call']>;\n preCallWebhook?: Partial<AgentDefinition['preCallWebhook']>;\n capabilities?: {\n dtmf?: Partial<EnabledWithDescription>;\n hangup?: Partial<EnabledWithDescription & { message: string | null }>;\n transfer?: Partial<TransferCapability>;\n };\n knowledgeBases?: RemoteReference[];\n beforeCallAction?: ActionRunDefinition | null;\n summaryPrompt?: string | null;\n abTestGroupIds?: string[] | null;\n nodes: NodeDefinition[];\n};\n\nexport type AgentIdentityKind = 'node' | 'edge' | 'action-use-site' | 'action-version-placeholder';\n\nexport type AgentCompileOptions = {\n actionVersionUuids?: Record<string, string>;\n identity?: (input: { kind: AgentIdentityKind; key: string }) => string | undefined;\n readPromptFile?: (path: string) => string;\n readActionSourceFile?: (path: string) => string;\n allowUnresolvedActionVersions?: boolean;\n};\n\nexport type CompiledAgentProject = {\n agent: {\n key: string;\n name: string;\n description: string | null;\n modality: 'voice' | 'text';\n folderUuid: string | null;\n analyzerUuids: string[];\n tagUuids: string[];\n containmentConfig: unknown;\n };\n branch: {\n name: string;\n };\n actions: { key: string; versionUuid: string; values: ActionVersionValues }[];\n content: AgentV2CommitContentWire;\n};\n\nfunction defaultTransferCapability(): TransferCapability {\n return {\n enabled: false,\n phoneNumber: null,\n timeout: 120,\n mode: 'cold',\n description: null,\n voicemailMessage: null,\n };\n}\n\nexport function defineAgent(input: AgentDefinitionInput): AgentDefinition {\n const transferDefaults = defaultTransferCapability();\n return {\n kind: 'agent-definition',\n key: input.key,\n name: input.name,\n description: input.description ?? null,\n branch: input.branch,\n modality: input.modality ?? 'voice',\n folderUuid: input.folderUuid ?? null,\n analyzerUuids: input.analyzerUuids ?? [],\n tagUuids: input.tagUuids ?? [],\n containmentConfig: input.containmentConfig ?? null,\n voice: {\n voiceUuid: input.voice?.voiceUuid ?? null,\n backgroundNoise: input.voice?.backgroundNoise ?? 'off',\n },\n llm: {\n model: input.llm?.model ?? 'gpt-4.1',\n modelUuid: input.llm?.modelUuid ?? null,\n temperature: input.llm?.temperature ?? 0.65,\n },\n speech: {\n language: input.speech?.language ?? 'en',\n keyterms: input.speech?.keyterms ?? [],\n },\n call: {\n agentSpeaksFirst: input.call?.agentSpeaksFirst ?? false,\n firstSentence: input.call?.firstSentence ?? null,\n maxCallLengthSeconds: input.call?.maxCallLengthSeconds ?? 1800,\n record: input.call?.record ?? true,\n checkInAfterSilence: input.call?.checkInAfterSilence ?? { enabled: false, prompt: null },\n endCallAfterExtendedSilence: input.call?.endCallAfterExtendedSilence ?? false,\n pciEnabled: input.call?.pciEnabled ?? false,\n backgroundNoiseTrack: input.call?.backgroundNoiseTrack ?? null,\n backgroundNoiseGain: input.call?.backgroundNoiseGain === undefined ? 1 : input.call.backgroundNoiseGain,\n interruptionMode: input.call?.interruptionMode === undefined ? 'medium' : input.call.interruptionMode,\n },\n preCallWebhook: {\n enabled: input.preCallWebhook?.enabled ?? false,\n url: input.preCallWebhook?.url ?? null,\n authToken: input.preCallWebhook?.authToken ?? null,\n timeout: input.preCallWebhook?.timeout ?? 5,\n parameters: input.preCallWebhook?.parameters ?? [],\n },\n capabilities: {\n dtmf: {\n enabled: input.capabilities?.dtmf?.enabled ?? false,\n description: input.capabilities?.dtmf?.description ?? null,\n },\n hangup: {\n enabled: input.capabilities?.hangup?.enabled ?? true,\n description: input.capabilities?.hangup?.description ?? null,\n message: input.capabilities?.hangup?.message ?? null,\n },\n transfer: {\n enabled: input.capabilities?.transfer?.enabled ?? transferDefaults.enabled,\n phoneNumber: input.capabilities?.transfer?.phoneNumber ?? transferDefaults.phoneNumber,\n timeout: input.capabilities?.transfer?.timeout ?? transferDefaults.timeout,\n mode: input.capabilities?.transfer?.mode ?? transferDefaults.mode,\n description: input.capabilities?.transfer?.description ?? transferDefaults.description,\n voicemailMessage: input.capabilities?.transfer?.voicemailMessage ?? transferDefaults.voicemailMessage,\n },\n },\n knowledgeBases: input.knowledgeBases ?? [],\n beforeCallAction: input.beforeCallAction ?? null,\n summaryPrompt: input.summaryPrompt ?? null,\n abTestGroupIds: input.abTestGroupIds ?? null,\n nodes: input.nodes,\n };\n}\n\nexport const node = {\n global(config: Omit<GlobalNodeDefinition, 'type'>): GlobalNodeDefinition {\n return { type: 'global', ...config };\n },\n prompt(config: Omit<PromptNodeDefinition, 'type'>): PromptNodeDefinition {\n return { type: 'prompt', ...config };\n },\n action(config: Omit<ActionNodeDefinition, 'type'>): ActionNodeDefinition {\n return { type: 'action', ...config };\n },\n http(config: Omit<HttpNodeDefinition, 'type'>): HttpNodeDefinition {\n return { type: 'http', ...config };\n },\n extract(config: Omit<ExtractNodeDefinition, 'type'>): ExtractNodeDefinition {\n return { type: 'extract', ...config };\n },\n say(config: Omit<SayNodeDefinition, 'type'>): SayNodeDefinition {\n return { type: 'say', ...config };\n },\n endCall(config: Omit<EndCallNodeDefinition, 'type'>): EndCallNodeDefinition {\n return { type: 'end-call', ...config };\n },\n route(config: Omit<RouteNodeDefinition, 'type'>): RouteNodeDefinition {\n return { type: 'route', ...config };\n },\n abTest(config: Omit<AbTestNodeDefinition, 'type'>): AbTestNodeDefinition {\n return { type: 'ab-test', ...config };\n },\n transfer(config: Omit<TransferNodeDefinition, 'type'>): TransferNodeDefinition {\n return { type: 'transfer', ...config };\n },\n transferChat(config: Omit<TransferChatNodeDefinition, 'type'>): TransferChatNodeDefinition {\n return { type: 'transfer-chat', ...config };\n },\n};\n\nexport const prompt = {\n inline(text: string | null, example: string | null = null, generatedExamples?: unknown): PromptReference {\n return { kind: 'inline', text, example, ...(generatedExamples === undefined ? {} : { generatedExamples }) };\n },\n file(path: string, example: string | null = null): PromptReference {\n return { kind: 'file', path, example };\n },\n version(versionId: string): PromptReference {\n return { kind: 'version', versionId };\n },\n};\n\nexport function reference(uuid: string): RemoteReference {\n return { uuid };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction deterministicUuid(input: { kind: AgentIdentityKind; key: string }): string {\n const bytes = Buffer.from(createHash('sha256').update(`${input.kind}:${input.key}`).digest().subarray(0, 16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = bytes.toString('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction resolveIdentity({\n options,\n kind,\n key,\n fallbackKeys = [],\n}: {\n options: AgentCompileOptions;\n kind: AgentIdentityKind;\n key: string;\n fallbackKeys?: string[];\n}): string {\n for (const candidateKey of [key, ...fallbackKeys]) {\n const identity = options.identity?.({ kind, key: candidateKey });\n if (identity !== undefined) {\n return identity;\n }\n }\n return deterministicUuid({ kind, key });\n}\n\nexport function canonicalAuthoringKey(value: string, fallback: string): string {\n const normalizedCharacters: string[] = [];\n let needsSeparator = false;\n for (const character of value.toLowerCase()) {\n const characterCode = character.charCodeAt(0);\n const isLowercaseLetter = characterCode >= 97 && characterCode <= 122;\n const isDigit = characterCode >= 48 && characterCode <= 57;\n if (isLowercaseLetter || isDigit) {\n if (needsSeparator && normalizedCharacters.length > 0) {\n normalizedCharacters.push('-');\n }\n normalizedCharacters.push(character);\n needsSeparator = false;\n } else if (normalizedCharacters.length > 0) {\n needsSeparator = true;\n }\n }\n const normalized = normalizedCharacters.join('');\n return normalized === '' ? fallback : normalized;\n}\n\nexport function canonicalAuthoringKeys(values: { value: string; fallback: string }[]): string[] {\n const used = new Set<string>();\n return values.map(({ value, fallback }) => {\n const base = canonicalAuthoringKey(value, fallback);\n let candidate = base;\n let sequence = 2;\n while (used.has(candidate)) {\n candidate = `${base}-${sequence}`;\n sequence += 1;\n }\n used.add(candidate);\n return candidate;\n });\n}\n\nfunction jsonSchemaDescription(value: Record<string, unknown>): string {\n return typeof value.description === 'string' ? value.description : '';\n}\n\nfunction extractionFieldFromJsonSchema({\n name,\n value,\n required,\n path,\n}: {\n name: string;\n value: unknown;\n required: boolean;\n path: string;\n}): ExtractionField {\n if (!isRecord(value)) {\n throw new Error(`${path} is not a representable extraction field`);\n }\n\n const enumValues = Array.isArray(value.enum)\n ? value.enum.filter(\n (item): item is string | number | boolean =>\n typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean'\n )\n : undefined;\n\n if (value.type === 'object') {\n const rawProperties = isRecord(value.properties) ? value.properties : {};\n const requiredNames = new Set(\n Array.isArray(value.required) ? value.required.filter((item): item is string => typeof item === 'string') : []\n );\n return {\n name,\n type: 'object',\n description: jsonSchemaDescription(value),\n required,\n properties: Object.entries(rawProperties).map(([childName, child]) =>\n extractionFieldFromJsonSchema({\n name: childName,\n value: child,\n required: requiredNames.has(childName),\n path: `${path}.${childName}`,\n })\n ),\n };\n }\n\n if (value.type === 'array') {\n if (value.items === undefined) {\n throw new Error(`${path} must declare an array item schema`);\n }\n return {\n name,\n type: 'array',\n description: jsonSchemaDescription(value),\n required,\n items: extractionFieldFromJsonSchema({\n name: 'item',\n value: value.items,\n required: true,\n path: `${path}[]`,\n }),\n };\n }\n\n if (!['string', 'number', 'integer', 'boolean'].includes(String(value.type))) {\n throw new Error(`${path} uses unsupported extraction type \"${String(value.type)}\"`);\n }\n\n return {\n name,\n type: value.type === 'integer' ? 'number' : String(value.type),\n description: jsonSchemaDescription(value),\n required,\n ...(enumValues === undefined ? {} : { enum: enumValues }),\n };\n}\n\nfunction extractionFieldsFromZod(schema: z.ZodObject<z.ZodRawShape>): ExtractionField[] {\n const jsonSchema = z.toJSONSchema(schema);\n if (!isRecord(jsonSchema) || jsonSchema.type !== 'object') {\n throw new Error('Extraction schemas must be Zod objects');\n }\n const rawProperties = isRecord(jsonSchema.properties) ? jsonSchema.properties : {};\n const requiredNames = new Set(\n Array.isArray(jsonSchema.required)\n ? jsonSchema.required.filter((item): item is string => typeof item === 'string')\n : []\n );\n return Object.entries(rawProperties).map(([name, value]) =>\n extractionFieldFromJsonSchema({\n name,\n value,\n required: requiredNames.has(name),\n path: `schema.${name}`,\n })\n );\n}\n\nfunction compilePrompt(referenceValue: PromptReference, options: AgentCompileOptions): PromptWire {\n switch (referenceValue.kind) {\n case 'inline':\n return {\n type: 'inline',\n prompt: referenceValue.text,\n example: referenceValue.example,\n // Product-generated; preserved verbatim so pulled prompts round-trip.\n ...(referenceValue.generatedExamples === undefined\n ? {}\n : { generatedExamples: referenceValue.generatedExamples }),\n };\n case 'file': {\n if (options.readPromptFile === undefined) {\n throw new Error(`Prompt file \"${referenceValue.path}\" requires a readPromptFile compiler option`);\n }\n return {\n type: 'inline',\n prompt: options.readPromptFile(referenceValue.path),\n example: referenceValue.example,\n };\n }\n case 'version':\n return { type: 'reference', promptVersionId: referenceValue.versionId };\n }\n}\n\nfunction resolveActionVersion({\n definition,\n options,\n}: {\n definition: ActionDefinition;\n options: AgentCompileOptions;\n}): string {\n if (definition.kind === 'reference') {\n return definition.versionUuid;\n }\n const resolved = options.actionVersionUuids?.[definition.key];\n if (resolved !== undefined) {\n return resolved;\n }\n if (options.allowUnresolvedActionVersions === true) {\n return resolveIdentity({\n options,\n kind: 'action-version-placeholder',\n key: definition.key,\n });\n }\n throw new Error(`Action \"${definition.key}\" does not have a resolved version UUID`);\n}\n\nfunction pointerForInputName(name: string): string {\n return `/${name.replace(/~/g, '~0').replace(/\\//g, '~1')}`;\n}\n\nfunction compileOutputParameterMappings(outputParameters: Record<string, string>): Record<string, string> {\n const mappedParameters = new Set<string>();\n const mappings: [string, string][] = [];\n for (const [outputName, parameterName] of Object.entries(outputParameters)) {\n if (mappedParameters.has(parameterName)) {\n throw new Error(`Agent parameter \"${parameterName}\" is mapped from more than one Action output`);\n }\n mappedParameters.add(parameterName);\n mappings.push([parameterName, `{{ outputs.${outputName} }}`]);\n }\n return Object.fromEntries(mappings);\n}\n\nfunction compileCallableUseSite({\n callable,\n canonicalKey,\n options,\n}: {\n callable: CallableActionDefinition;\n canonicalKey: string;\n options: AgentCompileOptions;\n}): ToolUseSiteWire {\n const inputMappings: Record<string, string> = {};\n const inputDescriptions: Record<string, string> = {};\n\n for (const [name, input] of Object.entries(callable.inputs)) {\n const pointer = pointerForInputName(name);\n if (input.source === 'agent') {\n inputDescriptions[pointer] = input.description;\n } else {\n inputMappings[pointer] = input.value;\n }\n }\n\n const contractProperties = callable.action.contract?.inputSchema.properties ?? {};\n for (const [name, schema] of Object.entries(contractProperties)) {\n const pointer = pointerForInputName(name);\n if (inputMappings[pointer] !== undefined || inputDescriptions[pointer] !== undefined) {\n continue;\n }\n if (schema.description.trim() === '') {\n throw new Error(`Callable Action \"${callable.key}\" input \"${name}\" needs an agent-facing description`);\n }\n inputDescriptions[pointer] = schema.description;\n }\n\n return {\n actionUseSiteUuid: resolveIdentity({\n options,\n kind: 'action-use-site',\n key: callable.key,\n fallbackKeys: [canonicalKey],\n }),\n actionVersionUuid: resolveActionVersion({ definition: callable.action, options }),\n name: callable.name,\n description: callable.description,\n inputDescriptions,\n inputMappings,\n outputParameterMappings: compileOutputParameterMappings(callable.outputParameters),\n };\n}\n\nfunction compileActionRun<TTrigger extends 'before_call_start' | 'every_turn'>({\n run,\n trigger,\n canonicalKey,\n options,\n}: {\n run: ActionRunDefinition;\n trigger: TTrigger;\n canonicalKey: string;\n options: AgentCompileOptions;\n}): ActionUseSiteWire & { trigger: TTrigger } {\n return {\n actionUseSiteUuid: resolveIdentity({\n options,\n kind: 'action-use-site',\n key: run.key,\n fallbackKeys: [canonicalKey],\n }),\n actionVersionUuid: resolveActionVersion({ definition: run.action, options }),\n inputMappings: Object.fromEntries(\n Object.entries(run.inputs).map(([name, value]) => [\n name.startsWith('/') ? name : pointerForInputName(name),\n value,\n ])\n ),\n outputParameterMappings: compileOutputParameterMappings(run.outputParameters),\n trigger,\n };\n}\n\nfunction collectCallableActions(nodes: NodeDefinition[]): CallableActionDefinition[] {\n const byKey = new Map<string, CallableActionDefinition>();\n for (const definition of nodes) {\n if (definition.type !== 'prompt') {\n continue;\n }\n for (const callable of definition.actions ?? []) {\n const existing = byKey.get(callable.key);\n if (existing !== undefined && existing !== callable) {\n throw new Error(`Callable Action key \"${callable.key}\" is defined more than once`);\n }\n byKey.set(callable.key, callable);\n }\n }\n return [...byKey.values()];\n}\n\nfunction collectInlineActions(definition: AgentDefinition): InlineActionDefinition[] {\n const byKey = new Map<string, InlineActionDefinition>();\n const visit = (actionDefinition: ActionDefinition): void => {\n if (actionDefinition.kind !== 'inline') {\n return;\n }\n const existing = byKey.get(actionDefinition.key);\n if (existing !== undefined && existing !== actionDefinition) {\n throw new Error(`Inline Action key \"${actionDefinition.key}\" is defined more than once`);\n }\n byKey.set(actionDefinition.key, actionDefinition);\n };\n\n for (const callable of collectCallableActions(definition.nodes)) {\n visit(callable.action);\n }\n if (definition.beforeCallAction !== null) {\n visit(definition.beforeCallAction.action);\n }\n for (const definitionNode of definition.nodes) {\n if (definitionNode.type === 'action') {\n visit(definitionNode.action);\n }\n if (\n definitionNode.type === 'prompt' &&\n definitionNode.perTurnAction !== null &&\n definitionNode.perTurnAction !== undefined\n ) {\n visit(definitionNode.perTurnAction.action);\n }\n }\n return [...byKey.values()];\n}\n\nfunction compileEdges({\n definition,\n canonicalNodeKey,\n nodeUuids,\n options,\n}: {\n definition: NodeDefinition;\n canonicalNodeKey: string;\n nodeUuids: Map<string, string>;\n options: AgentCompileOptions;\n}): AgentV2EdgeWire[] {\n return (definition.edges ?? []).map((edgeDefinition, index) => {\n const targetUuid = nodeUuids.get(edgeDefinition.to);\n if (targetUuid === undefined) {\n throw new Error(`Node \"${definition.key}\" points to unknown node \"${edgeDefinition.to}\"`);\n }\n const edgeKey = edgeDefinition.key ?? `${definition.key}:${index}`;\n return {\n uuid: resolveIdentity({\n options,\n kind: 'edge',\n key: edgeKey,\n fallbackKeys: [`${canonicalNodeKey}:${index}`],\n }),\n toNodeUuid: targetUuid,\n description: edgeDefinition.when,\n priority: edgeDefinition.priority ?? index,\n condition: edgeDefinition.condition ?? null,\n };\n });\n}\n\nfunction baseNodeWire({\n definition,\n canonicalNodeKey,\n index,\n nodeUuids,\n options,\n}: {\n definition: NodeDefinition;\n canonicalNodeKey: string;\n index: number;\n nodeUuids: Map<string, string>;\n options: AgentCompileOptions;\n}): AgentV2NodeBaseWire {\n const uuid = nodeUuids.get(definition.key);\n if (uuid === undefined) {\n throw new Error(`Node \"${definition.key}\" has no compiled identity`);\n }\n return {\n uuid,\n name: definition.name,\n isRoot: definition.root ?? false,\n position: definition.position ?? { x: (index % 4) * 320, y: Math.floor(index / 4) * 220 },\n behavior: { waitAfterExecuting: definition.waitAfterExecuting ?? 0 },\n edges: compileEdges({ definition, canonicalNodeKey, nodeUuids, options }),\n };\n}\n\nfunction nodeCapabilities(definition: NodeDefinition): NodeBuiltInCapabilities {\n return definition.alwaysAvailable === undefined ? {} : { alwaysAvailable: definition.alwaysAvailable };\n}\n\nfunction promptNodeCapabilities(definition: PromptNodeDefinition): NodeBuiltInCapabilities {\n const base = nodeCapabilities(definition);\n if (definition.transfer === undefined) {\n return base;\n }\n return {\n ...base,\n transfer: {\n enabled: definition.transfer.enabled,\n phoneNumber: definition.transfer.phoneNumber ?? null,\n timeout: definition.transfer.timeout ?? 120,\n mode: definition.transfer.mode ?? 'cold',\n description: definition.transfer.description ?? null,\n voicemailMessage: definition.transfer.voicemailMessage ?? null,\n },\n };\n}\n\nfunction compileNode({\n definition,\n canonicalNodeKey,\n canonicalCallableKeys,\n index,\n nodeUuids,\n options,\n}: {\n definition: NodeDefinition;\n canonicalNodeKey: string;\n canonicalCallableKeys: Map<string, string>;\n index: number;\n nodeUuids: Map<string, string>;\n options: AgentCompileOptions;\n}): AgentV2NodeWire {\n const base = baseNodeWire({ definition, canonicalNodeKey, index, nodeUuids, options });\n const builtInTools = nodeCapabilities(definition);\n\n switch (definition.type) {\n case 'global':\n return {\n ...base,\n type: 'global',\n prompt: compilePrompt(definition.prompt, options),\n };\n case 'prompt': {\n const perTurnAction =\n definition.perTurnAction === null || definition.perTurnAction === undefined\n ? null\n : compileActionRun({\n run: definition.perTurnAction,\n trigger: 'every_turn',\n canonicalKey: `${canonicalNodeKey}:every-turn`,\n options,\n });\n return {\n ...base,\n type: 'standard',\n prompt: compilePrompt(definition.prompt, options),\n toolUuids: [],\n // Present whenever `actions` is declared, even when empty, so an\n // explicit empty list survives the round trip.\n ...(definition.actions === undefined\n ? {}\n : {\n toolUseSiteUuids: definition.actions.map((callable) =>\n resolveIdentity({\n options,\n kind: 'action-use-site',\n key: callable.key,\n fallbackKeys: [canonicalCallableKeys.get(callable.key) ?? callable.key],\n })\n ),\n }),\n knowledgeBaseUuids: (definition.knowledgeBases ?? []).map((item) => item.uuid),\n customDataTableNames: definition.customDataTables ?? [],\n builtInTools: promptNodeCapabilities(definition),\n sopSpec: definition.sopSpec ?? null,\n overrides: {\n ...(definition.voiceOverride === undefined ? {} : { voice: definition.voiceOverride }),\n ...(definition.llmOverride === undefined\n ? {}\n : {\n llm: {\n model: definition.llmOverride.model,\n llmModelUuid: definition.llmOverride.modelUuid,\n temperature: definition.llmOverride.temperature,\n },\n }),\n },\n behavior: {\n ...base.behavior,\n ...(definition.vadMinSilenceDuration === undefined\n ? {}\n : { vadMinSilenceDuration: definition.vadMinSilenceDuration }),\n ...(definition.waitAfterTransfer === undefined ? {} : { waitAfterTransfer: definition.waitAfterTransfer }),\n },\n // These three round-trip three states each: absent, explicit null, or a\n // value. The product emits all three across different nodes, so\n // `undefined` means \"omit the key\" and `null` means \"write null\".\n ...(definition.perTurnWebhook === undefined ? {} : { perTurnWebhook: definition.perTurnWebhook }),\n ...(definition.perTurnExtraction === undefined\n ? {}\n : {\n perTurnExtractionFields:\n definition.perTurnExtraction === null ? null : extractionFieldsFromZod(definition.perTurnExtraction),\n }),\n ...(definition.perTurnAction === undefined ? {} : { perTurnAction }),\n };\n }\n case 'action':\n return {\n ...base,\n type: 'action_node',\n actionVersionUuid: resolveActionVersion({ definition: definition.action, options }),\n inputMappings: Object.fromEntries(\n Object.entries(definition.inputs).map(([name, value]) => [\n name.startsWith('/') ? name : pointerForInputName(name),\n value,\n ])\n ),\n outputParameterMappings: compileOutputParameterMappings(definition.outputParameters ?? {}),\n runInBackground: definition.runInBackground ?? false,\n backgroundMessage: definition.backgroundMessage ?? null,\n executionMessage: definition.executionMessage ?? null,\n mockResponseData: definition.mockResponseData ?? null,\n builtInTools,\n };\n case 'http':\n return {\n ...base,\n type: 'http',\n url: definition.url,\n method: definition.method,\n headers: definition.headers ?? {},\n body: definition.body ?? null,\n responseSelectors: definition.responseSelectors ?? [],\n runInBackground: definition.runInBackground ?? false,\n backgroundMessage: definition.backgroundMessage ?? null,\n executionMessage: definition.executionMessage ?? null,\n mockResponseData: definition.mockResponseData ?? null,\n builtInTools,\n };\n case 'extract':\n return {\n ...base,\n type: 'extract',\n fields: extractionFieldsFromZod(definition.schema),\n executionMessage: definition.message ?? null,\n builtInTools,\n };\n case 'say':\n return {\n ...base,\n type: 'say',\n executionMessage: definition.text,\n overrides: definition.voiceUuid === undefined ? {} : { voice: { voiceUuid: definition.voiceUuid } },\n behavior: {\n ...base.behavior,\n ...(definition.waitAfterSay === undefined ? {} : { waitAfterSay: definition.waitAfterSay }),\n },\n builtInTools,\n };\n case 'end-call':\n return {\n ...base,\n type: 'end_call',\n executionMessage: definition.message ?? null,\n builtInTools,\n };\n case 'route':\n return {\n ...base,\n type: 'routing',\n description: definition.description,\n builtInTools,\n };\n case 'ab-test':\n return {\n ...base,\n type: 'ab_test',\n abTestGroupUuid: definition.abTestGroupUuid,\n builtInTools,\n };\n case 'transfer': {\n const transfer = {\n enabled: true,\n phoneNumber: definition.phoneNumber,\n timeout: definition.timeout ?? 120,\n mode: definition.mode ?? 'cold',\n description: definition.description ?? null,\n voicemailMessage: definition.voicemailMessage ?? null,\n };\n return {\n ...base,\n type: 'transfer',\n executionMessage: definition.message ?? null,\n behavior: {\n ...base.behavior,\n ...(definition.waitAfterTransfer === undefined ? {} : { waitAfterTransfer: definition.waitAfterTransfer }),\n },\n builtInTools: { ...builtInTools, transfer },\n };\n }\n case 'transfer-chat':\n return {\n ...base,\n type: 'transfer_chat',\n executionMessage: definition.message ?? null,\n mode: definition.mode,\n five9TenantName: definition.five9TenantName ?? '',\n five9CampaignName: definition.five9CampaignName ?? '',\n five9ContactMapping: definition.five9ContactMapping ?? {},\n five9AttributesMapping: definition.five9AttributesMapping ?? [],\n builtInTools,\n };\n }\n}\n\nfunction validateDefinition(definition: AgentDefinition): void {\n const keys = definition.nodes.map((definitionNode) => definitionNode.key);\n if (new Set(keys).size !== keys.length) {\n throw new Error('Every node key must be unique');\n }\n // An Agent with no nodes is a real product state — a freshly created Agent\n // before any graph is drawn — so it is representable rather than rejected.\n // The root-node invariant still applies to every Agent that has nodes.\n if (definition.nodes.length === 0) {\n return;\n }\n const roots = definition.nodes.filter((definitionNode) => definitionNode.root === true);\n if (roots.length !== 1) {\n throw new Error(`An agent with nodes must contain exactly one root node; received ${roots.length}`);\n }\n if (definition.nodes.some((definitionNode) => definitionNode.type === 'global' && definitionNode.root === true)) {\n throw new Error('The global node cannot be the root node');\n }\n}\n\nexport function compileAgent(definition: AgentDefinition, options: AgentCompileOptions = {}): CompiledAgentProject {\n validateDefinition(definition);\n\n const canonicalNodeKeys = canonicalAuthoringKeys(\n definition.nodes.map((definitionNode, index) => ({\n value: definitionNode.name,\n fallback: `node-${index + 1}`,\n }))\n );\n const canonicalNodeKeysByDefinitionKey = new Map(\n definition.nodes.map((definitionNode, index) => [\n definitionNode.key,\n canonicalNodeKeys[index] ?? definitionNode.key,\n ])\n );\n const nodeUuids = new Map(\n definition.nodes.map((definitionNode, index) => [\n definitionNode.key,\n resolveIdentity({\n options,\n kind: 'node',\n key: definitionNode.key,\n fallbackKeys: [canonicalNodeKeys[index] ?? definitionNode.key],\n }),\n ])\n );\n const callables = collectCallableActions(definition.nodes);\n const canonicalCallableKeys = canonicalAuthoringKeys(\n callables.map((callable, index) => ({\n value: callable.name,\n fallback: `action-${index + 1}`,\n }))\n );\n const canonicalCallableKeysByDefinitionKey = new Map(\n callables.map((callable, index) => [callable.key, canonicalCallableKeys[index] ?? callable.key])\n );\n const toolUseSites = callables.map((callable) =>\n compileCallableUseSite({\n callable,\n canonicalKey: canonicalCallableKeysByDefinitionKey.get(callable.key) ?? callable.key,\n options,\n })\n );\n const inlineActions = collectInlineActions(definition);\n const abTestGroupIds = [\n ...new Set(\n definition.nodes.flatMap((definitionNode) =>\n definitionNode.type === 'ab-test' ? [definitionNode.abTestGroupUuid] : []\n )\n ),\n ];\n\n return {\n agent: {\n key: definition.key,\n name: definition.name,\n description: definition.description,\n modality: definition.modality,\n folderUuid: definition.folderUuid,\n analyzerUuids: definition.analyzerUuids,\n tagUuids: definition.tagUuids,\n containmentConfig: definition.containmentConfig,\n },\n branch: { name: definition.branch },\n actions: inlineActions.map((definitionAction) => ({\n key: definitionAction.key,\n versionUuid: resolveActionVersion({\n definition: definitionAction,\n options,\n }),\n values: compileAction(definitionAction, {\n ...(options.readActionSourceFile === undefined ? {} : { readSourceFile: options.readActionSourceFile }),\n }),\n })),\n content: {\n config: {\n voice: {\n voiceUuid: definition.voice.voiceUuid,\n backgroundNoise: definition.voice.backgroundNoise,\n },\n llm: {\n model: definition.llm.model,\n llmModelUuid: definition.llm.modelUuid,\n temperature: definition.llm.temperature,\n },\n speech: definition.speech,\n call: {\n agentSpeaksFirst: definition.call.agentSpeaksFirst,\n firstSentence: definition.call.firstSentence,\n maxCallLengthSeconds: definition.call.maxCallLengthSeconds,\n record: definition.call.record,\n checkInAfterSilence: definition.call.checkInAfterSilence,\n endCallAfterExtendedSilence: definition.call.endCallAfterExtendedSilence,\n pciEnabled: definition.call.pciEnabled,\n backgroundNoise: {\n trackName: definition.call.backgroundNoiseTrack ?? definition.voice.backgroundNoise,\n ...(definition.call.backgroundNoiseGain === null\n ? {}\n : { gainMultiplier: definition.call.backgroundNoiseGain }),\n },\n ...(definition.call.interruptionMode === null\n ? {}\n : { interruptionConfig: { mode: definition.call.interruptionMode } }),\n },\n preCallWebhook: definition.preCallWebhook,\n builtInTools: definition.capabilities,\n assignedToolIds: [],\n // Emitted whenever any node declares an `actions` array, so an Agent\n // that once had callable Actions keeps its explicit empty list rather\n // than dropping the key.\n ...(definition.nodes.some(\n (definitionNode) => definitionNode.type === 'prompt' && definitionNode.actions !== undefined\n )\n ? { toolUseSites }\n : {}),\n automaticActions: {\n beforeCallStart:\n definition.beforeCallAction === null\n ? null\n : compileActionRun({\n run: definition.beforeCallAction,\n trigger: 'before_call_start',\n canonicalKey: 'before-call-start',\n options,\n }),\n },\n knowledgeBaseIds: definition.knowledgeBases.map((item) => item.uuid),\n abTestGroupIds: definition.abTestGroupIds ?? abTestGroupIds,\n },\n nodes: definition.nodes.map((definitionNode, index) =>\n compileNode({\n definition: definitionNode,\n canonicalNodeKey: canonicalNodeKeysByDefinitionKey.get(definitionNode.key) ?? definitionNode.key,\n canonicalCallableKeys: canonicalCallableKeysByDefinitionKey,\n index,\n nodeUuids,\n options,\n })\n ),\n summaryPrompt: definition.summaryPrompt,\n },\n };\n}\n","import { z } from 'zod';\n\n/**\n * Request wire schemas for the Simple AI public REST API (`/api/v1`).\n *\n * These deliberately mirror the server's own schemas (see\n * `projects/server-v2/src/domains/data/query-schemas.ts` and\n * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two\n * in sync. Responses are typed but not strictly validated, so additive server\n * changes never break deployed SDK consumers.\n */\n\n/** Hard cap on hits a single query may return. */\nexport const MAX_QUERY_SIZE = 50;\n/** Maximum rows accepted by a single batch-upsert chunk. */\nexport const MAX_BATCH_ROWS = 1000;\n\nexport const tableNameSchema = z.string().regex(/^[a-z0-9_]+$/, 'Table names are lowercase snake_case identifiers');\n\nexport const filterValueSchema = z.union([z.string(), z.number(), z.boolean()]);\n\n// Mirrors the server's customDataFacetAttributePathSchema: dot-separated\n// column paths with no empty segments (OBJECT leaves are parent.child).\nexport const dataColumnPathSchema = z\n .string()\n .trim()\n .min(1)\n .max(1024)\n .refine((path) => path.split('.').every((segment) => segment.length > 0), {\n message: 'Must be a dot-separated column path with no empty segments',\n });\n\nexport const dataFilterSchema = z.object({\n column: dataColumnPathSchema,\n values: z.array(filterValueSchema),\n});\nexport type DataFilter = z.infer<typeof dataFilterSchema>;\n\nexport const queryInputSchema = z.object({\n tableName: tableNameSchema,\n filters: z.array(dataFilterSchema).optional(),\n text: z.string().max(5000).optional(),\n size: z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),\n from: z.number().int().min(0).optional(),\n});\nexport type QueryInput = z.input<typeof queryInputSchema>;\n\nexport const listOptionsSchema = z.object({\n page: z.number().int().min(1).optional(),\n perPage: z.number().int().min(1).max(200).optional(),\n orderBy: z.string().optional(),\n orderDirection: z.enum(['asc', 'desc']).optional(),\n /** Column-name → value equality filters applied server-side. */\n filters: z.record(z.string(), z.string()).optional(),\n});\nexport type ListOptions = z.input<typeof listOptionsSchema>;\n\nexport const recordPayloadSchema = z.record(z.string(), z.unknown());\nexport type RecordPayload = z.infer<typeof recordPayloadSchema>;\n\nexport const batchUpsertRowsSchema = z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);\n\n// ---------------------------------------------------------------------------\n// Response types (typed, tolerantly parsed)\n// ---------------------------------------------------------------------------\n\nexport type DataRecord = Record<string, unknown>;\n\nexport type QueryResult = {\n records: DataRecord[];\n total: number;\n};\n\nexport type ListResult = {\n records: DataRecord[];\n total_count: number;\n page: number;\n per_page: number;\n};\n\nexport type RecordResult = {\n record: DataRecord;\n};\n\nexport type DeleteResult = {\n success: boolean;\n message: string;\n};\n\nexport type BatchUpsertResult = {\n ingestBatchId: string;\n status: string;\n};\n\nexport type IngestBatchStatus = {\n id: string;\n tableName: string;\n status: string;\n rowCount: number;\n upsertedCount: number | null;\n errorMessage: string | null;\n createdAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n};\n\nexport type FacetsResult = Record<string, unknown>;\n","import type { HttpClient } from './http';\nimport {\n type BatchUpsertResult,\n batchUpsertRowsSchema,\n type DataRecord,\n type DeleteResult,\n type FacetsResult,\n type IngestBatchStatus,\n type ListOptions,\n type ListResult,\n listOptionsSchema,\n type QueryInput,\n queryInputSchema,\n type RecordPayload,\n type RecordResult,\n recordPayloadSchema,\n tableNameSchema,\n} from './schemas';\n\nfunction encodeTable(tableName: string): string {\n return encodeURIComponent(tableNameSchema.parse(tableName));\n}\n\n/**\n * Custom data tables — query, read, and write your organization's records.\n * Wraps the `/api/v1/data` REST endpoints.\n */\nexport class DataClient {\n readonly #http: HttpClient;\n\n constructor(http: HttpClient) {\n this.#http = http;\n }\n\n /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */\n async query<TRecord extends DataRecord = DataRecord>(\n input: QueryInput\n ): Promise<{ records: TRecord[]; total: number }> {\n const parsed = queryInputSchema.parse(input);\n const result = await this.#http.request({ method: 'POST', path: '/data/query', body: parsed });\n return result as { records: TRecord[]; total: number };\n }\n\n /** Facet values for an indexed table. */\n async facets(tableName: string): Promise<FacetsResult> {\n const result = await this.#http.request({ method: 'GET', path: `/data/facets/${encodeTable(tableName)}` });\n return result as FacetsResult;\n }\n\n /** Paginated listing straight from the relational store. */\n async list<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n options: ListOptions = {}\n ): Promise<{ records: TRecord[]; total_count: number; page: number; per_page: number }> {\n const parsed = listOptionsSchema.parse(options);\n const query: Record<string, string> = { ...(parsed.filters ?? {}) };\n if (parsed.page !== undefined) {\n query.page = String(parsed.page);\n }\n if (parsed.perPage !== undefined) {\n query.per_page = String(parsed.perPage);\n }\n if (parsed.orderBy !== undefined) {\n query.order_by = parsed.orderBy;\n }\n if (parsed.orderDirection !== undefined) {\n query.order_direction = parsed.orderDirection;\n }\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}`, query });\n return result as ListResult & { records: TRecord[] };\n }\n\n async get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{ record: TRecord }> {\n const result = await this.#http.request({ method: 'GET', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as RecordResult & { record: TRecord };\n }\n\n async create<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async update<TRecord extends DataRecord = DataRecord>(\n tableName: string,\n id: number,\n payload: RecordPayload\n ): Promise<{ record: TRecord }> {\n const result = await this.#http.request({\n method: 'PATCH',\n path: `/data/${encodeTable(tableName)}/${id}`,\n body: recordPayloadSchema.parse(payload),\n });\n return result as RecordResult & { record: TRecord };\n }\n\n async delete(tableName: string, id: number): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}/${id}` });\n return result as DeleteResult;\n }\n\n /** Deletes every record in the table. Irreversible. */\n async deleteAll(tableName: string): Promise<DeleteResult> {\n const result = await this.#http.request({ method: 'DELETE', path: `/data/${encodeTable(tableName)}` });\n return result as DeleteResult;\n }\n\n /**\n * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW\n * REPLACE on key conflict — omitted columns are cleared, not preserved.\n * Returns a batch handle; poll `getBatch` for completion.\n */\n async batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult> {\n const result = await this.#http.request({\n method: 'PUT',\n path: `/data/${encodeTable(tableName)}/batch`,\n body: { rows: batchUpsertRowsSchema.parse(rows) },\n });\n return result as BatchUpsertResult;\n }\n\n /** Status of an async upsert batch created by `batchUpsert`. */\n async getBatch(ingestBatchId: string): Promise<IngestBatchStatus> {\n const result = await this.#http.request({\n method: 'GET',\n path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`,\n });\n return result as IngestBatchStatus;\n }\n}\n","/** Error thrown for any non-2xx response from the Simple AI API. */\nexport class SimpleAIError extends Error {\n /** HTTP status code, or 0 when the request never reached the API. */\n readonly status: number;\n /** Machine-readable error code from the API body, when present. */\n readonly code: string | null;\n /** The parsed response body (JSON when possible, otherwise raw text). */\n readonly body: unknown;\n\n constructor({\n message,\n status,\n code,\n body,\n cause,\n }: {\n message: string;\n status: number;\n code: string | null;\n body: unknown;\n cause?: unknown;\n }) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'SimpleAIError';\n this.status = status;\n this.code = code;\n this.body = body;\n }\n}\n","import { SimpleAIError } from './errors';\n\nexport type FetchLike = (url: string, init: RequestInit) => Promise<Response>;\n\nexport type HttpClient = {\n request: (args: {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, string>;\n body?: unknown;\n }) => Promise<unknown>;\n};\n\nfunction parseBody(text: string): unknown {\n if (text.length === 0) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction errorDetails(body: unknown): { code: string | null; message: string | null } {\n if (body !== null && typeof body === 'object') {\n const record = body as { code?: unknown; error?: unknown; message?: unknown };\n const code = typeof record.code === 'string' ? record.code : null;\n const message =\n typeof record.message === 'string' ? record.message : typeof record.error === 'string' ? record.error : null;\n return { code, message };\n }\n return { code: null, message: typeof body === 'string' && body.length > 0 ? body : null };\n}\n\nexport function createHttpClient({\n baseUrl,\n apiKey,\n fetchImplementation,\n}: {\n baseUrl: string;\n apiKey: string;\n fetchImplementation: FetchLike;\n}): HttpClient {\n const normalizedBase = baseUrl.replace(/\\/+$/, '');\n\n return {\n request: async ({ method, path, query, body }) => {\n const queryString =\n query === undefined || Object.keys(query).length === 0 ? '' : `?${new URLSearchParams(query).toString()}`;\n const url = `${normalizedBase}${path}${queryString}`;\n\n let response: Response;\n try {\n response = await fetchImplementation(url, {\n method,\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json',\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n } catch (e) {\n throw new SimpleAIError({\n message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,\n status: 0,\n code: 'network_error',\n body: null,\n cause: e,\n });\n }\n\n const parsed = parseBody(await response.text());\n if (!response.ok) {\n const { code, message } = errorDetails(parsed);\n throw new SimpleAIError({\n message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,\n status: response.status,\n code,\n body: parsed,\n });\n }\n return parsed;\n },\n };\n}\n","import { DataClient } from './data';\nimport type { FetchLike } from './http';\nimport { createHttpClient } from './http';\n\nconst DEFAULT_BASE_URL = 'https://api.prod.usesimple.ai/api/v1';\n\nexport type SimpleAIOptions = {\n /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */\n apiKey?: string;\n /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */\n baseUrl?: string;\n /** Custom fetch implementation (for testing or instrumentation). */\n fetch?: FetchLike;\n};\n\nfunction envVar(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) {\n return undefined;\n }\n const value = process.env[name];\n return value === undefined || value === '' ? undefined : value;\n}\n\nexport class SimpleAI {\n /** Custom data tables — query, read, and write records. */\n readonly data: DataClient;\n\n constructor(options: SimpleAIOptions = {}) {\n const apiKey = options.apiKey ?? envVar('SIMPLE_API_KEY');\n if (apiKey === undefined) {\n throw new Error(\n 'Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. ' +\n 'Inside Simple AI code actions the key is injected automatically.'\n );\n }\n const baseUrl = options.baseUrl ?? envVar('SIMPLE_BASE_URL') ?? DEFAULT_BASE_URL;\n const fetchImplementation: FetchLike = options.fetch ?? ((url, init) => fetch(url, init));\n\n const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });\n this.data = new DataClient(http);\n }\n}\n","import { SimpleAI } from './client';\n\n/**\n * Brand the code-action runner uses to recognize `defineAction` handlers. The\n * runner calls the default export with `{ inputs, config }` either way; the\n * wrapper adds the authenticated `client` to the handler's context.\n */\nexport const SIMPLE_ACTION_BRAND = Symbol.for('simple-ai.action');\nconst SIMPLE_ACTION_RUNTIME = Symbol.for('simple-ai.action-runtime');\n\ntype ActionRuntime = {\n apiKey: string;\n baseUrl: string;\n};\n\nexport type ActionContext<TInputs = Record<string, unknown>> = {\n /** The Action's declared inputs, already validated against its input schema. */\n inputs: TInputs;\n /** Your organization's configuration variables. */\n config: Record<string, string>;\n /** The Simple AI SDK, authenticated for your organization. */\n client: SimpleAI;\n};\n\nexport type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {\n inputs: TInputs;\n config: Record<string, string>;\n [SIMPLE_ACTION_RUNTIME]?: ActionRuntime;\n}) => Promise<TResult>) & { [SIMPLE_ACTION_BRAND]: true };\n\n/**\n * Define a code action with a typed context and an org-authenticated SDK\n * client. The returned value must be your module's default export.\n *\n * ```ts\n * import { defineAction } from '@simple-ai-lab/sdk';\n *\n * export default defineAction(async ({ inputs, config, client }) => {\n * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });\n * return { found: records.length > 0 };\n * });\n * ```\n */\nexport function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(\n handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult\n): ActionHandler<TInputs, TResult> {\n const wrapped = async (invocation: {\n inputs: TInputs;\n config: Record<string, string>;\n [SIMPLE_ACTION_RUNTIME]?: ActionRuntime;\n }): Promise<TResult> => {\n const { inputs, config } = invocation;\n const runtime = invocation[SIMPLE_ACTION_RUNTIME];\n // The Dynamic Worker runner supplies a non-secret API identity. The\n // outbound Worker injects the real short-lived credential after the\n // request has crossed the untrusted isolate boundary.\n const client = runtime === undefined ? new SimpleAI() : new SimpleAI(runtime);\n return handler({ inputs, config, client });\n };\n const brand: { [SIMPLE_ACTION_BRAND]: true } = { [SIMPLE_ACTION_BRAND]: true };\n return Object.assign(wrapped, brand);\n}\n","import type { ActionVersionValues } from './actions';\nimport {\n type AgentCompileOptions,\n type AgentDefinition,\n type AgentV2CommitContentWire,\n type AgentV2NodeWire,\n type CompiledAgentProject,\n compileAgent,\n} from './agents';\n\nexport type AgentProjectSource = AgentDefinition | AgentSnapshotDefinition;\n\nexport type SnapshotAction = {\n key: string;\n sourceVersionUuid: string;\n values: ActionVersionValues;\n};\n\nexport type AgentSnapshotDefinition = {\n kind: 'agent-snapshot';\n agent: CompiledAgentProject['agent'];\n branch: CompiledAgentProject['branch'];\n actions: SnapshotAction[];\n content: AgentV2CommitContentWire;\n};\n\nexport function defineAgentSnapshot(definition: Omit<AgentSnapshotDefinition, 'kind'>): AgentSnapshotDefinition {\n return { kind: 'agent-snapshot', ...definition };\n}\n\nfunction replaceActionVersionUuid({\n versionUuid,\n actions,\n options,\n}: {\n versionUuid: string;\n actions: SnapshotAction[];\n options: AgentCompileOptions;\n}): string {\n const actionDefinition = actions.find((item) => item.sourceVersionUuid === versionUuid);\n if (actionDefinition === undefined) {\n return versionUuid;\n }\n return options.actionVersionUuids?.[actionDefinition.key] ?? versionUuid;\n}\n\nfunction compileSnapshotNode({\n node,\n actions,\n options,\n}: {\n node: AgentV2NodeWire;\n actions: SnapshotAction[];\n options: AgentCompileOptions;\n}): AgentV2NodeWire {\n if (node.type === 'action_node') {\n return {\n ...node,\n actionVersionUuid: replaceActionVersionUuid({\n versionUuid: node.actionVersionUuid,\n actions,\n options,\n }),\n };\n }\n if (node.type === 'standard' && node.perTurnAction != null) {\n return {\n ...node,\n perTurnAction: {\n ...node.perTurnAction,\n actionVersionUuid: replaceActionVersionUuid({\n versionUuid: node.perTurnAction.actionVersionUuid,\n actions,\n options,\n }),\n },\n };\n }\n return node;\n}\n\nfunction compileSnapshot(definition: AgentSnapshotDefinition, options: AgentCompileOptions): CompiledAgentProject {\n const snapshotActionValues = (values: ActionVersionValues): ActionVersionValues => {\n switch (values.actionType) {\n case 'code':\n return {\n ...values,\n operation: {\n ...values.operation,\n compiledJs: null,\n },\n };\n case 'http':\n case 'custom_data':\n case 'knowledge_base':\n return values;\n }\n };\n\n return {\n agent: definition.agent,\n branch: definition.branch,\n actions: definition.actions.map((item) => ({\n key: item.key,\n versionUuid: replaceActionVersionUuid({\n versionUuid: item.sourceVersionUuid,\n actions: definition.actions,\n options,\n }),\n values: snapshotActionValues(item.values),\n })),\n content: {\n ...definition.content,\n config: {\n ...definition.content.config,\n ...(definition.content.config.toolUseSites === undefined\n ? {}\n : {\n toolUseSites: definition.content.config.toolUseSites.map((useSite) => ({\n ...useSite,\n actionVersionUuid: replaceActionVersionUuid({\n versionUuid: useSite.actionVersionUuid,\n actions: definition.actions,\n options,\n }),\n })),\n }),\n automaticActions: {\n beforeCallStart:\n definition.content.config.automaticActions.beforeCallStart === null\n ? null\n : {\n ...definition.content.config.automaticActions.beforeCallStart,\n actionVersionUuid: replaceActionVersionUuid({\n versionUuid: definition.content.config.automaticActions.beforeCallStart.actionVersionUuid,\n actions: definition.actions,\n options,\n }),\n },\n },\n },\n nodes: definition.content.nodes.map((node) =>\n compileSnapshotNode({ node, actions: definition.actions, options })\n ),\n },\n };\n}\n\nexport function compileAgentProject(\n definition: AgentProjectSource,\n options: AgentCompileOptions = {}\n): CompiledAgentProject {\n return definition.kind === 'agent-definition'\n ? compileAgent(definition, options)\n : compileSnapshot(definition, options);\n}\n\nexport function collectActionVersionUuids(content: AgentV2CommitContentWire): string[] {\n const versionUuids = new Set<string>();\n for (const useSite of content.config.toolUseSites ?? []) {\n versionUuids.add(useSite.actionVersionUuid);\n }\n const beforeCallAction = content.config.automaticActions.beforeCallStart;\n if (beforeCallAction !== null) {\n versionUuids.add(beforeCallAction.actionVersionUuid);\n }\n for (const node of content.nodes) {\n if (node.type === 'action_node') {\n versionUuids.add(node.actionVersionUuid);\n }\n if (node.type === 'standard' && node.perTurnAction != null) {\n versionUuids.add(node.perTurnAction.actionVersionUuid);\n }\n }\n return [...versionUuids];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AA8MlB,SAAS,SAAS,OAAkD;AAClE,SAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,mBAAmB,OAG1B;AACA,QAAM,OAAO,MAAM;AACnB,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,UAAM,eAAe,KAAK,OAAO,CAAC,SAAS,SAAS,MAAM;AAC1D,QAAI,aAAa,WAAW,KAAK,OAAO,aAAa,CAAC,MAAM,UAAU;AACpE,aAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,MAAM,aAAa,CAAC,EAAE,GAAG,UAAU,KAAK,SAAS,MAAM,EAAE;AAAA,IACx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