{"version":3,"sources":["../src/attrs.js","../src/logger.ts","../src/File.ts","../src/index.ts","../src/ModelAPI.js","../src/database.ts","../src/auditing.js","../src/camelCasePlugin.js","../src/types/decimal.ts","../src/Duration.ts","../src/types/duration.ts","../src/types/file.ts","../src/types/registry.ts","../src/type-utils.ts","../src/jsonColumnValue.js","../src/tracing.js","../src/user_tracing.json","../src/dateColumnValue.ts","../src/parsing.js","../src/applyWhereConditions.js","../src/casing.js","../src/TimePeriod.js","../src/applyAdditionalQueryConstraints.js","../src/applyJoins.js","../src/QueryContext.js","../src/errors.js","../src/QueryBuilder.js","../src/UnionAPI.js","../src/TaskAPI.js","../src/auth/serviceToken.ts","../src/auth/serviceTokenStore.ts","../src/FlowsAPI.js","../src/auth/callerIdentityStore.ts","../src/integrationServer.js","../src/moduleExports.ts","../src/RequestHeaders.ts","../src/handleRequest.js","../src/permissions.ts","../src/consts.js","../src/tryExecuteFunction.js","../src/notifications/brandStore.ts","../src/runtimeMeta.ts","../src/actions/invocationStore.ts","../src/handleJob.js","../src/tryExecuteJob.js","../src/handleSubscriber.js","../src/tryExecuteSubscriber.js","../src/handleRoute.js","../src/handleFlow.ts","../src/tryExecuteFlow.js","../src/flows/ui/elements/input/signature.ts","../src/flows/tools.ts","../src/flows/index.ts","../src/flows/ui/elements/input/text.ts","../src/flows/ui/elements/input/number.ts","../src/flows/ui/elements/display/divider.ts","../src/flows/ui/elements/input/boolean.ts","../src/flows/ui/elements/display/markdown.ts","../src/flows/ui/elements/display/table.ts","../src/flows/ui/elements/select/one.ts","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/errors.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/optional.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/globals.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/functions.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/registry.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/operators.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/macros.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/overloads.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/type-checker.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/parser.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/options.js","../node_modules/.pnpm/@marcbachmann+cel-js@8.0.0/node_modules/@marcbachmann/cel-js/lib/evaluator.js","../src/flows/ui/cel/transpile.ts","../src/flows/ui/visibility.ts","../src/flows/ui/page.ts","../src/flows/disrupts.ts","../src/flows/ui/elements/display/banner.ts","../src/flows/ui/elements/display/image.ts","../src/flows/ui/elements/display/code.ts","../src/flows/ui/elements/display/grid.ts","../src/flows/ui/elements/display/list.ts","../src/flows/ui/elements/display/header.ts","../src/flows/ui/elements/display/keyValue.ts","../src/flows/ui/elements/select/table.ts","../src/flows/ui/elements/input/dataGrid.ts","../src/flows/ui/elements/format.ts","../src/flows/ui/elements/input/datePicker.ts","../src/flows/ui/elements/input/file.ts","../src/flows/ui/elements/input/imageCapture.ts","../src/flows/ui/elements/iterator.ts","../src/flows/ui/elements/interactive/print.ts","../src/flows/ui/elements/interactive/pickList.ts","../src/flows/errors.ts","../src/flows/ui/elements/input/scan.ts","../src/flows/ui/elements/display/file.ts","../src/flows/ui/elements/display/summary.ts","../src/flows/ui/elements/display/timeline.ts","../src/flows/progress.ts","../src/agents/engine.ts","../src/agents/engineResolver.ts","../src/agents/decision.ts","../src/agents/aiSdkEngine.ts","../src/agents/typesafeDecisionEngine.ts","../src/agents/extraction.ts","../src/agents/cloudflareExtractionEngine.ts","../src/flows/ui/complete.ts","../src/actions/ActionError.ts","../src/actions/ActionsAPI.ts","../src/notifications/email-template.tsx","../src/notifications/notify.ts","../src/sync/store.ts","../src/sync/walk.ts","../src/sync/records.ts","../src/sync/telemetry.ts","../src/sync/apply.ts","../src/sync/upsert.ts","../src/sync/recordApi.ts","../src/sync/index.ts","../src/experimental/index.ts","../src/experimental/ai.ts","../src/agents/schema.ts","../src/agents/llm.ts","../src/agents/decide.ts","../src/agents/extract.ts","../src/agents/defineAgent.ts","../src/agents/defineTool.ts","../src/experimental/testing.ts"],"sourcesContent":["// attrs.js holds the shared keel.* attribute vocabulary and the values of\n// keel.kind. It is deliberately a LEAF module: it imports nothing, so modules\n// that must not pull in tracing.js (and with it the OTel SDK bootstrap) can\n// still use the vocabulary. logger.ts is exactly that case - see the import\n// note at the top of logger.ts.\n//\n// tracing.js re-exports ATTRS, so `import { ATTRS } from \"./tracing\"` keeps\n// working everywhere it is used today.\n//\n// ATTRS mirrors the keel.* attribute vocabulary defined once in\n// telemetry/attrs.go (Go). Span attributes and canonical-event fields share\n// these same keys across both runtimes. telemetry/parity_test.go fails CI if\n// this object and the Go constants drift.\nconst ATTRS = {\n  ACTION: \"keel.action\",\n  ACTION_TYPE: \"keel.action.type\",\n  ACTION_IMPLEMENTATION: \"keel.action.implementation\",\n  MODEL: \"keel.model\",\n  API: \"keel.api\",\n  PROTOCOL: \"keel.protocol\",\n  KIND: \"keel.kind\",\n  LOG_SOURCE: \"keel.log.source\",\n  LOG_RAW: \"keel.log.raw\",\n  IDENTITY_ID: \"keel.identity.id\",\n  JOB_NAME: \"keel.job.name\",\n  JOB_ID: \"keel.job.id\",\n  EVENT_NAME: \"keel.event.name\",\n  EVENT_TARGET_TYPE: \"keel.event.target_type\",\n  EVENT_TARGET_ID: \"keel.event.target_id\",\n  SUBSCRIBER: \"keel.subscriber\",\n  SUBSCRIBER_ID: \"keel.subscriber.id\",\n  FLOW_NAME: \"keel.flow.name\",\n  FLOW_RUN_ID: \"keel.flow.run_id\",\n  STEP_NAME: \"keel.step.name\",\n  STEP_TYPE: \"keel.step.type\",\n  STEP_STATUS: \"keel.step.status\",\n  STEP_ID: \"keel.step.id\",\n  STEP_EXPECTED_ID: \"keel.step.expected_id\",\n  STEP_ELEMENT: \"keel.step.element\",\n  STEP_CALLBACK: \"keel.step.callback\",\n  TRIGGER: \"keel.trigger\",\n  GRAPHQL_QUERY_BYTES: \"keel.graphql.query_bytes\",\n  GRAPHQL_OPERATION: \"keel.graphql.operation\",\n  GRAPHQL_DEMAND: \"keel.graphql.demand\",\n  GRAPHQL_METADATA_DEMAND: \"keel.graphql.metadata_demand\",\n  PERMISSION_RESULT: \"keel.permission.result\",\n  VALIDATION_RESULT: \"keel.validation.result\",\n  VALIDATION_RULES: \"keel.validation.rules\",\n  VALIDATION_RULES_FAILED: \"keel.validation.rules_failed\",\n  VALIDATION_FAILED_RULES: \"keel.validation.failed_rules\",\n  PERMISSION_REASON: \"keel.permission.reason\",\n  INTERNAL: \"keel.internal\",\n  STATUS: \"keel.status\",\n  ATTEMPT: \"keel.attempt\",\n  EVENTS_GENERATED: \"keel.events.generated\",\n  FLOW_STATUS: \"keel.flow.status\",\n  FLOW_DURATION_MS: \"keel.flow.duration_ms\",\n  MIGRATION_DRY_RUN: \"keel.migration.dry_run\",\n  MIGRATION_CHANGES: \"keel.migration.changes\",\n  MIGRATION_CHANGES_ADDED: \"keel.migration.changes_added\",\n  MIGRATION_CHANGES_REMOVED: \"keel.migration.changes_removed\",\n  MIGRATION_CHANGES_MODIFIED: \"keel.migration.changes_modified\",\n  MIGRATION_BACKFILL_TABLE: \"keel.migration.backfill.table\",\n  MIGRATION_BACKFILL_WINDOWS: \"keel.migration.backfill.windows\",\n  MIGRATION_BACKFILL_ROWS_CORRECTED: \"keel.migration.backfill.rows_corrected\",\n  MIGRATION_BACKFILL_CHECKPOINT: \"keel.migration.backfill.checkpoint\",\n  MIGRATION_BACKFILL_LOCK_RETRIES: \"keel.migration.backfill.lock_retries\",\n  MIGRATION_BACKFILL_RESUMED_FROM: \"keel.migration.backfill.resumed_from\",\n  MIGRATION_BACKFILL_DURATION_MS: \"keel.migration.backfill.duration_ms\",\n  MIGRATION_BACKFILL_ELAPSED_MS: \"keel.migration.backfill.elapsed_ms\",\n  MIGRATION_BACKFILL_STOP_REASON: \"keel.migration.backfill.stop_reason\",\n  MIGRATION_DEFERRED_BUDGET_MS: \"keel.migration.deferred.budget_ms\",\n  MIGRATION_DEFERRED_DONE: \"keel.migration.deferred.done\",\n  MIGRATION_DEFERRED_PENDING: \"keel.migration.deferred.pending\",\n  MIGRATION_GUARDED_DDL_ATTEMPT: \"keel.migration.guarded_ddl.attempt\",\n  MIGRATION_GUARDED_DDL_STATEMENT: \"keel.migration.guarded_ddl.statement\",\n  EVENT_PAYLOAD_BYTES: \"keel.event.payload_bytes\",\n  RESPONSE_CODE: \"keel.response.code\",\n  RESPONSE_BYTES: \"keel.response.bytes\",\n\n  // --- Checkpoint K additions (consistency finishing) ---\n  CREATE_FIELDS: \"keel.create.fields\",\n  UPDATE_FIELDS: \"keel.update.fields\",\n  UPDATE_WHERE: \"keel.update.where\",\n  GET_EMBEDS: \"keel.get.embeds\",\n  LIST_WHERE: \"keel.list.where\",\n  LIST_ORDER_BY: \"keel.list.orderBy\",\n  LIST_SEARCH: \"keel.list.search\",\n  LIST_FACETS: \"keel.list.facets\",\n  LIST_PAGE_FIRST: \"keel.list.page.first\",\n  LIST_PAGE_HAS_CURSOR: \"keel.list.page.hasCursor\",\n  LIST_PAGE_LAST: \"keel.list.page.last\",\n  LIST_PAGE_LIMIT: \"keel.list.page.limit\",\n  LIST_PAGE_OFFSET: \"keel.list.page.offset\",\n  LIST_RESULTS_COUNT: \"keel.list.results.count\",\n  AUTH_ISSUER: \"keel.auth.issuer\",\n  IDENTITY_EXTERNAL_ID: \"keel.identity.external_id\",\n  USER_ID: \"keel.user.id\",\n  AUTH_EMAIL_LOOKUP: \"keel.auth.email_lookup\",\n  AUTH_USER_PROVISIONING: \"keel.auth.user_provisioning\",\n  OUTCOME: \"keel.outcome\",\n  AUTH_ERROR: \"keel.auth.error\",\n  AUTH_ERROR_DESCRIPTION: \"keel.auth.error_description\",\n  FLOW_COUNT: \"keel.flow.count\",\n  FLOW_METADATA_ONLY: \"keel.flow.metadata_only\",\n  FLOW_SCHEDULED_AT: \"keel.flow.scheduled_at\",\n  MIGRATION_STATEMENTS: \"keel.migration.statements\",\n  TIMEZONE: \"keel.timezone\",\n  FILES_DELETED: \"keel.files.deleted\",\n  UPLOAD_ACTION: \"keel.upload.action\",\n  UPLOAD_FIELD: \"keel.upload.field\",\n  STEP_VALUE_BYTES: \"keel.step.value_bytes\",\n  STEP_RENDERED: \"keel.step.rendered\",\n\n  // --- Checkpoint L additions (user-facing tracing, spec step 1) ---\n  AUDIENCE: \"keel.audience\",\n  SPAN_TYPE: \"keel.span.type\",\n  QUEUED_MS: \"keel.queued_ms\",\n\n  // --- Ledger record actions (written by the Go runtime only) ---\n  LEDGER: \"keel.ledger\",\n  LEDGER_GROUP: \"keel.ledger.group\",\n  LEDGER_ENTRIES: \"keel.ledger.entries\",\n  LEDGER_POSITIONS: \"keel.ledger.positions\",\n\n  INTEGRATION: \"keel.integration\",\n  INTEGRATION_ATTEMPTS: \"keel.integration.attempts\",\n  INTEGRATION_TOKEN_REFRESH: \"keel.integration.token_refresh\",\n  INTEGRATION_REQUEST_ID: \"keel.integration.request_id\",\n  INTEGRATION_REPLAY_OF: \"keel.integration.replay_of\",\n  INTEGRATION_REQUESTS_SHED: \"keel.integration.requests.shed\",\n  INTEGRATION_REQUESTS_DELETED: \"keel.integration.requests.deleted\",\n\n  // --- Integration sync engine (src/sync) ---\n  SYNC_INTEGRATION: \"keel.sync.integration\",\n  SYNC_ENTITY: \"keel.sync.entity\",\n  SYNC_SCOPE: \"keel.sync.scope\",\n  SYNC_STRATEGY: \"keel.sync.strategy\",\n  SYNC_PHASE: \"keel.sync.phase\",\n  SYNC_MODE: \"keel.sync.mode\",\n  SYNC_PAGE: \"keel.sync.page\",\n  SYNC_RECONCILE_ID: \"keel.sync.reconcile_id\",\n  SYNC_RECORDS_FETCHED: \"keel.sync.records.fetched\",\n  SYNC_RECORDS_CHANGED: \"keel.sync.records.changed\",\n  SYNC_RECORDS_APPLIED: \"keel.sync.records.applied\",\n  SYNC_RECORDS_FAILED: \"keel.sync.records.failed\",\n  SYNC_RECORDS_SKIPPED: \"keel.sync.records.skipped\",\n  SYNC_RECORDS_TOMBSTONED: \"keel.sync.records.tombstoned\",\n  SYNC_RECORDS_LIVE: \"keel.sync.records.live\",\n  SYNC_RECORDS_ATTEMPTED: \"keel.sync.records.attempted\",\n  SYNC_RECORD_EXTERNAL_ID: \"keel.sync.record.external_id\",\n  SYNC_RECORD_ATTEMPTS: \"keel.sync.record.attempts\",\n  SYNC_RATE_LIMIT_REMAINING: \"keel.sync.rate_limit.remaining\",\n  SYNC_RATE_LIMIT_RESERVE: \"keel.sync.rate_limit.reserve\",\n  SYNC_ACTION: \"keel.sync.action\",\n};\n\n// KINDS mirrors the values of ATTRS.KIND defined in telemetry/attrs.go (the\n// Kind* constants). REQUEST/JOB/SUBSCRIBER/FLOW_RUN/MIGRATION name a unit of\n// work; LOG marks a structured log record emitted by a runtime's own logger.\n// telemetry/parity_test.go's TestGoTSKindValueParity fails CI if these drift.\nconst KINDS = {\n  REQUEST: \"request\",\n  JOB: \"job\",\n  SUBSCRIBER: \"subscriber\",\n  FLOW_RUN: \"flow_run\",\n  MIGRATION: \"migration\",\n  LOG: \"log\",\n};\n\n// LOG_SOURCE_FUNCTIONS is this runtime's value for ATTRS.LOG_SOURCE - mirrors\n// telemetry.LogSourceFunctions (Go).\nconst LOG_SOURCE_FUNCTIONS = \"functions\";\n\nexport { ATTRS, KINDS, LOG_SOURCE_FUNCTIONS };\n","import * as opentelemetry from \"@opentelemetry/api\";\nimport { ATTRS, KINDS, LOG_SOURCE_FUNCTIONS } from \"./attrs\";\n\n// logger.ts is a small structured logger for the functions-runtime's OWN\n// internal messages (database connection diagnostics, file-storage\n// failures, flow bookkeeping warnings, ...). It is deliberately separate\n// from the user-facing console.log/console.error monkey-patching in\n// tracing.js (which turns *user* logs into span events) - that patching is\n// untouched by this module.\n//\n// Mirrors the shape of the Go runtime's telemetry.Event/telemetry.Logger\n// (telemetry/event.go, telemetry/handler.go): one JSON line per call,\n// trace/span correlation from the active OTel span, KEEL_LOG_LEVEL gating,\n// and reserved top-level keys that call sites can't clobber.\n//\n// NOTE ON IMPORTS: this module must not import tracing.js (or anything that\n// imports tracing.js) beyond the plain @opentelemetry/api surface used here.\n// attrs.js is the one exception, and is safe by construction: it is a leaf\n// module that imports nothing, so taking the shared keel.* vocabulary from it\n// cannot drag in the OTel SDK bootstrap.\n// tracing.js's forceFlush() logs through a small inline writer instead of\n// importing `log` from here, specifically to avoid a tracing.js <-> logger.ts\n// import cycle (tracing.js is imported by nearly everything, including this\n// file's own callers).\n\nexport type LogLevel = \"trace\" | \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type LogFields = Record<string, unknown>;\n\nconst LEVEL_ORDER: Record<LogLevel, number> = {\n  trace: 0,\n  debug: 1,\n  info: 2,\n  warn: 3,\n  error: 4,\n};\n\nconst DEFAULT_LEVEL: LogLevel = \"info\";\n\n// Reserved top-level keys owned by the logger itself. Fields passed by\n// call sites must not override these - mirrors Go's\n// telemetry.Event.Set/reservedEventKeys (telemetry/event.go), which\n// silently drops writes to the same key set.\nconst RESERVED_KEYS = new Set<string>([\n  \"level\",\n  \"msg\",\n  \"time\",\n  \"trace_id\",\n  \"span_id\",\n  // Stamped by write() below to identify the record to the Go side (the CLI's\n  // logs pane routes on keel.kind). A call site must never be able to pass\n  // e.g. keel.kind: \"request\" and have a log line render as a canonical event.\n  ATTRS.KIND,\n  ATTRS.LOG_SOURCE,\n]);\n\nfunction isLogLevel(value: string): value is LogLevel {\n  return value in LEVEL_ORDER;\n}\n\n// currentLevel is read at call time (not cached at module init) so that\n// tests can flip KEEL_LOG_LEVEL between assertions without re-importing the\n// module. The performance cost of an env lookup per log call is irrelevant\n// here - this is not a hot path like CEL evaluation.\nfunction currentLevel(): LogLevel {\n  const raw = process.env.KEEL_LOG_LEVEL?.toLowerCase();\n  return raw && isLogLevel(raw) ? raw : DEFAULT_LEVEL;\n}\n\nfunction enabled(level: LogLevel): boolean {\n  return LEVEL_ORDER[level] >= LEVEL_ORDER[currentLevel()];\n}\n\n// serializeError turns an Error into a plain object for JSON output.\n// Only `name` and `message` are included by default: a stack trace can\n// contain file paths and (depending on what threw) fragments of the data\n// that caused the failure, which is noise-at-best and a CWE-532-adjacent\n// information disclosure risk at worst for logs that flow to a shared\n// destination at the default (info) level. The stack is genuinely useful\n// for local debugging, so it's included at debug level and below, where a\n// developer has explicitly opted into more verbose output.\nfunction serializeError(\n  err: Error,\n  level: LogLevel\n): { name: string; message: string; stack?: string } {\n  const out: { name: string; message: string; stack?: string } = {\n    name: err.name,\n    message: err.message,\n  };\n  if (LEVEL_ORDER[level] <= LEVEL_ORDER.debug) {\n    out.stack = err.stack;\n  }\n  return out;\n}\n\nfunction serializeFields(\n  fields: LogFields | undefined,\n  level: LogLevel\n): Record<string, unknown> {\n  const out: Record<string, unknown> = {};\n  if (!fields) {\n    return out;\n  }\n\n  for (const [key, value] of Object.entries(fields)) {\n    if (RESERVED_KEYS.has(key)) {\n      // Silently drop, mirroring Go's Event.Set - a call site accidentally\n      // passing `time` or `trace_id` in fields shouldn't be able to spoof\n      // the logger's own framing.\n      continue;\n    }\n    out[key] = value instanceof Error ? serializeError(value, level) : value;\n  }\n\n  return out;\n}\n\nfunction write(level: LogLevel, msg: string, fields?: LogFields): void {\n  if (!enabled(level)) {\n    return;\n  }\n\n  const record: Record<string, unknown> = {\n    level,\n    msg,\n    time: new Date().toISOString(),\n    // Identify the record as a structured log line from this runtime. `keel\n    // run` routes on keel.kind to decide that a line belongs in the logs pane\n    // rather than inline on the main view (see engine/functionlogs.go), and\n    // deployed log pipelines can filter on the same pair.\n    [ATTRS.KIND]: KINDS.LOG,\n    [ATTRS.LOG_SOURCE]: LOG_SOURCE_FUNCTIONS,\n  };\n\n  const spanContext = opentelemetry.trace.getActiveSpan()?.spanContext();\n  if (spanContext && opentelemetry.isSpanContextValid(spanContext)) {\n    record.trace_id = spanContext.traceId;\n    record.span_id = spanContext.spanId;\n  }\n\n  Object.assign(record, serializeFields(fields, level));\n\n  process.stdout.write(JSON.stringify(record) + \"\\n\");\n}\n\nexport const log = {\n  debug: (msg: string, fields?: LogFields) => write(\"debug\", msg, fields),\n  info: (msg: string, fields?: LogFields) => write(\"info\", msg, fields),\n  warn: (msg: string, fields?: LogFields) => write(\"warn\", msg, fields),\n  error: (msg: string, fields?: LogFields) => write(\"error\", msg, fields),\n};\n","import {\n  S3Client,\n  PutObjectCommand,\n  GetObjectCommand,\n  DeleteObjectCommand,\n  PutObjectCommandInput,\n} from \"@aws-sdk/client-s3\";\nimport { fromEnv } from \"@aws-sdk/credential-providers\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { useDatabase } from \"./database\";\nimport { DatabaseError } from \"./errors\";\nimport KSUID from \"ksuid\";\nimport { log } from \"./logger\";\n\ntype MimeType =\n  | \"application/json\"\n  | \"application/gzip\"\n  | \"application/pdf\"\n  | \"application/rtf\"\n  | \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n  | \"application/vnd.openxmlformats-officedocument.presentationml.presentation\"\n  | \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"\n  | \"application/vnd.ms-excel\"\n  | \"application/vnd.ms-powerpoint\"\n  | \"application/msword\"\n  | \"application/zip\"\n  | \"application/xml\"\n  | \"application/x-7z-compressed\"\n  | \"application/x-tar\"\n  | \"image/gif\"\n  | \"image/jpeg\"\n  | \"image/svg+xml\"\n  | \"image/png\"\n  | \"text/html\"\n  | \"text/csv\"\n  | \"text/javascript\"\n  | \"text/plain\"\n  | \"text/calendar\"\n  | (string & {});\n\n// Type Declarations\nexport type InlineFileConstructor = {\n  filename: string;\n  contentType: MimeType;\n};\n\nexport type FileDbRecord = {\n  key: string;\n  filename: string;\n  contentType: string;\n  size: number;\n};\n\nexport class FileSizeLimitError extends Error {\n  constructor(\n    public readonly actualBytes: number,\n    public readonly maxBytes: number\n  ) {\n    super(`File is ${actualBytes} bytes, exceeding the ${maxBytes} byte limit`);\n    this.name = \"FileSizeLimitError\";\n  }\n}\n\n// Implementation\nconst s3Client: S3Client | null = (() => {\n  if (!process.env.KEEL_FILES_BUCKET_NAME) {\n    return null;\n  }\n\n  const endpoint = process.env.KEEL_S3_ENDPOINT;\n  if (endpoint) {\n    return new S3Client({\n      region: process.env.KEEL_REGION,\n      credentials: {\n        accessKeyId: \"keelstorage\",\n        secretAccessKey: \"keelstorage\",\n      },\n      endpoint: endpoint,\n    });\n  }\n\n  const testEndpoint = process.env.TEST_AWS_ENDPOINT;\n  if (testEndpoint) {\n    return new S3Client({\n      region: process.env.KEEL_REGION,\n      credentials: {\n        accessKeyId: \"test\",\n        secretAccessKey: \"test\",\n      },\n      endpointProvider: () => {\n        return {\n          url: new URL(testEndpoint),\n        };\n      },\n    });\n  }\n\n  return new S3Client({\n    region: process.env.KEEL_REGION,\n    credentials: fromEnv(),\n  });\n})();\n\n// Rewrites the origin of a pre-signed URL when KEEL_FILES_DOMAIN is set.\n// This is used when running behind a reverse proxy that exposes the storage server\n// on a different domain than localhost.\nexport function rewriteFilesDomain(url: URL): URL {\n  const domain = process.env.KEEL_FILES_DOMAIN;\n  if (domain) {\n    const override = new URL(domain);\n    url.protocol = override.protocol;\n    url.hostname = override.hostname;\n    url.port = override.port;\n\n    const overridePath = override.pathname.replace(/\\/+$/, \"\");\n    if (overridePath && overridePath !== \"/\") {\n      url.pathname = overridePath + url.pathname;\n    }\n  }\n  return url;\n}\n\n// Percent-encodes a string per RFC 5987 (the value used by the filename*\n// parameter). encodeURIComponent already encodes everything outside the\n// attr-char set except ' ( ) *, so we encode those too. Over-encoding is valid.\nfunction encodeRFC5987(value: string): string {\n  return encodeURIComponent(value).replace(\n    /['()*]/g,\n    (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase()\n  );\n}\n\n// Builds an RFC 6266 Content-Disposition header value for a presigned download\n// URL. When a filename is present it is emitted both as a quoted ascii fallback\n// (with quotes, backslashes, control and non-ascii characters replaced) and as\n// an RFC 5987 filename* parameter carrying the exact UTF-8 name. When no\n// filename is given the bare disposition is returned so browsers fall back to\n// the object key, matching the previous behaviour.\nexport function buildContentDisposition(\n  disposition: \"inline\" | \"attachment\",\n  filename?: string\n): string {\n  // The disposition can arrive from an untyped boundary (e.g. a Keel Text?\n  // input cast to the union), so normalise anything that isn't exactly\n  // \"attachment\" to \"inline\" rather than emitting an invalid header type.\n  const type = disposition === \"attachment\" ? \"attachment\" : \"inline\";\n\n  if (!filename || filename.trim() === \"\") {\n    return type;\n  }\n\n  const asciiFallback = filename.replace(/[^\\x20-\\x7e]|[\"\\\\]/g, \"_\");\n  return `${type}; filename=\"${asciiFallback}\"; filename*=UTF-8''${encodeRFC5987(\n    filename\n  )}`;\n}\n\nexport class InlineFile {\n  protected _filename: string;\n  protected _contentType: MimeType;\n  protected _contents: Blob | null;\n\n  constructor(input: InlineFileConstructor) {\n    this._filename = input.filename;\n    this._contentType = input.contentType;\n    this._contents = null;\n  }\n\n  static fromDataURL(dataURL: string): InlineFile {\n    const info = dataURL.split(\",\")[0].split(\":\")[1];\n    const data = dataURL.split(\",\")[1];\n    const mimeType = info.split(\";\")[0];\n    const name = decodeDataURLParam(info.split(\";\")[1].split(\"=\")[1]) || \"file\";\n    const buffer = Buffer.from(data, \"base64\");\n    const file = new InlineFile({ filename: name, contentType: mimeType });\n    file.write(buffer);\n\n    return file;\n  }\n\n  // Gets size of the file's contents in bytes\n  get size(): number {\n    if (this._contents) {\n      return this._contents.size;\n    }\n    return 0;\n  }\n\n  // Gets the media type of the file contents\n  get contentType(): string {\n    return this._contentType;\n  }\n\n  // Gets the name of the file\n  get filename(): string {\n    return this._filename;\n  }\n\n  // Write the files contents from a buffer\n  write(buffer: Buffer): void {\n    this._contents = new Blob([\n      new Uint8Array(\n        buffer.buffer as ArrayBuffer,\n        buffer.byteOffset,\n        buffer.byteLength\n      ),\n    ]);\n  }\n\n  // Reads the contents of the file as a buffer\n  async read(maxBytes?: number): Promise<Buffer> {\n    if (!this._contents) {\n      throw new Error(\"No contents to read\");\n    }\n    if (maxBytes !== undefined && this._contents.size > maxBytes) {\n      throw new FileSizeLimitError(this._contents.size, maxBytes);\n    }\n    const arrayBuffer = await this._contents.arrayBuffer();\n    return Buffer.from(arrayBuffer);\n  }\n\n  // Encodes the file's in-memory contents as a data-URL, mirroring the format\n  // fromDataURL parses (`data:<mime>;name=<filename>;base64,<data>`). The name\n  // is percent-encoded, as RFC 2397 parameter values must be: a raw space, ';'\n  // or ',' would end the parameter early, and the Go runtime's parser rejects\n  // the whole URL (\"invalid attachment data-url\" from notify.email).\n  async toDataURL(): Promise<string> {\n    const buffer = await this.read();\n    const base64 = buffer.toString(\"base64\");\n    return `data:${this._contentType};name=${encodeURIComponent(\n      this._filename\n    )};base64,${base64}`;\n  }\n\n  // Persists the file\n  async store(expires: Date | null = null): Promise<File> {\n    const content = await this.read();\n    const key = KSUID.randomSync().string;\n\n    await storeFile(\n      content,\n      key,\n      this._filename,\n      this._contentType,\n      this.size,\n      expires\n    );\n\n    return new File({\n      key: key,\n      size: this.size,\n      filename: this.filename,\n      contentType: this.contentType,\n    });\n  }\n}\n\nexport class File extends InlineFile {\n  private _key: string;\n  private _size: number;\n\n  constructor(input: Partial<FileDbRecord>) {\n    super({\n      filename: input.filename || \"\",\n      contentType: input.contentType || \"\",\n    });\n    this._key = input.key || \"\";\n    this._size = input.size || 0;\n  }\n\n  // Creates a new instance from the database record\n  static fromDbRecord(input: FileDbRecord): File {\n    return new File({\n      key: input.key,\n      filename: input.filename,\n      size: input.size,\n      contentType: input.contentType,\n    });\n  }\n\n  get size(): number {\n    return this._size;\n  }\n\n  // Gets the stored key\n  get key(): string {\n    return this._key;\n  }\n\n  get isPublic(): boolean {\n    return false; // Implement as needed\n  }\n\n  async read(maxBytes?: number): Promise<Buffer> {\n    if (this._contents) {\n      if (maxBytes !== undefined && this._contents.size > maxBytes) {\n        throw new FileSizeLimitError(this._contents.size, maxBytes);\n      }\n      const arrayBuffer = await this._contents.arrayBuffer();\n      return Buffer.from(arrayBuffer);\n    }\n\n    if (!s3Client) {\n      throw new Error(\"S3 client is required\");\n    }\n\n    const params = {\n      Bucket: process.env.KEEL_FILES_BUCKET_NAME,\n      Key: \"files/\" + this.key,\n    };\n    const command = new GetObjectCommand(params);\n    const abortController = new AbortController();\n    const response = await s3Client.send(command, {\n      abortSignal: abortController.signal,\n    });\n    if (\n      maxBytes !== undefined &&\n      response.ContentLength !== undefined &&\n      response.ContentLength > maxBytes\n    ) {\n      abortController.abort();\n      throw new FileSizeLimitError(response.ContentLength, maxBytes);\n    }\n    const blob = await response.Body!.transformToByteArray();\n    if (maxBytes !== undefined && blob.byteLength > maxBytes) {\n      throw new FileSizeLimitError(blob.byteLength, maxBytes);\n    }\n    return Buffer.from(blob);\n  }\n\n  async store(expires: Date | null = null): Promise<File> {\n    if (this._contents) {\n      const contents = await this.read();\n      await storeFile(\n        contents,\n        this.key,\n        this.filename,\n        this.contentType,\n        this.size,\n        expires\n      );\n    }\n    return this;\n  }\n\n  // Generates a presigned download URL.\n  //\n  // By default the browser previews the file inline and, when saved, uses the\n  // file's own filename. Pass `contentDisposition: \"attachment\"` to force a\n  // download, or `filename` to override the suggested name.\n  async getPresignedUrl(options?: {\n    contentDisposition?: \"inline\" | \"attachment\";\n    filename?: string;\n  }): Promise<URL> {\n    if (!s3Client) {\n      throw new Error(\"S3 client is required\");\n    }\n\n    const disposition = options?.contentDisposition ?? \"inline\";\n    const filename = options?.filename ?? this.filename;\n\n    const command = new GetObjectCommand({\n      Bucket: process.env.KEEL_FILES_BUCKET_NAME,\n      Key: \"files/\" + this.key,\n      ResponseContentDisposition: buildContentDisposition(\n        disposition,\n        filename\n      ),\n    });\n\n    const url = await getSignedUrl(s3Client, command, { expiresIn: 60 * 60 });\n\n    return rewriteFilesDomain(new URL(url));\n  }\n\n  // Generates a presigned upload URL. If the file doesn't have a key, a new one will be generated\n  async getPresignedUploadUrl(): Promise<URL> {\n    if (!s3Client) {\n      throw new Error(\"S3 client is required\");\n    }\n\n    if (!this.key) {\n      this._key = KSUID.randomSync().string;\n    }\n\n    const command = new PutObjectCommand({\n      Bucket: process.env.KEEL_FILES_BUCKET_NAME,\n      Key: \"files/\" + this.key,\n    });\n\n    const url = await getSignedUrl(s3Client, command, { expiresIn: 60 * 60 });\n\n    return rewriteFilesDomain(new URL(url));\n  }\n\n  // Persists the file\n  toDbRecord(): FileDbRecord {\n    return {\n      key: this.key,\n      filename: this.filename,\n      contentType: this.contentType,\n      size: this.size,\n    };\n  }\n\n  toJSON(): FileDbRecord {\n    return this.toDbRecord();\n  }\n}\n\n// S3 user metadata is sent as an HTTP header (x-amz-meta-filename), and Node\n// refuses to send a header value holding any character above U+00FF\n// (ERR_INVALID_CHAR) - so storing a file named, say, \"Capture d’écran.png\"\n// (a curly apostrophe, or an accent in decomposed form as macOS writes it)\n// threw before the request left the process. A name that is not printable\n// ASCII is therefore sent as an RFC 2047 encoded-word, the form S3 documents\n// for non-ASCII user metadata; the Go storer decodes it when it reads the name\n// back. Printable-ASCII names are sent unchanged.\nexport function encodeFilenameMetadata(filename: string): string {\n  if (/^[\\x20-\\x7e]*$/.test(filename)) {\n    return filename;\n  }\n  return `=?UTF-8?B?${Buffer.from(filename, \"utf8\").toString(\"base64\")}?=`;\n}\n\n// Data-URL parameter values are percent-encoded (RFC 2397). A value that is\n// not valid percent-encoding - a name sent raw by an older client, e.g.\n// \"100%.pdf\" - is kept exactly as sent.\nfunction decodeDataURLParam(value: string | undefined): string | undefined {\n  if (value === undefined) {\n    return undefined;\n  }\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n\nasync function storeFile(\n  contents: Buffer,\n  key: string,\n  filename: string,\n  contentType: string,\n  size: number,\n  expires: Date | null\n): Promise<void> {\n  if (!s3Client) {\n    throw new Error(\"S3 client is required\");\n  }\n\n  const params: PutObjectCommandInput = {\n    Bucket: process.env.KEEL_FILES_BUCKET_NAME,\n    Key: \"files/\" + key,\n    Body: contents,\n    ContentType: contentType,\n    ContentDisposition: `attachment; filename=\"${encodeURIComponent(\n      filename\n    )}\"`,\n    Metadata: {\n      filename: encodeFilenameMetadata(filename),\n    },\n    ACL: \"private\",\n  };\n\n  if (expires) {\n    if (expires instanceof Date) {\n      params.Expires = expires;\n    } else {\n      log.warn(\"invalid expires value, skipping expires parameter\");\n    }\n  }\n\n  const command = new PutObjectCommand(params);\n  try {\n    await s3Client.send(command);\n  } catch (error) {\n    // Only the AWS error's name/message are logged (via the logger's Error\n    // serialisation) - never the full error object, which can carry request\n    // metadata we don't want in logs.\n    log.error(\"error uploading file\", { error });\n    throw error;\n  }\n}\n\nexport type FileWriteTypes = InlineFile | File;\n\n// deleteStoredFile removes the object for the given key from storage.\nexport async function deleteStoredFile(key: string): Promise<void> {\n  if (!s3Client) {\n    throw new Error(\"S3 client is required\");\n  }\n\n  await s3Client.send(\n    new DeleteObjectCommand({\n      Bucket: process.env.KEEL_FILES_BUCKET_NAME,\n      Key: \"files/\" + key,\n    })\n  );\n}\n","import { ModelAPI } from \"./ModelAPI\";\nimport { UnionAPI } from \"./UnionAPI\";\nimport { TaskAPI } from \"./TaskAPI\";\nimport { FlowsAPI } from \"./FlowsAPI\";\nimport { createIntegrationServer } from \"./integrationServer\";\nimport {\n  defineModuleExports,\n  registerModuleExports,\n  buildModuleAPI,\n} from \"./moduleExports\";\nimport { RequestHeaders } from \"./RequestHeaders\";\nimport { handleRequest } from \"./handleRequest\";\nimport { handleJob } from \"./handleJob\";\nimport { handleSubscriber } from \"./handleSubscriber\";\nimport { handleRoute } from \"./handleRoute\";\nimport { handleFlow } from \"./handleFlow\";\nimport KSUID from \"ksuid\";\nimport { useDatabase } from \"./database\";\nimport {\n  Permissions,\n  PERMISSION_STATE,\n  checkBuiltInPermissions,\n} from \"./permissions\";\nimport * as tracing from \"./tracing\";\nimport { ActionsAPI } from \"./actions/ActionsAPI\";\nimport {\n  ActionError,\n  isActionError,\n  ACTION_ERROR_CODES,\n} from \"./actions/ActionError\";\nimport { InlineFile, File } from \"./File\";\nimport { Duration } from \"./Duration\";\nimport { ErrorPresets } from \"./errors\";\nimport type { TraceAPI } from \"./traceTypes\";\nimport { createNotifier } from \"./notifications\";\nimport { log } from \"./logger\";\n\nexport type {\n  TraceAPI,\n  TraceAttributeValue,\n  TraceAttributes,\n} from \"./traceTypes\";\n\nexport type {\n  ModuleExportsContext,\n  ModuleExportsFactory,\n} from \"./moduleExports\";\n\nexport type { ActionInputs, ActionPaths } from \"./actions/ActionsAPI\";\nexport type {\n  ActionErrorCode,\n  ActionValidationErrorData,\n  ActionLedgerErrorData,\n  ActionLedgerGuardKind,\n  ActionLedgerGuardErrorData,\n  ActionLedgerBalanceGuardError,\n  ActionLedgerAmountGuardError,\n  ActionLedgerRelatedRowGuardError,\n} from \"./actions/ActionError\";\n\n// Export JS files\nexport {\n  ModelAPI,\n  UnionAPI,\n  TaskAPI,\n  FlowsAPI,\n  ActionsAPI,\n  ActionError,\n  isActionError,\n  ACTION_ERROR_CODES,\n  handleRequest,\n  handleJob,\n  handleSubscriber,\n  handleRoute,\n  KSUID,\n  Permissions,\n  PERMISSION_STATE,\n  checkBuiltInPermissions,\n  tracing,\n  ErrorPresets,\n  createIntegrationServer,\n  defineModuleExports,\n  registerModuleExports,\n  buildModuleAPI,\n};\nexport const createTraceAPI = tracing.createTraceAPI;\n\nexport function ksuid() {\n  return KSUID.randomSync().string;\n}\n\n// Export TS files\n\nexport {\n  RequestHeaders,\n  Duration,\n  useDatabase,\n  File,\n  InlineFile,\n  handleFlow,\n  log,\n};\nexport const notify = createNotifier();\nexport { createNotifier, type NotifyApi } from \"./notifications\";\nexport type {\n  EmailInput,\n  EmailContent,\n  EmailDetail,\n  EmailRecipients,\n  EmailRecipientGroup,\n  RecipientUser,\n  RecipientIdentity,\n} from \"./notifications\";\nexport * from \"./flows\";\nexport * from \"./sync\";\nexport {\n  type UIApiResponses,\n  type VisibilityExpression,\n} from \"./flows/ui/index\";\n\n// Experimental agent + LLM primitives, namespaced so their pre-release status\n// is explicit at every call site (e.g. experimental.ai.defineTool, experimental.ai.generate).\nexport * as experimental from \"./experimental\";\n\n// Re-export zod so flow implementations can use schema validation without\n// adding zod as a direct project dependency.\nexport { z } from \"zod\";\n\n// *****************************\n// Static Types\n// *****************************\n\nexport type IDWhereCondition = {\n  equals?: string | null;\n  notEquals?: string | null;\n  oneOf?: string[] | null;\n};\n\nexport type StringWhereCondition = {\n  startsWith?: string | null;\n  endsWith?: string | null;\n  oneOf?: string[] | null;\n  contains?: string | null;\n  equals?: string | null;\n  notEquals?: string | null;\n};\n\nexport type BooleanWhereCondition = {\n  equals?: boolean | null;\n  notEquals?: boolean | null;\n};\n\nexport type NumberWhereCondition = {\n  greaterThan?: number | null;\n  greaterThanOrEquals?: number | null;\n  lessThan?: number | null;\n  lessThanOrEquals?: number | null;\n  equals?: number | null;\n  notEquals?: number | null;\n};\n\nexport type DurationWhereCondition = {\n  greaterThan?: DurationString | null;\n  greaterThanOrEquals?: DurationString | null;\n  lessThan?: DurationString | null;\n  lessThanOrEquals?: DurationString | null;\n  equals?: DurationString | null;\n  notEquals?: DurationString | null;\n};\n\nexport type DateWhereCondition = {\n  equals?: Date | string | null;\n  equalsRelative?: RelativeDateString | null;\n  before?: Date | string | null;\n  beforeRelative?: RelativeDateString | null;\n  onOrBefore?: Date | string | null;\n  after?: Date | string | null;\n  afterRelative?: RelativeDateString | null;\n  onOrAfter?: Date | string | null;\n};\n\nexport type DateQueryInput = {\n  equals?: string | null;\n  before?: string | null;\n  onOrBefore?: string | null;\n  after?: string | null;\n  onOrAfter?: string | null;\n};\n\nexport type TimestampQueryInput = {\n  before?: string | null;\n  onOrBefore?: string | null;\n  after?: string | null;\n  onOrAfter?: string | null;\n  equalsRelative?: RelativeDateString | null;\n  beforeRelative?: RelativeDateString | null;\n  afterRelative?: RelativeDateString | null;\n};\n\nexport type StringArrayWhereCondition = {\n  equals?: string[] | null;\n  notEquals?: string[] | null;\n  any?: StringArrayQueryWhereCondition | null;\n  all?: StringArrayQueryWhereCondition | null;\n};\n\nexport type StringArrayQueryWhereCondition = {\n  equals?: string | null;\n  notEquals?: string | null;\n};\n\nexport type NumberArrayWhereCondition = {\n  equals?: number[] | null;\n  notEquals?: number[] | null;\n  any?: NumberArrayQueryWhereCondition | null;\n  all?: NumberArrayQueryWhereCondition | null;\n};\n\nexport type NumberArrayQueryWhereCondition = {\n  greaterThan?: number | null;\n  greaterThanOrEquals?: number | null;\n  lessThan?: number | null;\n  lessThanOrEquals?: number | null;\n  equals?: number | null;\n  notEquals?: number | null;\n};\n\nexport type BooleanArrayWhereCondition = {\n  equals?: boolean[] | null;\n  notEquals?: boolean[] | null;\n  any?: BooleanArrayQueryWhereCondition | null;\n  all?: BooleanArrayQueryWhereCondition | null;\n};\n\nexport type BooleanArrayQueryWhereCondition = {\n  equals?: boolean | null;\n  notEquals?: boolean | null;\n};\n\nexport type DateArrayWhereCondition = {\n  equals?: Date[] | null;\n  notEquals?: Date[] | null;\n  any?: DateArrayQueryWhereCondition | null;\n  all?: DateArrayQueryWhereCondition | null;\n};\n\nexport type DateArrayQueryWhereCondition = {\n  greaterThan?: Date | null;\n  greaterThanOrEquals?: Date | null;\n  lessThan?: Date | null;\n  lessThanOrEquals?: number | null;\n  equals?: Date | null;\n  notEquals?: Date | null;\n};\n\nexport type ContextAPI = {\n  headers: RequestHeaders;\n  response: Response;\n  isAuthenticated: boolean;\n  trace: TraceAPI;\n  now(): Date;\n};\n\nexport type Response = {\n  headers: Headers;\n  status?: number;\n};\n\nexport type PageInfo = {\n  startCursor: string;\n  endCursor: string;\n  totalCount: number;\n  hasNextPage: boolean;\n  count: number;\n  pageNumber?: number;\n};\n\n/**\n * Partial PageInfo for manual pagination - all fields optional with sensible defaults.\n * - count: defaults to results.length\n * - totalCount: defaults to results.length\n * - hasNextPage: defaults to false\n * - startCursor: defaults to first result's id or \"\"\n * - endCursor: defaults to last result's id or \"\"\n * - pageNumber: optional, no default\n */\nexport type PartialPageInfo = {\n  startCursor?: string;\n  endCursor?: string;\n  totalCount?: number;\n  hasNextPage?: boolean;\n  count?: number;\n  pageNumber?: number;\n};\n\n/**\n * Result type for list operations with pagination info.\n * Used when returning manually paginated results from beforeQuery or afterQuery hooks.\n */\nexport type ListResult<M> = {\n  results: Array<M>;\n  pageInfo: PartialPageInfo;\n};\n\nexport type SortDirection = \"asc\" | \"desc\" | \"ASC\" | \"DESC\";\n\ndeclare class NotFoundError extends Error {}\ndeclare class BadRequestError extends Error {}\ndeclare class UnknownError extends Error {}\n\nexport type Errors = {\n  /**\n   * Returns a 404 HTTP status with an optional message.\n   * This error indicates that the requested resource could not be found.\n   */\n  NotFound: typeof NotFoundError;\n  /**\n   * Returns a 400 HTTP status with an optional message.\n   * This error indicates that the request made by the client is invalid or malformed.\n   */\n  BadRequest: typeof BadRequestError;\n  /**\n   * Returns a 500 HTTP status with an optional message.\n   * This error indicates that an unexpected condition was encountered, preventing the server from fulfilling the request.\n   */\n  Unknown: typeof UnknownError;\n};\n\nexport type FunctionConfig = {\n  /**\n   * All DB calls within the function will be executed within a transaction.\n   * The transaction is rolled back if the function throws an error.\n   */\n  dbTransaction?: boolean;\n};\n\nexport type FuncWithConfig<T> = T & {\n  config: FunctionConfig;\n};\n\ntype unit =\n  | \"year\"\n  | \"years\"\n  | \"month\"\n  | \"months\"\n  | \"day\"\n  | \"days\"\n  | \"hour\"\n  | \"hours\"\n  | \"minute\"\n  | \"minutes\"\n  | \"second\"\n  | \"seconds\";\ntype direction = \"next\" | \"last\";\ntype completed = \"complete\";\ntype value = number;\n\nexport type RelativeDateString =\n  | \"now\"\n  | \"today\"\n  | \"tomorrow\"\n  | \"yesterday\"\n  | `this ${unit}`\n  | `${direction} ${unit}`\n  | `${direction} ${value} ${unit}`\n  | `${direction} ${value} ${completed} ${unit}`;\n\ntype dateDuration =\n  | `${number}Y${number}M${number}D` // Example: 1Y2M10D\n  | `${number}Y${number}M` // Example: 1Y2M\n  | `${number}Y${number}D` // Example: 1Y10D\n  | `${number}M${number}D` // Example: 10M2D\n  | `${number}Y` // Example: 1Y\n  | `${number}M` // Example: 1M\n  | `${number}D`; // Example: 2D\n\ntype timeDuration =\n  | `${number}H${number}M${number}S` // Example: 2H30M\n  | `${number}H${number}M` // Example: 2H30M\n  | `${number}M${number}S` // Example: 2M30S\n  | `${number}H${number}S` // Example: 2H30S\n  | `${number}H` // Example: 2H\n  | `${number}M` // Example: 30M\n  | `${number}S`; // Example: 30S\n\nexport type DurationString =\n  | `P${dateDuration}T${timeDuration}`\n  | `P${dateDuration}`\n  | `PT${timeDuration}`;\n\nexport type TaskStatus =\n  | \"NEW\"\n  | \"ASSIGNED\"\n  | \"STARTED\"\n  | \"COMPLETED\"\n  | \"CANCELLED\"\n  | \"DEFERRED\";\n\nexport type Task = {\n  id: string;\n  topic: string;\n  status: TaskStatus;\n  deferredUntil?: Date;\n  createdAt: Date;\n  updatedAt: Date;\n  assignedToUserId?: string;\n  assignedToTeam?: string;\n  assignedAt?: Date;\n  resolvedAt?: Date;\n  flowRunId?: string;\n};\n\nexport type TaskCreateOptions = {\n  deferredUntil?: Date;\n};\n\nexport type FlowRunStatus =\n  | \"PENDING\"\n  | \"RUNNING\"\n  | \"COMPLETED\"\n  | \"FAILED\"\n  | \"CANCELLED\";\n\nexport type FlowRunStep = {\n  id: string;\n  name?: string;\n  status?: string;\n  data?: any;\n};\n\nexport type FlowRun = {\n  id: string;\n  name: string;\n  status: FlowRunStatus;\n  inputs?: any;\n  outputs?: any;\n  steps?: FlowRunStep[];\n  pendingStep?: FlowRunStep;\n  createdAt?: Date;\n  updatedAt?: Date;\n  completedAt?: Date;\n};\n\nexport type FlowListOptions = {\n  limit?: number;\n  offset?: number;\n};\n\nexport type FlowListResult = {\n  results: FlowRun[];\n  pageInfo: {\n    totalCount: number;\n    hasNextPage: boolean;\n  };\n};\n\nexport type SignedLinkOptions<Inputs = any> = {\n  inputs?: Inputs;\n  expiresAt?: Date;\n  reusable?: boolean;\n};\n\nexport type SignedLinkStatus = \"active\" | \"revoked\" | \"expired\";\n\n// A persisted shareable signed link for a flow. The shareable url is exposed so the link can be\n// re-shared; the raw token/hash is never exposed. url is absent for links minted before the token\n// was persisted.\nexport type SignedLinkRecord = {\n  id: string;\n  flowName: string;\n  inputs: Record<string, any> | null;\n  reusable: boolean;\n  createdBy: string | null;\n  expiresAt: Date | null;\n  usedCount: number;\n  revokedAt: Date | null;\n  createdAt: Date;\n  updatedAt: Date;\n  status: SignedLinkStatus;\n  url?: string;\n};\n\nexport type ListSignedLinksOptions = {\n  status?: SignedLinkStatus;\n};\n\nexport type ListSignedLinksResult = {\n  results: SignedLinkRecord[];\n};\n\n// The signed-link management namespace exposed on a flow's SDK API as `flows.<flow>.signedLinks`.\n// Only flows declared with @externalAccess get this property (see the SDK type generation), so\n// referencing it on a non-shareable flow is a compile error.\n// By default every operation authenticates with a first-party `flows` service token the runtime\n// trusts, so backend code can manage links without satisfying the flow's `share` permission.\n// Chaining withIdentity()/withAuthToken() switches to user-scoped auth, where the flow's\n// @permission(actions: [share]) rule is enforced.\nexport type SignedLinksAPI<Inputs = any> = {\n  // Mint a signed link that lets an external, unauthenticated actor execute this flow.\n  create(options?: SignedLinkOptions<Inputs>): Promise<SignedLinkRecord>;\n  // List the signed links minted for this flow, optionally filtered by status.\n  list(options?: ListSignedLinksOptions): Promise<ListSignedLinksResult>;\n  // Revoke a signed link by id so it can no longer be opened. Idempotent.\n  revoke(linkId: string): Promise<SignedLinkRecord>;\n};\n","import { sql } from \"kysely\";\nimport { useDatabase, deferFileDeletion } from \"./database\";\nimport { transformRichDataTypes, isReferencingExistingRecord } from \"./parsing\";\nimport { isPlainObject } from \"./type-utils\";\nimport { QueryBuilder } from \"./QueryBuilder\";\nimport { QueryContext } from \"./QueryContext\";\nimport { applyWhereConditions } from \"./applyWhereConditions\";\nimport { applyJoins } from \"./applyJoins\";\nimport { allTypes, transformValueForWrite } from \"./types/registry\";\n\nimport {\n  applyLimit,\n  applyOffset,\n  applyOrderBy,\n} from \"./applyAdditionalQueryConstraints\";\nimport { camelCaseObject, snakeCaseObject, upperCamelCase } from \"./casing\";\nimport * as tracing from \"./tracing\";\nimport { DatabaseError } from \"./errors\";\n\n// isWritableRichInstance is a synchronous pre-check so scalar values that\n// don't match any registered rich type skip the async transformValueForWrite\n// call entirely, preserving the historical synchronous assignment for plain\n// values. Some auditing behaviour (set_config('...', true) scoped to the\n// current transaction) depends on write queries for plain values being\n// dispatched without an intervening microtask tick; adding an unconditional\n// await here would change that ordering even though the value is unchanged.\nfunction isWritableRichInstance(value) {\n  return allTypes.some((def) => def.isInstance?.(value));\n}\n\n/**\n * RelationshipConfig is a simple representation of a model field that\n * is a relationship. It is used by applyJoins and applyWhereConditions\n * to build the correct query.\n * @typedef {{\n *  relationshipType: \"belongsTo\" | \"hasMany\",\n *  foreignKey: string,\n *  referencesTable: string,\n * }} RelationshipConfig\n *\n * TableConfig is an object where the keys are relationship field names\n * (which don't exist in the database) and the values are RelationshipConfig\n * objects describing that relationship.\n * @typedef {Object.<string, RelationshipConfig} TableConfig\n *\n * TableConfigMap is mapping of database table names to TableConfig objects\n * @typedef {Object.<string, TableConfig>} TableConfigMap\n */\n\nclass ModelAPI {\n  /**\n   * @param {string} tableName The name of the table this API is for\n   * @param {Function} _ Used to be a function that returns the default values for a row in this table. No longer used.\n   * @param {TableConfigMap} tableConfigMap\n   */\n  constructor(tableName, _, tableConfigMap = {}, fileFieldsMap = {}) {\n    this._tableName = tableName;\n    this._tableConfigMap = tableConfigMap;\n    this._fileFields = fileFieldsMap[tableName] || {};\n    this._modelName = upperCamelCase(this._tableName);\n  }\n\n  async create(values) {\n    const modelName = this._modelName;\n\n    return tracing.withDbQuerySpan(modelName, \"create\", () => {\n      const db = useDatabase();\n      return create(\n        db,\n        this._tableName,\n        this._tableConfigMap,\n        snakeCaseObject(values)\n      );\n    });\n  }\n\n  async findOne(where = {}) {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(this._modelName, \"findOne\", async (span) => {\n      let builder = db\n        .selectFrom(this._tableName)\n        .distinctOn(`${this._tableName}.id`)\n        .selectAll(this._tableName);\n\n      const context = new QueryContext([this._tableName], this._tableConfigMap);\n\n      builder = applyJoins(context, builder, where);\n      builder = applyWhereConditions(context, builder, where);\n\n      span.setAttribute(\n        \"db.statement\",\n        tracing.truncateSQL(builder.compile().sql)\n      );\n      const row = await builder.executeTakeFirst();\n      if (!row) {\n        return null;\n      }\n\n      return transformRichDataTypes(camelCaseObject(row));\n    });\n  }\n\n  async findMany(params) {\n    const db = useDatabase();\n    const where = params?.where || {};\n\n    return tracing.withDbQuerySpan(\n      this._modelName,\n      \"findMany\",\n      async (span) => {\n        const context = new QueryContext(\n          [this._tableName],\n          this._tableConfigMap\n        );\n\n        let builder = db\n          .selectFrom((qb) => {\n            // We need to wrap this query as a sub query in the selectFrom because you cannot apply a different order by column when using distinct(id)\n            let builder = qb\n              .selectFrom(this._tableName)\n              .distinctOn(`${this._tableName}.id`)\n              .selectAll(this._tableName);\n\n            builder = applyJoins(context, builder, where);\n            builder = applyWhereConditions(context, builder, where);\n\n            builder = builder.as(this._tableName);\n\n            return builder;\n          })\n          .selectAll();\n\n        // The only constraints added to the main query are the orderBy, limit and offset as they are performed on the \"outer\" set\n        if (params?.limit) {\n          builder = applyLimit(context, builder, params.limit);\n        }\n\n        if (params?.offset) {\n          builder = applyOffset(context, builder, params.offset);\n        }\n\n        if (\n          params?.orderBy !== undefined &&\n          Object.keys(params?.orderBy).length > 0\n        ) {\n          builder = applyOrderBy(\n            context,\n            builder,\n            this._tableName,\n            params.orderBy\n          );\n        } else {\n          builder = builder.orderBy(`${this._tableName}.id`);\n        }\n\n        const query = builder;\n\n        span.setAttribute(\n          \"db.statement\",\n          tracing.truncateSQL(query.compile().sql)\n        );\n        const rows = await builder.execute();\n        return rows.map((x) => transformRichDataTypes(camelCaseObject(x)));\n      }\n    );\n  }\n\n  async update(where, values) {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(this._modelName, \"update\", async (span) => {\n      const fileColumns = Object.keys(values || {}).filter(\n        (k) => k in this._fileFields\n      );\n      const existingFileRows =\n        fileColumns.length > 0\n          ? await this._selectExistingFileValues(where, fileColumns)\n          : [];\n\n      let builder = db.updateTable(this._tableName).returningAll();\n\n      // process input values\n      const keys = values ? Object.keys(values) : [];\n      const row = {};\n\n      for (const key of keys) {\n        const value = values[key];\n        if (Array.isArray(value)) {\n          row[key] = await Promise.all(\n            value.map(async (item) => {\n              const result = await transformValueForWrite(item);\n              return result.value;\n            })\n          );\n        } else if (isWritableRichInstance(value)) {\n          const result = await transformValueForWrite(value);\n          row[key] = result.value;\n        } else {\n          row[key] = value;\n        }\n      }\n\n      builder = builder.set(snakeCaseObject(row));\n\n      const context = new QueryContext([this._tableName], this._tableConfigMap);\n\n      // TODO: support joins for update\n      builder = applyWhereConditions(context, builder, where);\n\n      span.setAttribute(\n        \"db.statement\",\n        tracing.truncateSQL(builder.compile().sql)\n      );\n\n      try {\n        const row = await builder.executeTakeFirstOrThrow();\n        const result = transformRichDataTypes(camelCaseObject(row));\n        this._deferReplacedFiles(existingFileRows, fileColumns, result);\n        return result;\n      } catch (e) {\n        throw new DatabaseError(e);\n      }\n    });\n  }\n\n  async delete(where) {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(this._modelName, \"delete\", async (span) => {\n      const fileColumns = Object.keys(this._fileFields);\n      const existingFileRows =\n        fileColumns.length > 0\n          ? await this._selectExistingFileValues(where, fileColumns)\n          : [];\n\n      let builder = db.deleteFrom(this._tableName).returning([\"id\"]);\n\n      const context = new QueryContext([this._tableName], this._tableConfigMap);\n\n      // TODO: support joins for delete\n      builder = applyWhereConditions(context, builder, where);\n\n      span.setAttribute(\n        \"db.statement\",\n        tracing.truncateSQL(builder.compile().sql)\n      );\n      try {\n        const row = await builder.executeTakeFirstOrThrow();\n        this._deferReplacedFiles(existingFileRows, fileColumns, null);\n        return row.id;\n      } catch (e) {\n        throw new DatabaseError(e);\n      }\n    });\n  }\n\n  where(where) {\n    const db = useDatabase();\n\n    let builder = db\n      .selectFrom(this._tableName)\n      .distinctOn(`${this._tableName}.id`)\n      .selectAll(this._tableName);\n\n    const context = new QueryContext([this._tableName], this._tableConfigMap);\n\n    builder = applyJoins(context, builder, where);\n    builder = applyWhereConditions(context, builder, where);\n\n    return new QueryBuilder(this._tableName, context, builder);\n  }\n\n  // Reads the current file-column values for rows matched by `where`.\n  async _selectExistingFileValues(where, fileColumns) {\n    if (fileColumns.length === 0) {\n      return [];\n    }\n    const db = useDatabase();\n    let builder = db.selectFrom(this._tableName).selectAll(this._tableName);\n    const context = new QueryContext([this._tableName], this._tableConfigMap);\n    builder = applyWhereConditions(context, builder, where);\n    const rows = await builder.execute();\n    return rows.map((x) => transformRichDataTypes(camelCaseObject(x)));\n  }\n\n  // Defers deletion of every old file key in existingRows that is not still\n  // referenced by newRow.\n  _deferReplacedFiles(existingRows, fileColumns, newRow) {\n    const retained = new Set(\n      collectFileKeys(newRow ? [newRow] : [], fileColumns)\n    );\n    for (const key of collectFileKeys(existingRows, fileColumns)) {\n      if (!retained.has(key)) {\n        deferFileDeletion(key);\n      }\n    }\n  }\n}\n\n// prepareInsertRow turns the (snake_cased) values passed to a create into the row to insert:\n// rich Keel types are transformed for writing, belongs-to relations become their foreign key\n// (creating the related record first when it is not a reference to an existing one) and\n// has-many relations are returned separately so the caller can insert them after the parent\n// exists. Shared by ModelAPI.create and the sync engine's syncUpsert so both write values\n// identically.\n//\n// Deliberately not an async function: when every value is plain it returns the result\n// synchronously, and only returns a promise when a value genuinely needs async work. See\n// isWritableRichInstance above - the audit context's transaction-scoped set_config depends on\n// plain-value writes being dispatched without an intervening microtask tick.\nfunction prepareInsertRow(conn, tableName, tableConfigs, values) {\n  const keys = values ? Object.keys(values) : [];\n  const tableConfig = tableConfigs[tableName] || {};\n  const hasManyRecords = [];\n  const row = {};\n  const asyncWork = [];\n\n  for (const key of keys) {\n    const value = values[key];\n    const columnConfig = tableConfig[key];\n\n    if (!columnConfig) {\n      if (Array.isArray(value)) {\n        asyncWork.push(async () => {\n          row[key] = await Promise.all(\n            value.map(async (item) => {\n              const result = await transformValueForWrite(item);\n              return result.value;\n            })\n          );\n        });\n      } else if (isWritableRichInstance(value)) {\n        asyncWork.push(async () => {\n          const result = await transformValueForWrite(value);\n          row[key] = result.value;\n        });\n      } else {\n        row[key] = value;\n      }\n      continue;\n    }\n\n    switch (columnConfig.relationshipType) {\n      case \"belongsTo\":\n        if (!isPlainObject(value)) {\n          throw new Error(\n            `non-object provided for field ${key} of ${tableName}`\n          );\n        }\n\n        if (isReferencingExistingRecord(value)) {\n          row[columnConfig.foreignKey] = value.id;\n          break;\n        }\n\n        asyncWork.push(async () => {\n          const created = await create(\n            conn,\n            columnConfig.referencesTable,\n            tableConfigs,\n            value\n          );\n          row[columnConfig.foreignKey] = created.id;\n        });\n        break;\n\n      case \"hasMany\":\n        if (!Array.isArray(value)) {\n          throw new Error(\n            `non-array provided for has-many field ${key} of ${tableName}`\n          );\n        }\n        for (const v of value) {\n          hasManyRecords.push({\n            key,\n            value: v,\n            columnConfig,\n          });\n        }\n        break;\n      default:\n        throw new Error(\n          `unsupported relationship type - ${tableName}.${key} (${columnConfig.relationshipType})`\n        );\n    }\n  }\n\n  if (asyncWork.length === 0) {\n    return { row, hasManyRecords };\n  }\n\n  return (async () => {\n    // Sequential, matching the order the original create loop awaited these in.\n    for (const work of asyncWork) {\n      await work();\n    }\n    return { row, hasManyRecords };\n  })();\n}\n\nasync function create(conn, tableName, tableConfigs, values) {\n  try {\n    let query = conn.insertInto(tableName);\n\n    const keys = values ? Object.keys(values) : [];\n    const tableConfig = tableConfigs[tableName] || {};\n    let hasManyRecords = [];\n\n    if (keys.length === 0) {\n      // See https://github.com/kysely-org/kysely/issues/685#issuecomment-1711240534\n      query = query.expression(sql`default values`);\n    } else {\n      let prepared = prepareInsertRow(conn, tableName, tableConfigs, values);\n      if (prepared instanceof Promise) {\n        prepared = await prepared;\n      }\n      hasManyRecords = prepared.hasManyRecords;\n      query = query.values(prepared.row);\n    }\n\n    const created = await query.returningAll().executeTakeFirstOrThrow();\n\n    await Promise.all(\n      hasManyRecords.map(async ({ key, value, columnConfig }) => {\n        if (!isPlainObject(value)) {\n          throw new Error(\n            `non-object provided for field ${key} of ${tableName}`\n          );\n        }\n\n        if (isReferencingExistingRecord(value)) {\n          throw new Error(\n            `nested update as part of create not supported for ${key} of ${tableConfig}`\n          );\n        }\n\n        return create(conn, columnConfig.referencesTable, tableConfigs, {\n          ...value,\n          [columnConfig.foreignKey]: created.id,\n        });\n      })\n    );\n\n    let result = created;\n    if (hasManyRecords.length > 0) {\n      result = await conn\n        .selectFrom(tableName)\n        .selectAll(tableName)\n        .where(`${tableName}.id`, \"=\", created.id)\n        .executeTakeFirstOrThrow();\n    }\n\n    return transformRichDataTypes(result);\n  } catch (e) {\n    throw new DatabaseError(e);\n  }\n}\n\n// collectFileKeys gathers the storage keys from File values across the given\n// rows for the given (camelCase) file columns.\nfunction collectFileKeys(rows, fileColumns) {\n  const keys = [];\n  for (const row of rows || []) {\n    if (!row) continue;\n    for (const col of fileColumns) {\n      const v = row[col];\n      if (!v) continue;\n      if (Array.isArray(v)) {\n        for (const f of v) if (f?.key) keys.push(f.key);\n      } else if (v.key) {\n        keys.push(v.key);\n      }\n    }\n  }\n  return keys;\n}\n\nexport { ModelAPI, DatabaseError, create, prepareInsertRow, collectFileKeys };\n","import { Kysely, PostgresDialect, KyselyConfig } from \"kysely\";\nimport * as neon from \"@neondatabase/serverless\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { AuditContextPlugin } from \"./auditing\";\nimport { KeelCamelCasePlugin } from \"./camelCasePlugin\";\nimport {\n  Pool,\n  Client,\n  types as pgTypes,\n  defaults as pgDefaults,\n  PoolConfig,\n  PoolClient,\n} from \"pg\";\nimport { withSpan, SpanKind, truncateSQL } from \"./tracing\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport { log } from \"./logger\";\nimport WebSocket from \"ws\";\nimport { readFileSync } from \"node:fs\";\nimport { parseJsonColumnValue } from \"./jsonColumnValue\";\nimport {\n  parseDateColumnValue,\n  parseDateArrayColumnValue,\n} from \"./dateColumnValue\";\nimport { allTypes } from \"./types/registry\";\n\ninterface DatabaseContext {\n  transaction?: Kysely<any>;\n  sDb?: Kysely<any>;\n}\n\ninterface DatabaseClientConfig {\n  connString?: string;\n}\n\n// Default server-side statement timeout. Must be comfortably below the\n// functions Lambda timeout (840s) so a slow query surfaces as a catchable\n// error (pg code 57014) instead of an uncatchable Lambda kill.\nconst DEFAULT_STATEMENT_TIMEOUT_MS = 780_000;\n\nfunction getStatementTimeoutMs(): number {\n  const parsed = parseInt(process.env.KEEL_DB_STATEMENT_TIMEOUT ?? \"\", 10);\n  return Number.isFinite(parsed) && parsed > 0\n    ? parsed\n    : DEFAULT_STATEMENT_TIMEOUT_MS;\n}\n\nconst dbInstance = new AsyncLocalStorage<DatabaseContext>();\n\nconst fileCleanupStore = new AsyncLocalStorage<Set<string>>();\n\n// deferFileDeletion records a storage key to delete once the current\n// transaction commits. No-op when called outside a withDatabase context.\nfunction deferFileDeletion(key: string): void {\n  fileCleanupStore.getStore()?.add(key);\n}\n\n// flushFileDeletions deletes the given keys from storage, best-effort.\n// File is imported lazily to avoid a circular import (File.ts imports useDatabase).\nasync function flushFileDeletions(keys: Set<string>): Promise<void> {\n  if (keys.size === 0) {\n    return;\n  }\n  const { deleteStoredFile } = await import(\"./File\");\n  for (const key of keys) {\n    try {\n      await deleteStoredFile(key);\n    } catch (e) {\n      // Avoid logging the raw storage key (CWE-532): keys identify private\n      // customer uploads and should not leak into application logs.\n      log.error(\"failed to delete orphaned file from storage\");\n    }\n  }\n}\n\n// used to establish a singleton for our vitest environment\nlet vitestDb: Kysely<any> | null = null;\n\n// withDatabase is responsible for setting the correct database client in our AsyncLocalStorage\n// so that the the code in a custom function uses the correct client.\n// For GET and LIST action types, no transaction is used, but for\n// actions that mutate data such as CREATE, DELETE & UPDATE, all of the code inside\n// the user's custom function is wrapped in a transaction so we can rollback\n// the transaction if something goes wrong.\n// withDatabase shouldn't be exposed in the public api of the sdk\nasync function withDatabase<T>(\n  db: Kysely<any>,\n  requiresTransaction: boolean,\n  cb: (context: DatabaseContext) => Promise<T>\n): Promise<T> {\n  const pending = new Set<string>();\n\n  if (requiresTransaction) {\n    // Pin READ COMMITTED explicitly rather than relying on the cluster/database default.\n    // Computed-field cascades depend on each recompute, after waiting on a row lock, seeing\n    // the latest committed state of sibling rows. Under REPEATABLE READ, concurrent sibling\n    // writes inside overlapping transactions hard-fail with a serialization error (40001)\n    // instead of correctly cascading.\n    const result = await db\n      .transaction()\n      .setIsolationLevel(\"read committed\")\n      .execute(async (transaction) => {\n        return dbInstance.run({ transaction }, () =>\n          fileCleanupStore.run(pending, () => cb({ transaction }))\n        );\n      });\n    // Reached only if the transaction committed.\n    await flushFileDeletions(pending);\n    return result;\n  }\n\n  const result = await db.connection().execute(async (sDb) => {\n    return dbInstance.run({ sDb }, () => {\n      return fileCleanupStore.run(pending, () => cb({ sDb }));\n    });\n  });\n  await flushFileDeletions(pending);\n  return result;\n}\n\nfunction isInDatabaseTransaction(): boolean {\n  return dbInstance.getStore()?.transaction !== undefined;\n}\n\n// useDatabase will retrieve the database client set by withDatabase from the local storage\nfunction useDatabase(): Kysely<any> {\n  // retrieve the instance of the database client from the store which is aware of\n  // which context the current connection to the db is running in - e.g does the context\n  // require a transaction or not?\n  const fromStore = dbInstance.getStore();\n  if (fromStore?.transaction) {\n    return fromStore.transaction;\n  }\n  if (fromStore?.sDb) {\n    return fromStore.sDb;\n  }\n\n  // if the NODE_ENV is 'test' then we know we are inside of the vitest environment\n  // which covers any test files ending in *.test.ts. Custom function code runs in a different node process which will not have this environment variable. Tests written using our testing\n  // framework call actions (and in turn custom function code) over http using the ActionExecutor class\n  if (\"NODE_ENV\" in process.env && process.env.NODE_ENV == \"test\") {\n    if (!vitestDb) {\n      vitestDb = createDatabaseClient();\n    }\n    return vitestDb;\n  }\n\n  // If we've gotten to this point, then we know that we are in a custom function runtime server\n  // context and we haven't been able to retrieve the in-context instance of Kysely, which means we should throw an error.\n  log.error(\"useDatabase called outside of a function context\");\n  throw new Error(\"useDatabase must be called within a function\");\n}\n\n// reusableClients caches one Kysely instance (and its underlying connection pool)\n// per connection string, so that a long-lived functions process can reuse a warm\n// pool across invocations instead of paying a cold connect on every one.\n//\n// This is gated behind KEEL_FUNCTIONS_DB_POOL_REUSE and only enabled by the local\n// test/dev runtime, where the functions process is long-lived and the database\n// connection is stable for the whole run. In a deployed (Lambda) environment the\n// flag is unset, so every invocation still creates and destroys its own client -\n// leaving the existing freeze/thaw semantics untouched.\nconst reusableClients = new Map<string, Kysely<any>>();\n\nfunction dbPoolReuseEnabled(): boolean {\n  return process.env.KEEL_FUNCTIONS_DB_POOL_REUSE === \"true\";\n}\n\n// createDatabaseClient will return an instance of Kysely. Every instance of Kysely\n// represents an individual connection pool to the database.\n// When pool reuse is enabled it returns a cached, shared instance per connection\n// string; otherwise it returns a brand new instance (the default behaviour).\n// not to be exported externally from our sdk - consumers should use useDatabase\nfunction createDatabaseClient(config: DatabaseClientConfig = {}): Kysely<any> {\n  const connString = config.connString ?? process.env.KEEL_DB_CONN;\n\n  if (dbPoolReuseEnabled() && connString) {\n    const existing = reusableClients.get(connString);\n    if (existing) {\n      return existing;\n    }\n  }\n\n  const kyseleyConfig: KyselyConfig = {\n    dialect: getDialect(config.connString),\n    plugins: [\n      // ensures that the audit context data is written to Postgres configuration parameters\n      new AuditContextPlugin(),\n      // allows users to query using camelCased versions of the database column names, which\n      // should match the names we use in our schema.\n      // We're using an extended version of Kysely's CamelCasePlugin which avoids changing keys of objects that represent\n      // rich data formats, specific to Keel (e.g. Duration)\n      new KeelCamelCasePlugin(),\n    ],\n    log(event: any) {\n      if (event.level === \"query\") {\n        log.debug(\"database query\", { sql: truncateSQL(event.query.sql) });\n      }\n    },\n  };\n\n  const client = new Kysely(kyseleyConfig);\n\n  if (dbPoolReuseEnabled() && connString) {\n    // The per-invocation handlers (handleRequest/handleSubscriber/handleJob/\n    // handleFlow/handleRoute) call db.destroy() in a finally block. When reusing a\n    // shared pool we must keep it alive across invocations, so make destroy() a\n    // no-op for cached clients. Each invocation still acquires its own connection/\n    // transaction from the pool (via withDatabase), so per-request isolation is\n    // unchanged. The pool is released when the long-lived local process exits.\n    client.destroy = async () => {};\n    reusableClients.set(connString, client);\n  }\n\n  return client;\n}\n\n// Connecting a pooled client used to open its own \"Database Connect\" span per\n// connection - high volume, low diagnostic value (the connection itself\n// isn't a unit of work worth its own trace node). It's now a span event on\n// whatever span is active when the connection is opened (Task 8 of the\n// observability overhaul, trace noise reduction).\nclass InstrumentedPool extends Pool {\n  connect(...args: any): Promise<PoolClient> {\n    const _super = super.connect.bind(this);\n    opentelemetry.trace.getActiveSpan()?.addEvent(\"database.connect\", {\n      dialect: process.env[\"KEEL_DB_CONN_TYPE\"],\n    });\n    return _super.apply(null, args) as unknown as Promise<PoolClient>;\n  }\n}\n\nclass InstrumentedNeonServerlessPool extends neon.Pool {\n  async connect(...args: any): Promise<neon.PoolClient> {\n    const _super = super.connect.bind(this);\n    opentelemetry.trace.getActiveSpan()?.addEvent(\"database.connect\", {\n      dialect: process.env[\"KEEL_DB_CONN_TYPE\"],\n    });\n    return _super.apply(null, args) as unknown as Promise<neon.PoolClient>;\n  }\n}\n\nconst txStatements = {\n  begin: \"db.transaction.begin\",\n  commit: \"db.transaction.commit\",\n  rollback: \"db.transaction.rollback\",\n};\n\nclass InstrumentedClient extends Client {\n  async query(...args: any): Promise<any> {\n    const _super = super.query.bind(this);\n    const sql = args[0];\n\n    let sqlAttribute = false;\n    let spanName = txStatements[sql.toLowerCase() as keyof typeof txStatements];\n    if (!spanName) {\n      spanName = \"db.query\";\n      sqlAttribute = true;\n    }\n\n    return withSpan(\n      spanName,\n      function (span: any) {\n        if (sqlAttribute) {\n          // Checkpoint L follow-up: this driver-level span carries the raw\n          // SQL statement - internal detail, not customer-visible. The\n          // \"db.query\" archetype's user-facing span is the outer,\n          // model-scoped one from tracing.js's withDbQuerySpan (which knows\n          // keel.model/db.operation.name); a single logical query here can\n          // fan out into several of these driver spans, so marking this one\n          // too would produce more than one user-facing db.query span per\n          // logical query. See withDbQuerySpan's comment.\n          span.setAttribute(\"db.statement\", truncateSQL(args[0]));\n          span.setAttribute(\"db.system\", process.env[\"KEEL_DB_CONN_TYPE\"]);\n        }\n        return _super.apply(null, args);\n      },\n      { kind: SpanKind.CLIENT }\n    );\n  }\n}\n\n// A connection dropped by the server - a Postgres FATAL (e.g. 57P01\n// \"terminating connection due to administrator command\" during a Neon restart\n// or failover) or a closed Neon WebSocket - surfaces as an \"error\" event on the\n// pooled client. When that client is idle, pg-pool removes it and re-emits the\n// error on the Pool (see pg-pool's makeIdleListener). With no \"error\" listener\n// on the Pool, the EventEmitter throws, which the Lambda runtime logs as an\n// \"Uncaught Exception\" and which exits the process mid-invocation. A dropped\n// idle connection is recoverable - the pool opens a fresh one on the next\n// checkout - so record it and keep the process alive instead of crashing.\nfunction attachPoolErrorHandler(pool: Pool | neon.Pool): void {\n  pool.on(\"error\", (err: Error) => {\n    log.warn(\"database pool connection error\", {\n      code: (err as { code?: string }).code,\n      error: err,\n    });\n  });\n}\n\n// Postgres OID for DATE[]; pg-types' builtins (and so its TypeId type) only\n// lists scalar types.\nconst DATE_ARRAY_OID = 1182 as (typeof pgTypes.builtins)[\"DATE\"];\n\nfunction getDialect(connString?: string): PostgresDialect {\n  const dbConnType = process.env.KEEL_DB_CONN_TYPE;\n  switch (dbConnType) {\n    case \"pg\": {\n      // Register type parsers for all field types with a Postgres OID (e.g.\n      // NUMERIC, INTERVAL): see https://kysely.dev/docs/recipes/data-types#configuring-runtime-javascript-types\n      for (const t of allTypes) {\n        if (t.pgOid && t.pgParse) {\n          pgTypes.setTypeParser(t.pgOid, t.pgParse);\n        }\n      }\n      // Mark JSON and JSONB values before the casing plugin sees result rows.\n      // This lets us camelCase top-level column names while preserving the\n      // developer-defined keys inside JSON payloads.\n      pgTypes.setTypeParser(pgTypes.builtins.JSON, parseJsonColumnValue);\n      pgTypes.setTypeParser(pgTypes.builtins.JSONB, parseJsonColumnValue);\n      // Read and write DATE values as midnight UTC, regardless of the\n      // process's timezone (see dateColumnValue.ts).\n      pgTypes.setTypeParser(pgTypes.builtins.DATE, parseDateColumnValue);\n      pgTypes.setTypeParser(DATE_ARRAY_OID, parseDateArrayColumnValue);\n      // This flag is global to the pg module, so it also applies to any other\n      // code in this process that uses pg directly (e.g. a custom function\n      // that imports pg). On Lambda, which runs in UTC, it changes nothing.\n      pgDefaults.parseInputDatesAsUTC = true;\n\n      const poolConfig: PoolConfig = {\n        Client: InstrumentedClient,\n        // Increased idle time before closing a connection in the local pool (from 10s default).\n        // Establising a new connection on (almost) every functions query can be expensive, so this\n        // will reduce having to open connections as regularly. https://node-postgres.com/apis/pool\n        //\n        // NOTE: We should consider setting this to 0 (i.e. never pool locally) and open and close\n        // connections with each invocation. This is because the freeze/thaw nature of lambdas can cause problems\n        // with long-lived connections - see https://github.com/brianc/node-postgres/issues/2718\n        // Once we're \"fully regional\" this should not be a performance problem anymore.\n        //\n        // Although I doubt we will run into these freeze/thaw issues if idleTimeoutMillis is always shorter than the\n        // time is takes for a lambda to freeze (which is not a constant, but could be as short as several minutes,\n        // https://www.pluralsight.com/resources/blog/cloud/how-long-does-aws-lambda-keep-your-idle-functions-around-before-a-cold-start)\n        idleTimeoutMillis: 50000,\n        // When one pool is shared by every invocation of a long-lived local process (keel test), a\n        // chain of nested action calls holds one connection per level while it waits. The runtime\n        // refuses chains deeper than 10, so the shared pool must comfortably exceed that for the\n        // refusal, not a connection timeout, to be what ends a runaway chain. A per-invocation pool\n        // (the default, and always the case when deployed) only ever needs pg's default of 10.\n        max: dbPoolReuseEnabled() ? 20 : undefined,\n        // If connString is not passed fall back to reading from env var\n        connectionString: connString || process.env.KEEL_DB_CONN,\n        // Server-side timeout, sent in the connection startup packet. Postgres\n        // cancels a query that exceeds it with error 57014 (query_canceled),\n        // which is catchable, unlike the Lambda function timeout which\n        // hard-kills the process.\n        statement_timeout: getStatementTimeoutMs(),\n        // Client-side backstop in case the server never responds. Set above\n        // statement_timeout so the server-side cancel (which frees the\n        // connection cleanly) always wins when the server is healthy.\n        query_timeout: getStatementTimeoutMs() + 10_000,\n        // Fail fast on connect instead of hanging.\n        connectionTimeoutMillis: 30_000,\n      };\n\n      // Allow the setting of a cert (.pem) file. RDS requires this to enforce SSL.\n      if (process.env.KEEL_DB_CERT) {\n        poolConfig.ssl = { ca: readFileSync(process.env.KEEL_DB_CERT) };\n      }\n\n      const pool = new InstrumentedPool(poolConfig);\n      attachPoolErrorHandler(pool);\n\n      return new PostgresDialect({\n        pool,\n      });\n    }\n    case \"neon\": {\n      // Register type parsers for all field types with a Postgres OID (e.g.\n      // NUMERIC, INTERVAL): see https://kysely.dev/docs/recipes/data-types#configuring-runtime-javascript-types\n      for (const t of allTypes) {\n        if (t.pgOid && t.pgParse) {\n          neon.types.setTypeParser(t.pgOid, t.pgParse);\n        }\n      }\n      // Keep Neon and pg result parsing behavior aligned.\n      neon.types.setTypeParser(pgTypes.builtins.JSON, parseJsonColumnValue);\n      neon.types.setTypeParser(pgTypes.builtins.JSONB, parseJsonColumnValue);\n      neon.types.setTypeParser(pgTypes.builtins.DATE, parseDateColumnValue);\n      neon.types.setTypeParser(DATE_ARRAY_OID, parseDateArrayColumnValue);\n      // Global to the neon module, as with pg above.\n      neon.defaults.parseInputDatesAsUTC = true;\n\n      neon.neonConfig.webSocketConstructor = WebSocket;\n\n      const pool = new InstrumentedNeonServerlessPool({\n        // If connString is not passed fall back to reading from env var\n        connectionString: connString || process.env.KEEL_DB_CONN,\n        // Same timeout settings as the pg dialect above - the neon driver\n        // vendors pg's connection parameter handling so these apply the same.\n        statement_timeout: getStatementTimeoutMs(),\n        query_timeout: getStatementTimeoutMs() + 10_000,\n        connectionTimeoutMillis: 30_000,\n      });\n\n      pool.on(\"connect\", (client: any) => {\n        const originalQuery = client.query;\n        client.query = function (...args: any[]) {\n          const sql = args[0];\n\n          let sqlAttribute = false;\n          let spanName =\n            txStatements[sql.toLowerCase() as keyof typeof txStatements];\n          if (!spanName) {\n            spanName = \"db.query\";\n            sqlAttribute = true;\n          }\n\n          return withSpan(\n            spanName,\n            function (span: any) {\n              if (sqlAttribute) {\n                // Checkpoint L follow-up: see the matching\n                // InstrumentedClient.query comment above - this driver-level\n                // span stays internal-only; the outer, model-scoped span\n                // from tracing.js's withDbQuerySpan is the \"db.query\"\n                // archetype's user-facing span.\n                span.setAttribute(\"db.statement\", truncateSQL(args[0]));\n                span.setAttribute(\"db.system\", dbConnType);\n              }\n              return originalQuery.apply(client, args);\n            },\n            { kind: SpanKind.CLIENT }\n          );\n        };\n      });\n\n      attachPoolErrorHandler(pool);\n\n      return new PostgresDialect({\n        pool: pool,\n      });\n    }\n    default:\n      throw Error(\"unexpected KEEL_DB_CONN_TYPE: \" + dbConnType);\n  }\n}\n\nexport {\n  createDatabaseClient,\n  useDatabase,\n  withDatabase,\n  deferFileDeletion,\n  attachPoolErrorHandler,\n  getStatementTimeoutMs,\n  isInDatabaseTransaction,\n  type DatabaseContext,\n  type DatabaseClientConfig,\n};\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport TraceParent from \"traceparent\";\nimport { sql, SelectionNode } from \"kysely\";\n\nconst auditContextStorage = new AsyncLocalStorage();\n\n// withAuditContext creates the audit context from the runtime request body\n// and sets it to in AsyncLocalStorage so that this data is available to the\n// ModelAPI during the execution of actions, jobs and subscribers.\nasync function withAuditContext(request, cb) {\n  let audit = {};\n\n  if (request.meta?.identity) {\n    audit.identityId = request.meta.identity.id;\n  }\n  if (request.meta?.tracing?.traceparent) {\n    audit.traceId = TraceParent.fromString(\n      request.meta.tracing.traceparent\n    )?.traceId;\n  }\n\n  return await auditContextStorage.run(audit, () => {\n    return cb();\n  });\n}\n\n// getAuditContext retrieves the audit context from AsyncLocalStorage.\nfunction getAuditContext() {\n  let auditStore = auditContextStorage.getStore();\n  return {\n    identityId: auditStore?.identityId,\n    traceId: auditStore?.traceId,\n  };\n}\n\n// AuditContextPlugin is a Kysely plugin which ensures that the audit context data\n// is written to Postgres configuration parameters in the same execution as a query.\n// It does this by calling the set_identity_id() and set_trace_id() functions as a\n// clause in the returning statement. It then subsequently drops these from the actual result.\n// This ensures that these parameters are set when the tables' AFTER trigger function executes.\nclass AuditContextPlugin {\n  constructor() {\n    this.identityIdAlias = \"__keel_identity_id\";\n    this.traceIdAlias = \"__keel_trace_id\";\n  }\n\n  // Appends set_identity_id() and set_trace_id() function calls to the returning statement\n  // of INSERT, UPDATE and DELETE operations.\n  transformQuery(args) {\n    switch (args.node.kind) {\n      case \"InsertQueryNode\":\n      case \"UpdateQueryNode\":\n      case \"DeleteQueryNode\":\n        // Represents a RETURNING clause in a SQL statement.\n        const returning = {\n          kind: \"ReturningNode\",\n          selections: [],\n        };\n\n        // If the query already has a selection, then append it.\n        if (args.node.returning) {\n          returning.selections.push(...args.node.returning.selections);\n        }\n\n        // Retrieve the audit context from async storage.\n        const audit = getAuditContext();\n\n        if (audit.identityId) {\n          const rawNode = sql`set_identity_id(${audit.identityId})`\n            .as(this.identityIdAlias)\n            .toOperationNode();\n\n          returning.selections.push(SelectionNode.create(rawNode));\n        }\n\n        if (audit.traceId) {\n          const rawNode = sql`set_trace_id(${audit.traceId})`\n            .as(this.traceIdAlias)\n            .toOperationNode();\n\n          returning.selections.push(SelectionNode.create(rawNode));\n        }\n\n        // Only attach the RETURNING clause if it has selections. An empty ReturningNode\n        // compiles to a trailing \"returning \" which Postgres rejects with\n        // \"syntax error at end of input\". selections are only empty when the query has no\n        // RETURNING of its own AND the audit context is empty - i.e. an unauthenticated\n        // request (no identityId) with no propagated trace (no traceId). The latter is the\n        // norm locally (e.g. `keel run` without tracing configured) but rare in a deployed,\n        // fully-traced environment. This only bites raw useDatabase() writes; the generated\n        // ModelAPI always emits its own RETURNING clause.\n        if (returning.selections.length === 0) {\n          return { ...args.node };\n        }\n\n        return {\n          ...args.node,\n          returning: returning,\n        };\n    }\n\n    return {\n      ...args.node,\n    };\n  }\n\n  // Drops the set_identity_id() and set_trace_id() fields from the result.\n  transformResult(args) {\n    if (args.result?.rows) {\n      for (let i = 0; i < args.result.rows.length; i++) {\n        delete args.result.rows[i][this.identityIdAlias];\n        delete args.result.rows[i][this.traceIdAlias];\n      }\n    }\n\n    return args.result;\n  }\n}\n\nexport { withAuditContext, getAuditContext, AuditContextPlugin };\n","import { CamelCasePlugin } from \"kysely\";\nimport { isPlainObject, isRichType } from \"./type-utils\";\nimport { JsonColumnValue } from \"./jsonColumnValue\";\n\n// KeelCamelCasePlugin wraps kysely's CamelCasePlugin to match Keel's migration\n// casing (`underscoreBeforeDigits`) and to leave rich Keel data types (e.g.\n// Duration) as instances of their classes.\nclass KeelCamelCasePlugin {\n  constructor(opt) {\n    this.opt = opt;\n    this.auditQueryIds = new WeakSet();\n    this.CamelCasePlugin = new CamelCasePlugin({\n      ...opt,\n      underscoreBeforeDigits: true,\n    });\n  }\n\n  transformQuery(args) {\n    if (args.queryId && referencesTable(args.node, \"keel_audit\")) {\n      this.auditQueryIds.add(args.queryId);\n    }\n    return this.CamelCasePlugin.transformQuery(args);\n  }\n\n  async transformResult(args) {\n    if (args.result.rows && Array.isArray(args.result.rows)) {\n      const mapAuditJson = args.queryId && this.auditQueryIds.has(args.queryId);\n      return {\n        ...args.result,\n        rows: args.result.rows.map((row) => this.mapRow(row, { mapAuditJson })),\n      };\n    }\n    return args.result;\n  }\n  mapRow(row, context = {}) {\n    return Object.keys(row).reduce((obj, key) => {\n      // Fields using @sequence will have a corresponding __sequence field which we drop as we don't want to return it\n      if (key.endsWith(\"__sequence\")) {\n        return obj;\n      }\n      let value = row[key];\n      if (value instanceof JsonColumnValue) {\n        value =\n          shouldMapJsonColumn(row, key, context) &&\n          canMap(value.value, this.opt)\n            ? this.mapRow(value.value, context)\n            : value.value;\n        obj[this.CamelCasePlugin.camelCase(key)] = value;\n        return obj;\n      }\n      if (Array.isArray(value)) {\n        value = value.map((it) =>\n          canMap(it, this.opt) ? this.mapRow(it, context) : it\n        );\n      } else if (canMap(value, this.opt)) {\n        value = this.mapRow(value, context);\n      }\n      obj[this.CamelCasePlugin.camelCase(key)] = value;\n      return obj;\n    }, {});\n  }\n}\n\nfunction shouldMapJsonColumn(row, key, context) {\n  // keel_audit.data stores internal database row snapshots. Existing callers\n  // expect those snapshots to be model-shaped/camelCased, unlike developer\n  // supplied JSON payloads whose keys must be preserved.\n  return (\n    context.mapAuditJson &&\n    key === \"data\" &&\n    \"id\" in row &&\n    \"table_name\" in row &&\n    \"op\" in row &&\n    \"identity_id\" in row &&\n    \"trace_id\" in row &&\n    \"created_at\" in row &&\n    \"event_processed_at\" in row\n  );\n}\n\nfunction referencesTable(node, tableName) {\n  if (!node || typeof node !== \"object\") {\n    return false;\n  }\n\n  if (\n    node.kind === \"IdentifierNode\" &&\n    (node.name === tableName || node.name === \"keelAudit\")\n  ) {\n    return true;\n  }\n\n  if (\n    node.kind === \"RawNode\" &&\n    Array.isArray(node.sqlFragments) &&\n    node.sqlFragments.some((fragment) =>\n      new RegExp(`(^|[^A-Za-z0-9_])${tableName}($|[^A-Za-z0-9_])`, \"i\").test(\n        fragment\n      )\n    )\n  ) {\n    return true;\n  }\n\n  return Object.values(node).some((value) => {\n    if (Array.isArray(value)) {\n      return value.some((item) => referencesTable(item, tableName));\n    }\n    return referencesTable(value, tableName);\n  });\n}\n\nfunction canMap(obj, opt) {\n  return (\n    isPlainObject(obj) && !opt?.maintainNestedObjectKeys && !isRichType(obj)\n  );\n}\n\nexport { KeelCamelCasePlugin };\n","import { types as pgTypes } from \"pg\";\nimport type { TypeDefinition } from \"./definition\";\n\nexport const decimal: TypeDefinition = {\n  name: \"Decimal\",\n  pgOid: pgTypes.builtins.NUMERIC,\n  pgParse: (val) => parseFloat(val),\n};\n","import parseInterval from \"postgres-interval\";\n\nconst isoRegex =\n  /^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$/;\n\ninterface Interval {\n  years?: number;\n  months?: number;\n  days?: number;\n  hours?: number;\n  minutes?: number;\n  seconds?: number;\n  toISOStringShort(): string;\n  toPostgres(): string;\n}\n\nexport class Duration {\n  private _typename: string;\n  private pgInterval: string;\n  private _interval: Interval;\n\n  constructor(postgresString: string) {\n    this._typename = \"Duration\";\n    this.pgInterval = postgresString;\n    this._interval = parseInterval(postgresString);\n  }\n\n  static fromISOString(isoString: string): Duration {\n    const match = isoString.match(isoRegex);\n    if (match) {\n      const d = new Duration(\"0\");\n      d._interval.years = match[1] ? parseInt(match[1]) : undefined;\n      d._interval.months = match[2] ? parseInt(match[2]) : undefined;\n      d._interval.days = match[3] ? parseInt(match[3]) : undefined;\n      d._interval.hours = match[4] ? parseInt(match[4]) : undefined;\n      d._interval.minutes = match[5] ? parseInt(match[5]) : undefined;\n      d._interval.seconds = match[6] ? parseInt(match[6]) : undefined;\n      return d;\n    }\n    return new Duration(\"0\");\n  }\n\n  toISOString(): string {\n    return this._interval.toISOStringShort();\n  }\n\n  toPostgres(): string {\n    return this._interval.toPostgres();\n  }\n}\n","import { Duration } from \"../Duration\";\nimport { types as pgTypes } from \"pg\";\nimport type { TypeDefinition } from \"./definition\";\n\nexport const duration: TypeDefinition = {\n  name: \"Duration\",\n  wireTypename: \"Duration\",\n  fromWire: (v) => Duration.fromISOString(v.interval),\n  isInstance: (v) => v instanceof Duration,\n  serialize: (v: Duration) => v.toISOString(),\n  detectDbValue: (v) => v._typename === \"Duration\" && !!v.pgInterval,\n  fromDbValue: (v) => new Duration(v.pgInterval),\n  toDbWrite: (v: Duration) => v.toPostgres(),\n  pgOid: pgTypes.builtins.INTERVAL,\n  pgParse: (val) => new Duration(val),\n  isRich: true,\n};\n","import { File, InlineFile } from \"../File\";\nimport type { TypeDefinition } from \"./definition\";\n\n// InlineFile must precede file in allTypes: the historical chains checked\n// `instanceof InlineFile` first, and File extends InlineFile.\nexport const inlineFile: TypeDefinition = {\n  name: \"InlineFile\",\n  wireTypename: \"InlineFile\",\n  fromWire: (v) => InlineFile.fromDataURL(v.dataURL),\n  isInstance: (v) => v instanceof InlineFile,\n  serialize: (v: InlineFile) => v.store(),\n  toDbWrite: async (v: InlineFile) => {\n    const stored = await v.store();\n    return stored.toDbRecord();\n  },\n};\n\nexport const file: TypeDefinition = {\n  name: \"File\",\n  // The Go runtime sends an already-stored file (e.g. a promoted async\n  // upload) as a File envelope so the function receives a File, not an\n  // InlineFile.\n  wireTypename: \"File\",\n  fromWire: (v) => File.fromDbRecord(v),\n  isInstance: (v) => v instanceof File,\n  // Presence-based detection: fixes the truthiness bug where a zero-byte\n  // file record (size: 0) failed to hydrate.\n  detectDbValue: (v) =>\n    typeof v.key === \"string\" &&\n    typeof v.filename === \"string\" &&\n    typeof v.contentType === \"string\" &&\n    typeof v.size === \"number\",\n  fromDbValue: (v) => File.fromDbRecord(v),\n  toDbWrite: (v: File) => v.toDbRecord(),\n};\n","import { isPlainObject } from \"../type-utils\";\nimport type { TypeDefinition } from \"./definition\";\nimport { decimal } from \"./decimal\";\nimport { duration } from \"./duration\";\nimport { file, inlineFile } from \"./file\";\n\n// ORDER IS BEHAVIOUR: instance checks run in this order and File extends\n// InlineFile — duration, inlineFile, file mirrors the historical\n// instanceof-chain order in parsing.js and ModelAPI.js.\nexport const allTypes: TypeDefinition[] = [duration, inlineFile, file, decimal];\n\nconst byWireTypename = new Map<string, TypeDefinition>();\nfor (const t of allTypes) {\n  if (t.wireTypename) {\n    byWireTypename.set(t.wireTypename, t);\n  }\n}\n\n// fromWire replaces parsing.js's parseComplexInputType (same error message).\nexport function fromWire(value: any): any {\n  const def = byWireTypename.get(value.__typename);\n  if (!def || !def.fromWire) {\n    throw new Error(\"complex type not handled: \" + value.__typename);\n  }\n  return def.fromWire(value);\n}\n\n// serializeOutputValue replaces parseOutputs's instanceof branches.\nexport async function serializeOutputValue(\n  value: unknown\n): Promise<{ handled: boolean; value: any }> {\n  for (const def of allTypes) {\n    if (def.isInstance?.(value) && def.serialize) {\n      return { handled: true, value: await def.serialize(value) };\n    }\n  }\n  return { handled: false, value };\n}\n\n// hydrateDbValue replaces transformRichDataTypes's detection branches.\n// Returns undefined when the object is not a rich-type DB shape.\nexport function hydrateDbValue(value: Record<string, any>): any | undefined {\n  if (!isPlainObject(value)) {\n    return undefined;\n  }\n  for (const def of allTypes) {\n    if (def.detectDbValue?.(value) && def.fromDbValue) {\n      return def.fromDbValue(value);\n    }\n  }\n  return undefined;\n}\n\n// transformValueForWrite replaces the ModelAPI create/update instanceof chains.\nexport async function transformValueForWrite(\n  value: unknown\n): Promise<{ handled: boolean; value: any }> {\n  for (const def of allTypes) {\n    if (def.isInstance?.(value) && def.toDbWrite) {\n      return { handled: true, value: await def.toDbWrite(value) };\n    }\n  }\n  return { handled: false, value };\n}\n\n// richInstanceTypes drives type-utils.isRichType (casing-plugin protection).\nexport function isRichRegisteredInstance(obj: unknown): boolean {\n  for (const def of allTypes) {\n    if (def.isRich && def.isInstance?.(obj)) {\n      return true;\n    }\n  }\n  return false;\n}\n","import { isRichRegisteredInstance } from \"./types/registry\";\n\nfunction isPlainObject(obj: unknown): boolean {\n  return Object.prototype.toString.call(obj) === \"[object Object]\";\n}\n\nfunction isRichType(obj: unknown): boolean {\n  if (!isPlainObject(obj)) {\n    return false;\n  }\n\n  return isRichRegisteredInstance(obj);\n}\n\nexport { isPlainObject, isRichType };\n","// Marker used by Postgres JSON/JSONB type parsers so the casing plugin can\n// preserve object keys inside JSON columns while still casing top-level columns.\nclass JsonColumnValue {\n  constructor(value) {\n    this.value = value;\n  }\n}\n\nfunction parseJsonColumnValue(value) {\n  return new JsonColumnValue(JSON.parse(value));\n}\n\nexport { JsonColumnValue, parseJsonColumnValue };\n","import * as opentelemetry from \"@opentelemetry/api\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport { envDetectorSync } from \"@opentelemetry/resources\";\nimport userTracingRegistry from \"./user_tracing.json\";\nimport { ATTRS } from \"./attrs\";\n\nconst userSpanContextKey = opentelemetry.createContextKey(\"keel.userSpan\");\n\n// withSpan starts a span named `name`, runs `fn` inside it, and ends it when `fn` settles -\n// recording any thrown error on the span first. `opts.kind` sets the OTel SpanKind (an\n// opentelemetry.SpanKind value); it defaults to INTERNAL, so existing call sites are unaffected.\nasync function withSpan(name, fn, opts = {}) {\n  const { kind = opentelemetry.SpanKind.INTERNAL } = opts;\n  return getTracer().startActiveSpan(name, { kind }, async (span) => {\n    try {\n      // await the thing (this means we can use try/catch)\n      return await fn(span);\n    } catch (err) {\n      if (err instanceof Error) {\n        // record any errors\n        span.recordException(err);\n        span.setStatus({\n          code: opentelemetry.SpanStatusCode.ERROR,\n          message: err.message,\n        });\n      }\n      // re-throw the error\n      throw err;\n    } finally {\n      // make sure the span is ended\n      span.end();\n    }\n  });\n}\n\n// --- Checkpoint L: user-facing tracing (spec step 1) ---\n//\n// AUDIENCE_ATTR/SPAN_TYPE_ATTR/AUDIENCE_USER mirror telemetry.AttrAudience/\n// AttrSpanType/AudienceUser (telemetry/attrs.go) - see ATTRS.AUDIENCE/\n// ATTRS.SPAN_TYPE below, which are the parity-tested string values. These\n// two attributes are set ONLY by markUserFacing, withUserFacingSpan, and\n// createTraceAPI's ensureCustomArchetype (below) - never at any other call\n// site (grep-proof: `keel.audience`/`keel.span.type` string literals appear\n// nowhere else in this package).\n\n// archetypedSpans tracks which spans have already been given an explicit\n// archetype (via markUserFacing or withUserFacingSpan), so createTraceAPI's\n// ctx.trace annotation API (see ensureCustomArchetype) knows not to\n// overwrite it with the \"custom\" archetype. In this codebase today,\n// ctx.trace always targets an already-archetyped span (the handleRequest/\n// handleJob/handleSubscriber SERVER span for a plain custom\n// function/job/subscriber, or the flow.step/flow.page span inside a flow's\n// step()/page() callback, via withUserSpan below) - never a bare, otherwise\n// unarchetyped span. ensureCustomArchetype's \"custom\" default only fires for\n// a genuinely fresh span with no prior archetype, keeping this forward\n// compatible without clobbering the real mapping-table archetypes.\nconst archetypedSpans = new WeakSet();\n\n// isDevOrTest mirrors telemetry.isDevOrTest (telemetry/user_tracing.go) -\n// KEEL_ENV unset or anything other than \"production\" enables the\n// attribute-drift warning.\nfunction isDevOrTest() {\n  return (process.env.KEEL_ENV ?? \"\") !== \"production\";\n}\n\n// warnUnregisteredAttrs is the TS mirror of Go's warnUnregisteredAttrs\n// (telemetry/user_tracing.go): dev/test only, logs any attribute key passed\n// to withUserFacingSpan that isn't in the archetype's registered visible\n// set, so instrumentation drift from the registry is caught in CI/local\n// runs rather than silently never rendering in the Console.\nfunction warnUnregisteredAttrs(archetype, attrs) {\n  if (!isDevOrTest() || !attrs) {\n    return;\n  }\n  const def = userTracingRegistry.archetypes[archetype];\n  if (!def || def.attrs === \"*\") {\n    return;\n  }\n  const allowed = new Set(def.attrs);\n  for (const key of Object.keys(attrs)) {\n    if (key === ATTRS.AUDIENCE || key === ATTRS.SPAN_TYPE) {\n      continue;\n    }\n    if (!allowed.has(key)) {\n      // eslint-disable-next-line no-console -- this package's own\n      // console.log/error are patched to become span events (see\n      // patchConsoleLog/patchConsoleError below); a plain stderr write here\n      // avoids recursing into that patch for what is itself a diagnostic\n      // about the tracing subsystem.\n      process.stderr.write(\n        JSON.stringify({\n          level: \"warn\",\n          msg: \"user-facing span attribute outside the archetype's registered visible set\",\n          time: new Date().toISOString(),\n          [ATTRS.SPAN_TYPE]: archetype,\n          attribute: key,\n        }) + \"\\n\"\n      );\n    }\n  }\n}\n\n// markUserFacing retrofits an already-created, already-well-named span as\n// customer-visible - the TS mirror of telemetry.MarkUserFacing (Go). This is\n// the adoption path used at every Migration step 1 call site in this package\n// (fetch, db.query, the handleRequest/handleJob/handleSubscriber SERVER\n// spans, flow.step/flow.page): all of them already have a well-named span\n// from the observability overhaul, so nothing new needs to be created.\nfunction markUserFacing(span, archetype) {\n  if (!span) {\n    return;\n  }\n  span.setAttribute(ATTRS.AUDIENCE, AUDIENCE_USER);\n  span.setAttribute(ATTRS.SPAN_TYPE, archetype);\n  archetypedSpans.add(span);\n}\n\n// withUserFacingSpan starts a NEW customer-visible span of the given\n// archetype - the TS mirror of telemetry.UserSpan (Go). Reserved for\n// genuinely new user-facing concepts; every archetype adopted in this\n// package so far instead uses markUserFacing on an existing span. attrs\n// (a plain object of key/value pairs, or undefined) is set on the span and\n// checked (dev/test only) against the archetype's registered visible set.\nasync function withUserFacingSpan(archetype, attrs, fn, opts = {}) {\n  const def = userTracingRegistry.archetypes[archetype];\n  const name = (def && def.name) || archetype;\n\n  return withSpan(\n    name,\n    async (span) => {\n      markUserFacing(span, archetype);\n      if (attrs) {\n        span.setAttributes(attrs);\n      }\n      warnUnregisteredAttrs(archetype, attrs);\n      return fn(span);\n    },\n    opts\n  );\n}\n\nfunction withUserSpan(span, fn) {\n  const ctx = opentelemetry.context.active().setValue(userSpanContextKey, span);\n  return opentelemetry.context.with(ctx, fn);\n}\n\nfunction getUserSpan() {\n  return opentelemetry.context.active().getValue(userSpanContextKey);\n}\n\nfunction resolveTraceSpan(defaultSpan) {\n  const span = getUserSpan() ?? defaultSpan;\n\n  if (!span) {\n    throw new Error(\"no user span available for ctx.trace\");\n  }\n\n  return span;\n}\n\nfunction normalizeTraceAttributeValue(value) {\n  if (value === undefined) {\n    return undefined;\n  }\n\n  if (\n    typeof value === \"string\" ||\n    typeof value === \"number\" ||\n    typeof value === \"boolean\"\n  ) {\n    return value;\n  }\n\n  if (Array.isArray(value)) {\n    if (value.length === 0) {\n      return value;\n    }\n\n    const firstType = typeof value[0];\n    const validArrayType =\n      firstType === \"string\" ||\n      firstType === \"number\" ||\n      firstType === \"boolean\";\n\n    if (validArrayType && value.every((item) => typeof item === firstType)) {\n      return value;\n    }\n  }\n\n  throw new TypeError(\n    \"trace attribute values must be strings, numbers, booleans, or arrays of a single primitive type\"\n  );\n}\n\nfunction createTraceAPI(defaultSpan) {\n  return {\n    get traceId() {\n      return resolveTraceSpan(defaultSpan).spanContext().traceId;\n    },\n    get spanId() {\n      return resolveTraceSpan(defaultSpan).spanContext().spanId;\n    },\n    setAttribute(key, value) {\n      const normalized = normalizeTraceAttributeValue(value);\n      if (normalized === undefined) {\n        return;\n      }\n\n      const span = resolveTraceSpan(defaultSpan);\n      ensureCustomArchetype(span);\n      span.setAttribute(key, normalized);\n    },\n    setAttributes(attributes) {\n      const normalized = {};\n\n      for (const [key, value] of Object.entries(attributes)) {\n        const normalizedValue = normalizeTraceAttributeValue(value);\n        if (normalizedValue !== undefined) {\n          normalized[key] = normalizedValue;\n        }\n      }\n\n      const span = resolveTraceSpan(defaultSpan);\n      ensureCustomArchetype(span);\n      span.setAttributes(normalized);\n    },\n  };\n}\n\nfunction patchFetch() {\n  if (!globalThis.fetch.patched) {\n    const originalFetch = globalThis.fetch;\n\n    globalThis.fetch = async (...args) => {\n      return withSpan(\n        \"fetch\",\n        async (span) => {\n          // Checkpoint L: a customer function's own outbound fetch call -\n          // the \"fetch\" archetype (Migration step 1 adoption table).\n          markUserFacing(span, \"fetch\");\n\n          const url = new URL(\n            args[0] instanceof Request ? args[0].url : String(args[0])\n          );\n          span.setAttribute(\"url.full\", url.toString());\n          const scheme = url.protocol.replace(\":\", \"\");\n          span.setAttribute(\"url.scheme\", scheme);\n\n          const options = args[0] instanceof Request ? args[0] : args[1] || {};\n          const method = (options.method || \"GET\").toUpperCase();\n          span.setAttribute(\"http.request.method\", method);\n\n          const res = await originalFetch(...args);\n          span.setAttribute(\"http.response.status_code\", res.status);\n          span.setAttribute(\"http.response.status_text\", res.statusText);\n          return res;\n        },\n        { kind: opentelemetry.SpanKind.CLIENT }\n      );\n    };\n    globalThis.fetch.patched = true;\n    globalThis.fetch.untraced = originalFetch;\n  }\n}\n\n// fetchUntraced calls fetch without the \"fetch\" span patchFetch adds. It is for this package's own\n// calls to the Keel runtime that already run under a better-named CLIENT span of their own (see\n// integrationServer.js): a nested \"fetch\" span there would present an internal hop as the\n// customer's own outbound call.\nfunction fetchUntraced(...args) {\n  const fetch = globalThis.fetch;\n  return (fetch.untraced ?? fetch)(...args);\n}\n\nfunction patchConsoleLog() {\n  if (!console.log.patched) {\n    const originalConsoleLog = console.log;\n\n    console.log = (...args) => {\n      const span = opentelemetry.trace.getActiveSpan();\n      if (span) {\n        const output = args\n          .map((arg) => {\n            if (arg instanceof Error) {\n              return arg.stack;\n            }\n            if (typeof arg === \"object\") {\n              try {\n                return JSON.stringify(arg, getCircularReplacer());\n              } catch (error) {\n                return \"[Object with circular references]\";\n              }\n            }\n            if (typeof arg === \"function\") {\n              return arg() || arg.name || arg.toString();\n            }\n            return String(arg);\n          })\n          .join(\" \");\n\n        span.addEvent(output);\n      }\n      originalConsoleLog(...args);\n    };\n\n    console.log.patched = true;\n  }\n}\n\nfunction patchConsoleError() {\n  if (!console.error.patched) {\n    const originalConsoleError = console.error;\n\n    console.error = (...args) => {\n      const span = opentelemetry.trace.getActiveSpan();\n      if (span) {\n        const output = args\n          .map((arg) => {\n            if (arg instanceof Error) {\n              return arg.stack;\n            }\n            if (typeof arg === \"object\") {\n              try {\n                return JSON.stringify(arg, getCircularReplacer());\n              } catch (error) {\n                return \"[Object with circular references]\";\n              }\n            }\n            if (typeof arg === \"function\") {\n              return arg() || arg.name || arg.toString();\n            }\n            return String(arg);\n          })\n          .join(\" \");\n\n        span.setStatus({\n          code: opentelemetry.SpanStatusCode.ERROR,\n          message: output,\n        });\n      }\n      originalConsoleError(...args);\n    };\n\n    console.error.patched = true;\n  }\n}\n\n// Utility to handle circular references in objects\nfunction getCircularReplacer() {\n  const seen = new WeakSet();\n  return (key, value) => {\n    if (typeof value === \"object\" && value !== null) {\n      if (seen.has(value)) {\n        return \"[Circular]\";\n      }\n      seen.add(value);\n    }\n    return value;\n  };\n}\n\nfunction init() {\n  if (process.env.KEEL_TRACING_ENABLED == \"true\") {\n    const exporter = new OTLPTraceExporter();\n    const processor = new BatchSpanProcessor(exporter);\n\n    const provider = new NodeTracerProvider({\n      resource: envDetectorSync.detect(),\n      spanProcessors: [processor],\n    });\n\n    provider.register();\n  }\n\n  patchFetch();\n  patchConsoleLog();\n  patchConsoleError();\n}\n\n// logForceFlushFailure writes a single debug-level JSON line, mirroring the\n// shape produced by logger.ts's `log.debug`. tracing.js is imported by\n// nearly every module in this package (including logger.ts's callers), so\n// importing logger.ts here would risk a tracing.js <-> logger.ts import\n// cycle; this tiny inline writer avoids that while keeping the same\n// KEEL_LOG_LEVEL-gated, JSON-line behaviour.\nfunction logForceFlushFailure(err) {\n  const level = (process.env.KEEL_LOG_LEVEL ?? \"info\").toLowerCase();\n  if (level !== \"debug\" && level !== \"trace\") {\n    return;\n  }\n  process.stdout.write(\n    JSON.stringify({\n      level: \"debug\",\n      msg: \"tracing forceFlush failed\",\n      time: new Date().toISOString(),\n      error: { name: err.name, message: err.message },\n    }) + \"\\n\"\n  );\n}\n\nasync function forceFlush() {\n  // The \"delegate\" is the actual provider set by the functions-runtime package\n  const provider = opentelemetry.trace.getTracerProvider().getDelegate();\n  if (provider && provider.forceFlush) {\n    try {\n      await provider.forceFlush();\n    } catch (err) {\n      // Silently ignore flush errors - this can happen when the OTEL collector\n      // is unavailable (e.g., in tests or when network is unreachable).\n      // We don't want tracing failures to break actual request handling.\n      logForceFlushFailure(err);\n    }\n  }\n}\n\n// TRACER_NAME is the single OTel tracer name used by the Node functions\n// runtime. Mirrors telemetry.TracerFunctions in the Go runtime\n// (telemetry/attrs.go) — keep in lockstep, see parity_test.go.\nconst TRACER_NAME = \"keel.functions\";\n\nfunction getTracer() {\n  return opentelemetry.trace.getTracer(TRACER_NAME);\n}\n\n// withDbQuerySpan wraps a Node ModelAPI/QueryBuilder database operation in a \"db.query\" CLIENT\n// span. Checkpoint K of the observability overhaul replaced the old high-cardinality\n// \"Database <Model>.<action>\" span name (spanNameForModelAPI) with a low-cardinality name plus\n// keel.model/db.operation.name attributes - the model and action are detail, not identity.\n//\n// Checkpoint L follow-up: this is the \"db.query\" archetype's user-facing span, not the\n// lower-level pg/neon driver span in database.ts (InstrumentedClient/InstrumentedNeonServerlessPool).\n// A single ModelAPI/QueryBuilder call can issue zero, one, or several actual SQL statements\n// underneath, each producing its own driver-level \"db.query\" span with the raw db.statement text -\n// internal detail per the user-facing tracing design's \"no internal detail\" principle, and there\n// must be exactly one user-facing db.query span per logical query (the registry's\n// collapse/rollup hints exist precisely to fold those driver-level spans away). So this outer,\n// model-scoped span - not the driver span - is the one marked user-facing; database.ts's driver\n// spans stay internal-only.\nfunction withDbQuerySpan(modelName, action, fn) {\n  return withSpan(\n    \"db.query\",\n    (span) => {\n      span.setAttribute(ATTRS.MODEL, modelName);\n      span.setAttribute(\"db.operation.name\", action);\n      markUserFacing(span, \"db.query\");\n      return fn(span);\n    },\n    { kind: SpanKind.CLIENT }\n  );\n}\n\n// spanNameForServiceAPI names a Node SDK call to the Flows/Tasks HTTP API after the exact\n// endpoint operation it invokes, mirroring the API handler's own span name (SpanNameAPI in\n// telemetry/attrs.go, e.g. runtime/apis/flowsapi's \"flows.start\"/\"flows.cancel_run\"), so a\n// customer function's outbound call to e.g. flows.myFlow.start() produces \"flows.start\" rather\n// than the old \"Database <flowName>.start\" misnomer.\nfunction spanNameForServiceAPI(service, op) {\n  return `${service}.${op}`;\n}\n\n// AUDIENCE_USER is the only defined value for ATTRS.AUDIENCE - mirrors\n// telemetry.AudienceUser (Go).\nconst AUDIENCE_USER = \"user\";\n\n// ARCHETYPE_CUSTOM mirrors telemetry.ArchetypeCustom (Go) - the archetype\n// createTraceAPI's ensureCustomArchetype defaults an otherwise-unarchetyped\n// span to.\nconst ARCHETYPE_CUSTOM = \"custom\";\n\n// getUserTracingRegistry returns the parsed user-facing tracing registry\n// (the checked-in verbatim copy of telemetry/user_tracing.json - see\n// telemetry/parity_test.go's byte-identity check). Exposed as a function\n// (rather than re-exporting the imported JSON module directly) so tsup's\n// declaration-file bundler can resolve it.\nfunction getUserTracingRegistry() {\n  return userTracingRegistry;\n}\n\n// ensureCustomArchetype is called by createTraceAPI's setAttribute/\n// setAttributes (below) on every span a customer's ctx.trace call touches.\n// If that span was already given an explicit archetype (markUserFacing/\n// withUserFacingSpan - tracked via archetypedSpans), it's left alone: in\n// this codebase ctx.trace always resolves to an already-archetyped span\n// (see the archetypedSpans comment above). Otherwise it's marked\n// audience=user/span.type=custom, satisfying \"createTraceAPI user spans\n// automatically get audience=user + custom archetype\" for any future span\n// ctx.trace might target that isn't already part of the mapping table.\nfunction ensureCustomArchetype(span) {\n  if (!span || archetypedSpans.has(span)) {\n    return;\n  }\n  // Dual-marking sanity: a span already explicitly marked keel.internal\n  // (e.g. handleFlow.ts's SERVER span, which a flow's own top-level\n  // ctx.trace calls target before entering any ctx.step()/ctx.ui.page())\n  // must stay internal - \"internal by default\" (principle 1) wins over the\n  // \"custom\" convenience default. Reading span.attributes here relies on\n  // this package's spans always being the real @opentelemetry/sdk-trace-base\n  // Span class (which exposes .attributes publicly - see e.g. this file's\n  // own tests reading span.attributes directly), not just the public\n  // OTel API surface.\n  if (span.attributes && span.attributes[ATTRS.INTERNAL] !== undefined) {\n    return;\n  }\n  span.setAttribute(ATTRS.AUDIENCE, AUDIENCE_USER);\n  span.setAttribute(ATTRS.SPAN_TYPE, ARCHETYPE_CUSTOM);\n  archetypedSpans.add(span);\n}\n\n// This attribute marks just this current span as internal; if the value is\n// \"true\" only this span is hidden from the Console by default.\nconst KEEL_INTERNAL_ATTR = ATTRS.INTERNAL;\n\n// This value, when set on KEEL_INTERNAL_ATTR, marks just the current span as\n// internal. A string (\"true\"), not a boolean - keel.internal is always a\n// string attribute so the Go and TS runtimes agree on wire representation.\nconst KEEL_INTERNAL_TRUE = \"true\";\n\n// This value, when set on KEEL_INTERNAL_ATTR, marks that all children spans\n// are also internal.\nconst KEEL_INTERNAL_CHILDREN = \"children\";\n\n// SpanKind is a passthrough of the OTel SpanKind enum (INTERNAL, SERVER, CLIENT, PRODUCER,\n// CONSUMER) so callers of withSpan don't need their own dependency on @opentelemetry/api just to\n// pass a kind.\nconst SpanKind = opentelemetry.SpanKind;\n\n// SQL_TRUNCATION_RUNES and SQL_TRUNCATION_MARKER mirror telemetry.TruncateSQL\n// in the Go runtime (telemetry/sql.go) exactly, so a db.statement attribute\n// is capped the same way regardless of which runtime produced the span.\nconst SQL_TRUNCATION_RUNES = 4096;\nconst SQL_TRUNCATION_MARKER = \"… [truncated]\";\n\n// truncateSQL caps `s` at SQL_TRUNCATION_RUNES Unicode code points, appending\n// SQL_TRUNCATION_MARKER when the input had to be cut. Every db.statement\n// producer (database.ts, ModelAPI.js, QueryBuilder.js) passes its compiled\n// SQL text through this before setting the span attribute, so a pathological\n// bulk statement can't blow up trace payload size (Task 8 of the\n// observability overhaul). Uses Array.from to split on code points rather\n// than UTF-16 code units, so a surrogate pair is never cut in half.\nfunction truncateSQL(s) {\n  const codePoints = Array.from(s);\n  if (codePoints.length <= SQL_TRUNCATION_RUNES) {\n    return s;\n  }\n  return (\n    codePoints.slice(0, SQL_TRUNCATION_RUNES).join(\"\") + SQL_TRUNCATION_MARKER\n  );\n}\n\nexport {\n  getTracer,\n  withSpan,\n  withUserSpan,\n  init,\n  forceFlush,\n  createTraceAPI,\n  withDbQuerySpan,\n  spanNameForServiceAPI,\n  fetchUntraced,\n  TRACER_NAME,\n  ATTRS,\n  KEEL_INTERNAL_ATTR,\n  KEEL_INTERNAL_TRUE,\n  KEEL_INTERNAL_CHILDREN,\n  SpanKind,\n  truncateSQL,\n  markUserFacing,\n  withUserFacingSpan,\n  AUDIENCE_USER,\n  ARCHETYPE_CUSTOM,\n  getUserTracingRegistry,\n};\n","{\n  \"version\": 1,\n  \"archetypes\": {\n    \"request\": {\n      \"name\": \"request\",\n      \"display\": \"{http.request.method} {url.path}\",\n      \"attrs\": [\n        \"http.request.method\",\n        \"url.path\",\n        \"http.response.status_code\",\n        \"keel.protocol\",\n        \"keel.api\",\n        \"error\",\n        \"error.code\"\n      ]\n    },\n    \"auth\": {\n      \"name\": \"auth.authorize\",\n      \"display\": \"Authorization\",\n      \"attrs\": [\"keel.identity.id\", \"error\", \"error.code\"]\n    },\n    \"permissions\": {\n      \"name\": \"permissions.check\",\n      \"display\": \"Check permissions\",\n      \"attrs\": [\"keel.permission.result\", \"keel.permission.reason\"],\n      \"hints\": {\n        \"mergeWhenTrivial\": \"action\"\n      }\n    },\n    \"validation\": {\n      \"name\": \"validation.check\",\n      \"display\": \"Check validation rules\",\n      \"attrs\": [\n        \"keel.validation.result\",\n        \"keel.validation.rules\",\n        \"keel.validation.rules_failed\",\n        \"keel.validation.failed_rules\"\n      ],\n      \"hints\": {\n        \"mergeWhenTrivial\": \"action\"\n      }\n    },\n    \"action\": {\n      \"name\": \"action\",\n      \"display\": \"Action {keel.action}\",\n      \"attrs\": [\n        \"keel.action\",\n        \"keel.action.type\",\n        \"keel.model\",\n        \"keel.permission.result\",\n        \"keel.validation.result\",\n        \"error\",\n        \"error.code\"\n      ]\n    },\n    \"function\": {\n      \"name\": \"function\",\n      \"display\": \"Function {keel.action}\",\n      \"attrs\": [\"keel.action\", \"keel.action.type\", \"error\", \"error.code\"],\n      \"userAttrs\": true\n    },\n    \"db.query\": {\n      \"name\": \"db.query\",\n      \"display\": \"Query\",\n      \"attrs\": [\n        \"db.statement\",\n        \"db.rows_affected\",\n        \"keel.model\",\n        \"db.operation.name\",\n        \"error\"\n      ],\n      \"hints\": {\n        \"collapse\": true,\n        \"rollup\": \"queries\"\n      }\n    },\n    \"event\": {\n      \"name\": \"event.publish\",\n      \"display\": \"Event {keel.event.name}\",\n      \"attrs\": [\n        \"keel.event.name\",\n        \"keel.event.target_type\",\n        \"keel.event.target_id\"\n      ]\n    },\n    \"subscriber\": {\n      \"name\": \"subscriber\",\n      \"display\": \"Subscriber {keel.subscriber}\",\n      \"attrs\": [\n        \"keel.subscriber\",\n        \"keel.event.name\",\n        \"keel.queued_ms\",\n        \"error\",\n        \"error.code\"\n      ]\n    },\n    \"job\": {\n      \"name\": \"job.run\",\n      \"display\": \"Job {keel.job.name}\",\n      \"attrs\": [\n        \"keel.job.name\",\n        \"keel.trigger\",\n        \"keel.status\",\n        \"error\",\n        \"error.code\"\n      ]\n    },\n    \"flow.run\": {\n      \"name\": \"flow.start\",\n      \"display\": \"Flow {keel.flow.name}\",\n      \"attrs\": [\n        \"keel.flow.name\",\n        \"keel.flow.run_id\",\n        \"keel.flow.status\",\n        \"error\",\n        \"error.code\"\n      ]\n    },\n    \"flow.step\": {\n      \"name\": \"flow.step\",\n      \"display\": \"Step {keel.step.name}\",\n      \"attrs\": [\"keel.step.name\", \"keel.step.type\", \"keel.step.status\"],\n      \"userAttrs\": true\n    },\n    \"flow.page\": {\n      \"name\": \"flow.page\",\n      \"display\": \"Page {keel.step.name}\",\n      \"attrs\": [\"keel.step.name\", \"keel.step.type\", \"keel.step.status\"],\n      \"userAttrs\": true\n    },\n    \"file\": {\n      \"name\": \"storage\",\n      \"display\": \"File\",\n      \"attrs\": []\n    },\n    \"fetch\": {\n      \"name\": \"fetch\",\n      \"display\": \"Fetch {http.request.method} {url.full}\",\n      \"attrs\": [\n        \"http.request.method\",\n        \"url.full\",\n        \"url.scheme\",\n        \"http.response.status_code\"\n      ]\n    },\n    \"integration.request\": {\n      \"name\": \"integration.request\",\n      \"display\": \"{keel.integration} {http.request.method} {url.path}\",\n      \"attrs\": [\n        \"keel.integration\",\n        \"http.request.method\",\n        \"url.path\",\n        \"http.response.status_code\",\n        \"error\"\n      ]\n    },\n    \"custom\": {\n      \"name\": \"custom\",\n      \"display\": \"{name}\",\n      \"attrs\": \"*\",\n      \"userAttrs\": true,\n      \"note\": \"user-authored ctx.trace spans; attrs are theirs by definition, not curated by this registry\"\n    }\n  }\n}\n","import { types as pgTypes } from \"pg\";\nimport { parse as parsePostgresArray } from \"postgres-array\";\n\n// A Postgres DATE is a calendar day with no timezone, but a JS Date is an\n// instant. Keel's API represents a date as midnight UTC, so DATE columns are\n// read as midnight UTC too. pg-types' default parser builds midnight in the\n// process's local timezone instead, which only agrees with Keel on a UTC host\n// (e.g. Lambda): on a machine in BST every date reads as the day before.\n//\n// The write side is handled by setting parseInputDatesAsUTC on the driver, so\n// a JS Date is sent to Postgres as its UTC calendar day.\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n// Captured before any parser is overridden, for values Keel never writes\n// (infinity, BC dates).\nconst defaultDateParser: (value: string) => any = pgTypes.getTypeParser(\n  pgTypes.builtins.DATE\n);\n\nfunction parseDateColumnValue(value: string): Date {\n  return ISO_DATE.test(value)\n    ? new Date(`${value}T00:00:00Z`)\n    : defaultDateParser(value);\n}\n\n// Parses a DATE[] in Postgres text form, e.g. {2024-01-02,NULL,\"0044-03-15 BC\"},\n// using the same array parser pg-types uses by default, so multi-dimensional\n// arrays and explicit bounds (e.g. [2:3]={...}) from raw queries keep their\n// structure. NULL entries are returned as null without being transformed.\nfunction parseDateArrayColumnValue(value: string): (Date | null)[] {\n  return parsePostgresArray(value, parseDateColumnValue);\n}\n\nexport { parseDateColumnValue, parseDateArrayColumnValue };\n","import { isPlainObject } from \"./type-utils\";\nimport {\n  fromWire,\n  hydrateDbValue,\n  serializeOutputValue,\n} from \"./types/registry\";\n\n// ISO date format regex - matches both Date (YYYY-MM-DD) and Timestamp (YYYY-MM-DDTHH:mm:ss.sssZ)\nconst dateFormat =\n  /^\\d{4}-\\d{2}-\\d{2}(?:T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n// parseInputs takes a set of inputs and creates objects for the ones that are of a complex type.\n//\n// inputs that are objects and contain a \"__typename\" field are resolved to instances of the complex type\n// they represent.\n// Date strings (ISO format) are converted to JavaScript Date objects.\nfunction parseInputs(inputs) {\n  if (inputs != null && typeof inputs === \"object\") {\n    for (const k of Object.keys(inputs)) {\n      const value = inputs[k];\n      if (value === null) {\n        continue;\n      }\n      // Handle date strings\n      if (typeof value === \"string\" && dateFormat.test(value)) {\n        inputs[k] = new Date(value);\n      } else if (typeof value === \"object\") {\n        if (Array.isArray(value)) {\n          inputs[k] = value.map((item) => {\n            if (item && typeof item === \"object\") {\n              if (\"__typename\" in item) {\n                return fromWire(item);\n              }\n              // Recursively parse nested objects in arrays\n              return parseInputs(item);\n            }\n            // Handle date strings in arrays\n            if (typeof item === \"string\" && dateFormat.test(item)) {\n              return new Date(item);\n            }\n            return item;\n          });\n        } else if (\"__typename\" in value) {\n          inputs[k] = fromWire(value);\n        } else {\n          inputs[k] = parseInputs(value);\n        }\n      }\n    }\n  }\n\n  return inputs;\n}\n\n// parseOutputs will take a response from the custom function and perform operations on any fields if necessary.\n//\n// For example, InlineFiles need to be stored before returning the response.\nasync function parseOutputs(outputs) {\n  if (outputs != null && typeof outputs === \"object\") {\n    for (const k of Object.keys(outputs)) {\n      if (outputs[k] !== null && typeof outputs[k] === \"object\") {\n        if (Array.isArray(outputs[k])) {\n          outputs[k] = await Promise.all(\n            outputs[k].map((item) => parseOutputs(item))\n          );\n        } else {\n          const result = await serializeOutputValue(outputs[k]);\n          if (result.handled) {\n            outputs[k] = result.value;\n          } else {\n            outputs[k] = await parseOutputs(outputs[k]);\n          }\n        }\n      }\n    }\n  }\n\n  return outputs;\n}\n\n// transformRichDataTypes iterates through the given object's keys and if any of the values are a rich data type, instantiate their respective class\nfunction transformRichDataTypes(data) {\n  const keys = data ? Object.keys(data) : [];\n  const row = {};\n\n  for (const key of keys) {\n    const value = data[key];\n    if (Array.isArray(value)) {\n      row[key] = value.map((item) => transformRichDataTypes({ item }).item);\n    } else if (isPlainObject(value)) {\n      const hydrated = hydrateDbValue(value);\n      if (hydrated !== undefined) {\n        row[key] = hydrated;\n      } else {\n        // Recurse so nested rich types (e.g. a File record carried alongside\n        // metadata in a structured step value) get hydrated too.\n        row[key] = transformRichDataTypes(value);\n      }\n    } else {\n      row[key] = value;\n    }\n  }\n\n  return row;\n}\n\nfunction isReferencingExistingRecord(value) {\n  return Object.keys(value).length === 1 && value.id;\n}\n\nexport {\n  parseInputs,\n  parseOutputs,\n  transformRichDataTypes,\n  isReferencingExistingRecord,\n  // Exported so ActionsAPI parses action responses with the same notion of \"this string is a\n  // date\" that function inputs are parsed with.\n  dateFormat,\n};\n","import { sql } from \"kysely\";\nimport { snakeCase } from \"./casing\";\nimport { TimePeriod } from \"./TimePeriod\";\n\nconst opMapping = {\n  startsWith: { op: \"like\", value: (v) => `${v}%` },\n  endsWith: { op: \"like\", value: (v) => `%${v}` },\n  contains: { op: \"like\", value: (v) => `%${v}%` },\n  oneOf: { op: \"=\", value: (v) => sql`ANY(${v})` },\n  greaterThan: { op: \">\" },\n  greaterThanOrEquals: { op: \">=\" },\n  lessThan: { op: \"<\" },\n  lessThanOrEquals: { op: \"<=\" },\n  before: { op: \"<\" },\n  onOrBefore: { op: \"<=\" },\n  after: { op: \">\" },\n  onOrAfter: { op: \">=\" },\n  equals: {\n    op: (v) =>\n      v === null || Array.isArray(v) ? sql`is not distinct from` : \"=\",\n  },\n  notEquals: { op: sql`is distinct from` },\n  equalsRelative: {\n    custom: (qb, fieldName, v) => {\n      const tp = TimePeriod.fromExpression(v);\n      return qb.where(\n        sql`${sql.raw(fieldName)} >= ${sql.raw(\n          tp.periodStartSQL()\n        )} AND ${sql.raw(fieldName)} < ${sql.raw(tp.periodEndSQL())}`\n      );\n    },\n  },\n  beforeRelative: {\n    op: \"<\",\n    value: (v) =>\n      sql`${sql.raw(TimePeriod.fromExpression(v).periodStartSQL())}`,\n  },\n  afterRelative: {\n    op: \">=\",\n    value: (v) => sql`${sql.raw(TimePeriod.fromExpression(v).periodEndSQL())}`,\n  },\n  any: {\n    isArrayQuery: true,\n    greaterThan: { op: \">\" },\n    greaterThanOrEquals: { op: \">=\" },\n    lessThan: { op: \"<\" },\n    lessThanOrEquals: { op: \"<=\" },\n    before: { op: \"<\" },\n    onOrBefore: { op: \"<=\" },\n    after: { op: \">\" },\n    onOrAfter: { op: \">=\" },\n    equals: { op: \"=\" },\n    notEquals: { op: \"=\", value: (v) => sql`NOT ${v}` },\n  },\n  all: {\n    isArrayQuery: true,\n    greaterThan: { op: \">\" },\n    greaterThanOrEquals: { op: \">=\" },\n    lessThan: { op: \"<\" },\n    lessThanOrEquals: { op: \"<=\" },\n    before: { op: \"<\" },\n    onOrBefore: { op: \"<=\" },\n    after: { op: \">\" },\n    onOrAfter: { op: \">=\" },\n    equals: { op: \"=\" },\n    notEquals: { op: \"=\", value: (v) => sql`NOT ${v}` },\n  },\n};\n\n/**\n * Applies the given where conditions to the provided Kysely\n * instance and returns the resulting new Kysely instance.\n * @param {import(\"./QueryContext\").QueryContext} context\n * @param {import(\"kysely\").Kysely} qb\n * @param {Object} where\n * @returns {import(\"kysely\").Kysely}\n */\nfunction applyWhereConditions(context, qb, where = {}) {\n  const conf = context.tableConfig();\n  for (const key of Object.keys(where)) {\n    const v = where[key];\n\n    // Handle nested where conditions e.g. using a join table\n    if (conf && conf[snakeCase(key)]) {\n      const rel = conf[snakeCase(key)];\n      context.withJoin(rel.referencesTable, () => {\n        qb = applyWhereConditions(context, qb, v);\n      });\n      continue;\n    }\n\n    const fieldName = `${context.tableAlias()}.${snakeCase(key)}`;\n\n    if (Object.prototype.toString.call(v) !== \"[object Object]\") {\n      const operator =\n        v === null || Array.isArray(v) ? sql`is not distinct from` : \"=\";\n      qb = qb.where(fieldName, operator, sql`${v}`);\n      continue;\n    }\n\n    for (const op of Object.keys(v)) {\n      const mapping = opMapping[op];\n      if (!mapping) {\n        throw new Error(`invalid where condition: ${op}`);\n      }\n\n      if (mapping.custom) {\n        qb = mapping.custom(qb, fieldName, v[op]);\n      } else if (mapping.isArrayQuery) {\n        for (const arrayOp of Object.keys(v[op])) {\n          qb = qb.where(\n            mapping[arrayOp].value\n              ? mapping[arrayOp].value(v[op][arrayOp])\n              : sql`${v[op][arrayOp]}`,\n            mapping[arrayOp].op,\n            sql`${sql(op)}(${sql.ref(fieldName)})`\n          );\n        }\n      } else {\n        const operator =\n          typeof mapping.op === \"function\" ? mapping.op(v[op]) : mapping.op;\n        qb = qb.where(\n          fieldName,\n          operator,\n          mapping.value ? mapping.value(v[op]) : sql`${v[op]}`\n        );\n      }\n    }\n  }\n\n  return qb;\n}\n\nexport { applyWhereConditions };\n","import {\n  snakeCase as snakeCaseBase,\n  camelCase as camelCaseBase,\n} from \"change-case\";\n\n// Split rules that make change-case match Keel's migration casing, which splits\n// on letter→digit boundaries (e.g. `itemBarcode2` -> `item_barcode_2`).\nconst splitRegexp = [\n  /([a-z0-9])([A-Z])/g,\n  /([A-Z])([A-Z][a-z])/g,\n  /([a-zA-Z])([0-9])/g,\n];\n\nfunction camelCaseTransform(input, index) {\n  if (index === 0) return input.toLowerCase();\n  const firstChar = input.charAt(0);\n  const lowerChars = input.substr(1).toLowerCase();\n  return `${firstChar.toUpperCase()}${lowerChars}`;\n}\n\nfunction snakeCase(str) {\n  return snakeCaseBase(str, { splitRegexp });\n}\n\nfunction camelCase(str) {\n  return camelCaseBase(str, { transform: camelCaseTransform, splitRegexp });\n}\n\nfunction camelCaseObject(obj = {}) {\n  const r = {};\n  for (const key of Object.keys(obj)) {\n    r[camelCase(key)] = obj[key];\n  }\n  return r;\n}\n\nfunction snakeCaseObject(obj) {\n  const r = {};\n  for (const key of Object.keys(obj)) {\n    r[snakeCase(key)] = obj[key];\n  }\n  return r;\n}\n\nfunction upperCamelCase(s) {\n  s = camelCase(s);\n  return s[0].toUpperCase() + s.substring(1);\n}\n\nexport {\n  camelCaseObject,\n  snakeCaseObject,\n  snakeCase,\n  camelCase,\n  upperCamelCase,\n};\n","class TimePeriod {\n  constructor(period = \"\", value = 0, offset = 0, complete = false) {\n    this.period = period;\n    this.value = value;\n    this.offset = offset;\n    this.complete = complete;\n  }\n\n  static fromExpression(expression) {\n    // Regex pattern\n    const pattern =\n      /^(this|next|last)?\\s*(\\d+)?\\s*(complete)?\\s*(second|minute|hour|day|week|month|year|seconds|minutes|hours|days|weeks|months|years)?$/i;\n\n    const shorthandPattern = /^(now|today|tomorrow|yesterday)$/i;\n\n    const shorthandMatch = shorthandPattern.exec(expression.trim());\n    if (shorthandMatch) {\n      const shorthand = shorthandMatch[1].toLowerCase();\n      switch (shorthand) {\n        case \"now\":\n          return new TimePeriod();\n        case \"today\":\n          return TimePeriod.fromExpression(\"this day\");\n        case \"tomorrow\":\n          return TimePeriod.fromExpression(\"next complete day\");\n        case \"yesterday\":\n          return TimePeriod.fromExpression(\"last complete day\");\n      }\n    }\n\n    const match = pattern.exec(expression.trim());\n    if (!match) {\n      throw new Error(\"Invalid time period expression\");\n    }\n\n    const [, direction, rawValue, isComplete, rawPeriod] = match;\n\n    let period = rawPeriod ? rawPeriod.toLowerCase().replace(/s$/, \"\") : \"\";\n    let value = rawValue ? parseInt(rawValue, 10) : 1;\n    let complete = Boolean(isComplete);\n    let offset = 0;\n\n    const dir = direction?.toLowerCase();\n\n    // Two-token \"last/next\" expressions without an explicit count (e.g. \"last week\",\n    // \"next month\") are implicitly complete so they refer to calendar periods, not\n    // rolling windows. Only applies to day/week/month/year (not sub-day periods).\n    if (\n      !complete &&\n      !rawValue &&\n      (dir === \"last\" || dir === \"next\") &&\n      [\"day\", \"week\", \"month\", \"year\"].includes(period)\n    ) {\n      complete = true;\n    }\n\n    switch (dir) {\n      case \"this\":\n        offset = 0;\n        complete = true;\n        break;\n      case \"next\":\n        offset = complete ? 1 : 0;\n        break;\n      case \"last\":\n        offset = -value;\n        break;\n      default:\n        throw new Error(\n          \"Time period expression must start with this, next, or last\"\n        );\n    }\n\n    return new TimePeriod(period, value, offset, complete);\n  }\n\n  periodStartSQL() {\n    let sql = \"NOW()\";\n    if (this.offset !== 0) {\n      sql = `${sql} + INTERVAL '${this.offset} ${this.period}'`;\n    }\n\n    if (this.complete) {\n      sql = `DATE_TRUNC('${this.period}', ${sql})`;\n    } else {\n      sql = `(${sql})`;\n    }\n\n    return sql;\n  }\n\n  periodEndSQL() {\n    let sql = this.periodStartSQL();\n    if (this.value != 0) {\n      sql = `(${sql} + INTERVAL '${this.value} ${this.period}')`;\n    }\n    return sql;\n  }\n}\n\nexport { TimePeriod };\n","import { snakeCase } from \"./casing\";\n\nfunction applyLimit(context, qb, limit) {\n  return qb.limit(limit);\n}\n\nfunction applyOffset(context, qb, offset) {\n  return qb.offset(offset);\n}\n\nfunction applyOrderBy(context, qb, tableName, orderBy = {}) {\n  Object.entries(orderBy).forEach(([key, sortOrder]) => {\n    qb = qb.orderBy(`${tableName}.${snakeCase(key)}`, sortOrder.toLowerCase());\n  });\n  return qb;\n}\n\nexport { applyLimit, applyOffset, applyOrderBy };\n","import { snakeCase } from \"./casing\";\n\n/**\n * Adds the joins required by the where conditions to the given\n * Kysely instance and returns the resulting new Kysely instance.\n * @param {import(\"./QueryContext\").QueryContext} context\n * @param {import(\"kysely\").Kysely} qb\n * @param {Object} where\n * @returns {import(\"kysely\").Kysely}\n */\nfunction applyJoins(context, qb, where) {\n  const conf = context.tableConfig();\n  if (!conf) {\n    return qb;\n  }\n\n  const srcTable = context.tableAlias();\n\n  for (const key of Object.keys(where)) {\n    const rel = conf[snakeCase(key)];\n    if (!rel) {\n      continue;\n    }\n\n    const targetTable = rel.referencesTable;\n\n    if (context.hasJoin(targetTable)) {\n      continue;\n    }\n\n    context.withJoin(targetTable, () => {\n      switch (rel.relationshipType) {\n        case \"hasMany\":\n          // For hasMany the primary key is on the source table\n          // and the foreign key is on the target table\n          qb = qb.innerJoin(\n            `${targetTable} as ${context.tableAlias()}`,\n            `${srcTable}.id`,\n            `${context.tableAlias()}.${rel.foreignKey}`\n          );\n          break;\n\n        case \"belongsTo\":\n          // For belongsTo the primary key is on the target table\n          // and the foreign key is on the source table\n          qb = qb.innerJoin(\n            `${targetTable} as ${context.tableAlias()}`,\n            `${srcTable}.${rel.foreignKey}`,\n            `${context.tableAlias()}.id`\n          );\n          break;\n        default:\n          throw new Error(`unknown relationshipType: ${rel.relationshipType}`);\n      }\n\n      // Keep traversing through the where conditions to see if\n      // more joins need to be applied\n      qb = applyJoins(context, qb, where[key]);\n    });\n  }\n\n  return qb;\n}\n\nexport { applyJoins };\n","/**\n * QueryContext is used to store state about the current query, for example\n * which joins have already been applied. It is used by applyJoins and\n * applyWhereConditions to generate consistent table aliases for joins.\n *\n * This class has the concept of a \"table path\". This is just a list of tables, starting\n * with some \"root\" table and ending with the table we're currently joining to. So\n * for example if we started with a \"product\" table and joined from there to \"order_item\"\n * and then to \"order\" and then to \"customer\" the table path would be:\n *   [\"product\", \"order_item\", \"order\", \"customer\"]\n * At this point the \"current\" table is \"customer\" and it's alias would be:\n *   \"product$order_item$order$customer\"\n */\nclass QueryContext {\n  /**\n   * @param {string[]} tablePath This is the path from the \"root\" table to the \"current table\".\n   * @param {import(\"./ModelAPI\").TableConfigMap} tableConfigMap\n   * @param {string[]} joins\n   */\n  constructor(tablePath, tableConfigMap, joins = []) {\n    this._tablePath = tablePath;\n    this._tableConfigMap = tableConfigMap;\n    this._joins = joins;\n  }\n\n  clone() {\n    return new QueryContext([...this._tablePath], this._tableConfigMap, [\n      ...this._joins,\n    ]);\n  }\n\n  /**\n   * Returns true if, given the current table path, a join to the given\n   * table has already been added.\n   * @param {string} table\n   * @returns {boolean}\n   */\n  hasJoin(table) {\n    const alias = joinAlias([...this._tablePath, table]);\n    return this._joins.includes(alias);\n  }\n\n  /**\n   * Adds table to the QueryContext's path and registers the join,\n   * calls fn, then pops the table off the path.\n   * @param {string} table\n   * @param {Function} fn\n   */\n  withJoin(table, fn) {\n    this._tablePath.push(table);\n    this._joins.push(this.tableAlias());\n\n    fn();\n\n    // Don't change the _joins list, we want to remember those\n    this._tablePath.pop();\n  }\n\n  /**\n   * Returns the alias that will be used for the current table\n   * @returns {string}\n   */\n  tableAlias() {\n    return joinAlias(this._tablePath);\n  }\n\n  /**\n   * Returns the current table name\n   * @returns {string}\n   */\n  tableName() {\n    return this._tablePath[this._tablePath.length - 1];\n  }\n\n  /**\n   * Return the TableConfig for the current table\n   * @returns {import(\"./ModelAPI\").TableConfig | undefined}\n   */\n  tableConfig() {\n    return this._tableConfigMap[this.tableName()];\n  }\n}\n\nfunction joinAlias(tablePath) {\n  return tablePath.join(\"$\");\n}\n\nexport { QueryContext };\n","import { createJSONRPCErrorResponse } from \"json-rpc-2.0\";\n\nconst RuntimeErrors = {\n  // Catchall error type for unhandled execution errors during custom function\n  UnknownError: -32001,\n  // DatabaseError represents any error at pg level that isn't handled explicitly below\n  DatabaseError: -32002,\n  // No result returned from custom function by user\n  NoResultError: -32003,\n  // When trying to delete/update a non existent record in the db\n  RecordNotFoundError: -32004,\n  ForeignKeyConstraintError: -32005,\n  NotNullConstraintError: -32006,\n  UniqueConstraintError: -32007,\n  PermissionError: -32008,\n  BadRequestError: -32009,\n  // A model-level @validate rule the database refused the write for. Carries the rule's own message,\n  // raised by the trigger enforcing it.\n  DataIntegrityError: -32011,\n  // A ledger guard (@min/@max on a balance or an amount) the database refused the write for.\n  // Carries the guard's payload in data.errors[0], the envelope the runtime itself reports it in.\n  LedgerGuardError: -32012,\n  // A flow UI callback whose page another request had already submitted. An error rather than a\n  // result so it cannot be mistaken for whatever the callback itself returns.\n  StepAlreadySubmittedError: -32013,\n};\n\n// Error presets\nclass PermissionError extends Error {}\n\nclass DatabaseError extends Error {\n  constructor(error) {\n    super(error.message);\n    this.error = error;\n  }\n}\n\nclass NotFoundError extends Error {\n  errorCode = RuntimeErrors.RecordNotFoundError;\n  constructor(message) {\n    super(message); // Default message is handled by the runtime for consistency with built in actions\n  }\n}\n\nclass BadRequestError extends Error {\n  errorCode = RuntimeErrors.BadRequestError;\n  constructor(message = \"bad request\") {\n    super(message);\n  }\n}\n\nclass UnknownError extends Error {\n  errorCode = RuntimeErrors.UnknownError;\n  constructor(message = \"unknown error\") {\n    super(message);\n  }\n}\n\nconst ErrorPresets = {\n  NotFound: NotFoundError,\n  BadRequest: BadRequestError,\n  Unknown: UnknownError,\n};\n\n// errorToJSONRPCResponse transforms a JavaScript Error instance (or derivative) into a valid JSONRPC response object to pass back to the Keel runtime.\nfunction errorToJSONRPCResponse(request, e) {\n  switch (e.constructor.name) {\n    case \"PermissionError\":\n      return createJSONRPCErrorResponse(\n        request.id,\n        RuntimeErrors.PermissionError,\n        e.message\n      );\n    // Any error thrown in the ModelAPI class is\n    // wrapped in a DatabaseError in order to differentiate 'our code' vs the user's own code.\n    case \"NoResultError\":\n      return createJSONRPCErrorResponse(\n        request.id,\n\n        // to be matched to https://github.com/teamkeel/keel/blob/e3115ffe381bfc371d4f45bbf96a15072a994ce5/runtime/actions/update.go#L54-L54\n        RuntimeErrors.RecordNotFoundError,\n        \"\" // Don't pass on the message as we want to normalise these at the runtime layer but still support custom messages in other NotFound errors\n      );\n    // An ActionError the user's function did not catch: a call it made to another action failed.\n    // Map the runtime's own error envelope onto the equivalent JSON-RPC error so the failure\n    // surfaces to the original caller as the same kind of error the inner action reported,\n    // rather than a generic unknown error.\n    case \"ActionError\":\n      switch (e.code) {\n        case \"ERR_PERMISSION_DENIED\":\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.PermissionError,\n            e.message\n          );\n        case \"ERR_RECORD_NOT_FOUND\":\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.RecordNotFoundError,\n            e.message\n          );\n        case \"ERR_INVALID_INPUT\":\n        case \"ERR_INPUT_MALFORMED\":\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.BadRequestError,\n            e.message,\n            e.data\n          );\n        case \"ERR_CONFLICT\":\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.UniqueConstraintError,\n            e.message,\n            e.data\n          );\n        // The inner action already reported the guard in the runtime's own envelope, so it is\n        // passed on as is: the outer caller sees the same 409 and payload.\n        case \"ERR_LEDGER_GUARD\":\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.LedgerGuardError,\n            e.message,\n            e.data\n          );\n        default:\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.UnknownError,\n            e.message\n          );\n      }\n    case \"DatabaseError\":\n      let err = e;\n\n      // If wrapped error then unwrap\n      if (e instanceof DatabaseError) {\n        err = e.error;\n      }\n\n      if (err.constructor.name == \"NoResultError\") {\n        return createJSONRPCErrorResponse(\n          request.id,\n\n          // to be matched to https://github.com/teamkeel/keel/blob/e3115ffe381bfc371d4f45bbf96a15072a994ce5/runtime/actions/update.go#L54-L54\n          RuntimeErrors.RecordNotFoundError,\n          \"\" // Don't pass on the message as we want to normalise these at the runtime layer but still support custom messages in other NotFound errors\n        );\n      }\n\n      // if the error contains 'code' then assume it has other pg error message keys\n      // todo: make this more ironclad.\n      // when using lib-pq, should match https://github.com/brianc/node-postgres/blob/master/packages/pg-protocol/src/parser.ts#L371-L386\n      if (\"code\" in err) {\n        const { code, detail, table } = err;\n\n        // A ledger guard describes itself in DETAIL rather than naming a column, so it is reported\n        // with the payload read from there - the same one a built-in action reports.\n        if (code === \"KE005\") {\n          return createJSONRPCErrorResponse(\n            request.id,\n            RuntimeErrors.LedgerGuardError,\n            err.message,\n            { errors: [ledgerGuardPayload(err.message, detail)] }\n          );\n        }\n\n        let rpcErrorCode, column, value;\n        const [col, val] = parseKeyMessage(err.detail);\n        column = col;\n        value = val;\n\n        switch (code) {\n          case \"23502\":\n            rpcErrorCode = RuntimeErrors.NotNullConstraintError;\n            column = err.column;\n            break;\n          case \"23503\":\n            rpcErrorCode = RuntimeErrors.ForeignKeyConstraintError;\n            break;\n          case \"23505\":\n            rpcErrorCode = RuntimeErrors.UniqueConstraintError;\n            break;\n          case \"KE001\":\n            rpcErrorCode = RuntimeErrors.DataIntegrityError;\n            break;\n          default:\n            rpcErrorCode = RuntimeErrors.DatabaseError;\n            break;\n        }\n\n        return createJSONRPCErrorResponse(request.id, rpcErrorCode, e.message, {\n          table,\n          column,\n          code,\n          detail,\n          value,\n        });\n      }\n\n      // we don't know what it is, but it's something else\n      return createJSONRPCErrorResponse(\n        request.id,\n        RuntimeErrors.DatabaseError,\n        e.message\n      );\n    default:\n      // Use the errorCode in the error if we have some from a preset\n      return createJSONRPCErrorResponse(\n        request.id,\n        e.errorCode ?? RuntimeErrors.UnknownError,\n        e.message\n      );\n  }\n}\n\n// example data:\n// Key (author_id)=(fake) is not present in table \"author\".\nconst keyMessagePattern = /\\Key\\s[(](.*)[)][=][(](.*)[)]/;\nconst parseKeyMessage = (msg) => {\n  const [, col, value] = keyMessagePattern.exec(msg) || [];\n\n  return [col, value];\n};\n\n// ledgerGuardPayload reads the DETAIL a ledger guard raises KE005 with into the payload the runtime\n// reports under data.errors[0]. The DETAIL contract is documented on db.PgLedgerGuardViolation in the\n// Go runtime, and this must read it exactly as runtime/actions does for built-in actions: the cases\n// in ./testdata/ledger_guard_details.json are run against both. A DETAIL that cannot be read reports\n// the message alone - it is still the guard's rejection.\n//\n// Numbers become JS numbers, from a JSON number or a string holding one, so a Decimal loses any\n// trailing zeros here (0.10 is reported as 0.1), as Decimals do everywhere else in the functions\n// runtime. A write that has no request order to place an entry in reports no entryIndex.\nfunction ledgerGuardPayload(message, detail) {\n  const payload = readLedgerGuardDetail(detail);\n  return payload ? { error: message, ...payload } : { error: message };\n}\n\nconst LEDGER_GUARDS = [\"min\", \"max\"];\n\n// The JSON number grammar, which is what a number held in a string must match.\nconst jsonNumberPattern = /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?$/;\n\n// readLedgerGuardDetail returns the payload's keys for the guard DETAIL describes (without\n// \"error\"), or null when DETAIL is not a single JSON object carrying every key its kind requires.\n// Only the keys every kind shares and the keys of the kind DETAIL names are read, so a key that\n// belongs to another kind is ignored whatever it holds.\nfunction readLedgerGuardDetail(detail) {\n  let parsed;\n  try {\n    parsed = JSON.parse(detail);\n  } catch {\n    return null;\n  }\n  if (!isObject(parsed)) {\n    return null;\n  }\n\n  const kind = parsed.kind;\n  const guard = parsed.guard;\n  const bound = guardNumber(parsed.bound);\n  if (\n    !optionalString(kind) ||\n    !optionalString(guard) ||\n    !LEDGER_GUARDS.includes(guard) ||\n    bound === undefined\n  ) {\n    return null;\n  }\n\n  switch (kind) {\n    case \"balance\": {\n      const { balance, position } = parsed;\n      const current = guardNumber(parsed.current);\n      const attempted = guardNumber(parsed.attempted);\n      if (\n        !requiredString(balance) ||\n        !isObject(position) ||\n        current === undefined ||\n        attempted === undefined\n      ) {\n        return null;\n      }\n      return { guard, bound, balance, position, current, attempted };\n    }\n    case \"amount\": {\n      const { amount, entries } = parsed;\n      if (\n        !requiredString(amount) ||\n        !Array.isArray(entries) ||\n        entries.length === 0\n      ) {\n        return null;\n      }\n      const values = [];\n      for (const entry of entries) {\n        if (!isObject(entry) || !optionalString(entry.id)) {\n          return null;\n        }\n        const value = guardNumber(entry.value);\n        if (value === undefined) {\n          return null;\n        }\n        values.push(value);\n      }\n      return { guard, bound, amount, value: values[0] };\n    }\n    case \"related_row\": {\n      const { ledger, balance } = parsed;\n      if (!requiredString(ledger) || !requiredString(balance)) {\n        return null;\n      }\n      return { guard, bound, ledger, balance };\n    }\n    default:\n      return null;\n  }\n}\n\nfunction isObject(v) {\n  return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n// A string key is unset when absent or null; any other non-string makes DETAIL unreadable.\nfunction optionalString(v) {\n  return v === undefined || v === null || typeof v === \"string\";\n}\n\nfunction requiredString(v) {\n  return typeof v === \"string\" && v !== \"\";\n}\n\nfunction guardNumber(v) {\n  if (typeof v === \"number\" && Number.isFinite(v)) {\n    return v;\n  }\n  if (typeof v === \"string\" && jsonNumberPattern.test(v)) {\n    return Number(v);\n  }\n  return undefined;\n}\n\nexport {\n  errorToJSONRPCResponse,\n  ledgerGuardPayload,\n  RuntimeErrors,\n  DatabaseError,\n  PermissionError,\n  ErrorPresets,\n};\n","import { applyWhereConditions } from \"./applyWhereConditions\";\nimport {\n  applyLimit,\n  applyOffset,\n  applyOrderBy,\n} from \"./applyAdditionalQueryConstraints\";\nimport { applyJoins } from \"./applyJoins\";\nimport {\n  camelCaseObject,\n  snakeCaseObject,\n  snakeCase,\n  upperCamelCase,\n} from \"./casing\";\nimport { useDatabase } from \"./database\";\nimport { transformRichDataTypes } from \"./parsing\";\nimport { QueryContext } from \"./QueryContext\";\nimport * as tracing from \"./tracing\";\nimport { DatabaseError } from \"./errors\";\n\nclass QueryBuilder {\n  /**\n   * @param {string} tableName\n   * @param {import(\"./QueryContext\").QueryContext} context\n   * @param {import(\"kysely\").Kysely} db\n   */\n  constructor(tableName, context, db) {\n    this._tableName = tableName;\n    this._context = context;\n    this._db = db;\n    this._modelName = upperCamelCase(this._tableName);\n  }\n\n  where(where) {\n    const context = this._context.clone();\n\n    let builder = applyJoins(context, this._db, where);\n    builder = applyWhereConditions(context, builder, where);\n\n    return new QueryBuilder(this._tableName, context, builder);\n  }\n\n  sql() {\n    return this._db.compile().sql;\n  }\n\n  async update(values) {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(this._modelName, \"update\", async (span) => {\n      // we build a sub-query to add to the WHERE id IN (XXX) containing all of the\n      // wheres added in previous .where() chains.\n      const sub = this._db.clearSelect().select(\"id\");\n\n      const query = db\n        .updateTable(this._tableName)\n        .set(snakeCaseObject(values))\n        .returningAll()\n        .where(\"id\", \"in\", sub);\n\n      try {\n        const result = await query.execute();\n        const numUpdatedRows = result.length;\n\n        // the double (==) is important because we are comparing bigint to int\n        if (numUpdatedRows == 0) {\n          return null;\n        }\n\n        if (numUpdatedRows > 1) {\n          throw new DatabaseError(\n            new Error(\n              \"more than one row matched update constraints - only unique fields should be used when updating.\"\n            )\n          );\n        }\n\n        return transformRichDataTypes(camelCaseObject(result[0]));\n      } catch (e) {\n        throw new DatabaseError(e);\n      }\n    });\n  }\n\n  async delete() {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(this._modelName, \"delete\", async (span) => {\n      // the original query selects the distinct id + the model.* so we need to clear\n      const sub = this._db.clearSelect().select(\"id\");\n      let builder = db.deleteFrom(this._tableName).where(\"id\", \"in\", sub);\n\n      const query = builder.returning([\"id\"]);\n\n      // final query looks something like:\n      // delete from \"person\" where \"id\" in (select distinct on (\"person\".\"id\") \"id\" from \"person\" where \"person\".\"id\" = $1) returning \"id\"\n\n      span.setAttribute(\n        \"db.statement\",\n        tracing.truncateSQL(query.compile().sql)\n      );\n\n      try {\n        const row = await query.executeTakeFirstOrThrow();\n        return row.id;\n      } catch (e) {\n        throw new DatabaseError(e);\n      }\n    });\n  }\n\n  async findOne() {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(this._modelName, \"findOne\", async (span) => {\n      let builder = db\n        .selectFrom((qb) => {\n          // this._db contains all of the where constraints and joins\n          // we want to include that in the sub query in the same way we\n          // add all of this information into the sub query in the ModelAPI's\n          // implementation of findOne\n          return this._db.as(this._tableName);\n        })\n        .selectAll();\n\n      span.setAttribute(\n        \"db.statement\",\n        tracing.truncateSQL(builder.compile().sql)\n      );\n\n      const row = await builder.executeTakeFirst();\n      if (!row) {\n        return null;\n      }\n\n      return transformRichDataTypes(camelCaseObject(row));\n    });\n  }\n\n  async findMany(params) {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(\n      this._modelName,\n      \"findMany\",\n      async (span) => {\n        const context = new QueryContext(\n          [this._tableName],\n          this._tableConfigMap\n        );\n\n        let builder = db\n          .selectFrom((qb) => {\n            // this._db contains all of the where constraints and joins\n            // we want to include that in the sub query in the same way we\n            // add all of this information into the sub query in the ModelAPI's\n            // implementation of findMany\n            return this._db.as(this._tableName);\n          })\n          .selectAll();\n\n        // The only constraints added to the main query are the orderBy, limit and offset as they are performed on the \"outer\" set\n        if (params?.limit) {\n          builder = applyLimit(context, builder, params.limit);\n        }\n\n        if (params?.offset) {\n          builder = applyOffset(context, builder, params.offset);\n        }\n\n        if (\n          params?.orderBy !== undefined &&\n          Object.keys(params?.orderBy).length > 0\n        ) {\n          builder = applyOrderBy(\n            context,\n            builder,\n            this._tableName,\n            params.orderBy\n          );\n        } else {\n          builder = builder.orderBy(`${this._tableName}.id`);\n        }\n\n        const query = builder;\n\n        span.setAttribute(\n          \"db.statement\",\n          tracing.truncateSQL(query.compile().sql)\n        );\n        const rows = await builder.execute();\n        return rows.map((x) => transformRichDataTypes(camelCaseObject(x)));\n      }\n    );\n  }\n\n  /**\n   * Execute query with pagination support.\n   * Returns results along with pageInfo metadata.\n   * @param {Object} params - Pagination parameters\n   * @param {number} [params.first] - Number of items for cursor pagination (forward)\n   * @param {string} [params.after] - Cursor for forward pagination\n   * @param {number} [params.last] - Number of items for cursor pagination (backward)\n   * @param {string} [params.before] - Cursor for backward pagination\n   * @param {number} [params.limit] - Page size for offset pagination\n   * @param {number} [params.offset] - Offset for offset pagination\n   * @param {Object} [params.orderBy] - Ordering specification\n   * @returns {Promise<{results: any[], pageInfo: Object}>}\n   */\n  async findManyWithPageInfo(params = {}) {\n    const db = useDatabase();\n\n    return tracing.withDbQuerySpan(\n      this._modelName,\n      \"findManyWithPageInfo\",\n      async (span) => {\n        const context = new QueryContext(\n          [this._tableName],\n          this._tableConfigMap\n        );\n\n        // Determine pagination mode and direction\n        const isOffsetPagination = params.limit != null && params.limit > 0;\n        const isBackward = params.last != null && params.last > 0;\n\n        // Default page size - matches Go runtime (runtime/actions/pagination.go)\n        const DEFAULT_PAGE_SIZE = 50;\n\n        // Determine limit based on pagination mode and direction\n        let limit;\n        if (isOffsetPagination) {\n          limit = params.limit;\n        } else if (isBackward) {\n          limit = params.last;\n        } else {\n          // Forward cursor pagination - use first if provided, otherwise default\n          limit = params.first ?? DEFAULT_PAGE_SIZE;\n        }\n\n        // Get total count first (using the same filters from this._db)\n        const countQuery = db\n          .selectFrom((qb) => this._db.as(this._tableName))\n          .select(db.fn.countAll().as(\"total\"));\n\n        const countResult = await countQuery.executeTakeFirst();\n        const totalCount = Number(countResult?.total ?? 0);\n\n        // Build main query from existing filters\n        let builder = db\n          .selectFrom((qb) => this._db.as(this._tableName))\n          .selectAll();\n\n        // Normalize orderBy to object format\n        // Input can be array format [{ title: \"desc\" }] or object format { title: \"desc\" }\n        let normalizedOrderBy = null;\n        if (params.orderBy) {\n          if (Array.isArray(params.orderBy)) {\n            // Convert array format to object format\n            normalizedOrderBy = {};\n            for (const item of params.orderBy) {\n              for (const [key, dir] of Object.entries(item)) {\n                normalizedOrderBy[key] = dir;\n              }\n            }\n          } else {\n            normalizedOrderBy = params.orderBy;\n          }\n        }\n\n        // Parse orderBy into an array of {field, direction} for cursor filtering\n        // Always include id as final tiebreaker (matching Go runtime behavior)\n        const orderByFields = [];\n        const hasCustomOrderBy =\n          normalizedOrderBy !== null &&\n          Object.keys(normalizedOrderBy).length > 0;\n\n        if (hasCustomOrderBy) {\n          for (const [key, dir] of Object.entries(normalizedOrderBy)) {\n            orderByFields.push({\n              field: key,\n              direction: String(dir).toLowerCase(),\n            });\n          }\n        }\n        // Always add id as final ordering field for deterministic pagination\n        orderByFields.push({ field: \"id\", direction: \"asc\" });\n\n        // Apply ordering - reverse for backward pagination\n        // Always add id as secondary ordering for deterministic pagination with tiebreaker\n        if (hasCustomOrderBy) {\n          // For backward pagination, reverse all sort directions to get the \"last N\" items\n          const effectiveOrderBy = isBackward\n            ? Object.fromEntries(\n                Object.entries(normalizedOrderBy).map(([key, dir]) => [\n                  key,\n                  String(dir).toLowerCase() === \"asc\" ? \"desc\" : \"asc\",\n                ])\n              )\n            : normalizedOrderBy;\n\n          builder = applyOrderBy(\n            context,\n            builder,\n            this._tableName,\n            effectiveOrderBy\n          );\n          // Add id as tiebreaker for deterministic ordering when primary field has duplicates\n          const idDirection = isBackward ? \"desc\" : \"asc\";\n          builder = builder.orderBy(`${this._tableName}.id`, idDirection);\n        } else {\n          // Default ordering by id - reverse for backward pagination\n          const direction = isBackward ? \"desc\" : \"asc\";\n          builder = builder.orderBy(`${this._tableName}.id`, direction);\n        }\n\n        // Apply cursor filter based on direction and ordering\n        // This implements proper cursor pagination that works with custom orderBy\n        // Uses compound comparison: (field op value) OR (field = value AND id op cursorId)\n        // This handles tiebreakers when multiple records have the same ordering field value\n        const cursor = isBackward ? params.before : params.after;\n        if (cursor) {\n          // Look up the cursor row to get its value for the primary ordering field\n          const primaryField = orderByFields[0];\n          // Convert to snake_case for database column names\n          const primaryFieldCol = snakeCase(primaryField.field);\n          const cursorLookup = await db\n            .selectFrom((qb) => this._db.as(this._tableName))\n            .select([primaryFieldCol, \"id\"])\n            .where(`${this._tableName}.id`, \"=\", cursor)\n            .limit(1)\n            .executeTakeFirst();\n\n          if (cursorLookup) {\n            const primaryValue = cursorLookup[primaryFieldCol];\n            const cursorId = cursorLookup.id;\n\n            // Determine comparison operator based on direction and pagination direction\n            let primaryOp;\n            if (primaryField.direction === \"asc\") {\n              primaryOp = isBackward ? \"<\" : \">\";\n            } else {\n              primaryOp = isBackward ? \">\" : \"<\";\n            }\n\n            // ID comparison follows the same direction as pagination\n            const idOp = isBackward ? \"<\" : \">\";\n\n            if (primaryValue === null) {\n              if (primaryOp === \">\") {\n                // For \">\" comparison with null: anything non-null is greater\n                // Use compound: (field IS NOT NULL) OR (field IS NULL AND id > cursorId)\n                builder = builder.where((eb) =>\n                  eb.or([\n                    eb(`${this._tableName}.${primaryFieldCol}`, \"is not\", null),\n                    eb.and([\n                      eb(`${this._tableName}.${primaryFieldCol}`, \"is\", null),\n                      eb(`${this._tableName}.id`, idOp, cursorId),\n                    ]),\n                  ])\n                );\n              } else {\n                // For \"<\" comparison with null: nothing is less than null, only tiebreaker on id\n                builder = builder.where((eb) =>\n                  eb.and([\n                    eb(`${this._tableName}.${primaryFieldCol}`, \"is\", null),\n                    eb(`${this._tableName}.id`, idOp, cursorId),\n                  ])\n                );\n              }\n            } else {\n              // Compound comparison: (field op value) OR (field = value AND id op cursorId)\n              builder = builder.where((eb) =>\n                eb.or([\n                  eb(\n                    `${this._tableName}.${primaryFieldCol}`,\n                    primaryOp,\n                    primaryValue\n                  ),\n                  eb.and([\n                    eb(\n                      `${this._tableName}.${primaryFieldCol}`,\n                      \"=\",\n                      primaryValue\n                    ),\n                    eb(`${this._tableName}.id`, idOp, cursorId),\n                  ]),\n                ])\n              );\n            }\n          } else {\n            // Cursor not found - return empty results\n            builder = builder.where(\n              `${this._tableName}.id`,\n              \"=\",\n              \"___NONEXISTENT_ID___\"\n            );\n          }\n        }\n\n        // Apply limit only if specified\n        if (limit != null) {\n          builder = applyLimit(context, builder, limit);\n        }\n\n        // Apply offset for offset pagination\n        if (isOffsetPagination && params.offset) {\n          builder = applyOffset(context, builder, params.offset);\n        }\n\n        // Execute main query\n        span.setAttribute(\n          \"db.statement\",\n          tracing.truncateSQL(builder.compile().sql)\n        );\n        let rows = await builder.execute();\n\n        // For backward pagination, reverse results to restore natural order\n        if (isBackward) {\n          rows = rows.reverse();\n        }\n\n        // Transform results\n        const results = rows.map((x) =>\n          transformRichDataTypes(camelCaseObject(x))\n        );\n\n        // Check hasNextPage using orderBy-aware compound comparison\n        // Uses: (field op value) OR (field = value AND id op lastId) for proper tiebreaker handling\n        let hasNextPage = false;\n        if (isOffsetPagination) {\n          // For offset pagination, calculate hasNextPage from totalCount\n          hasNextPage = totalCount > (params.offset || 0) + limit;\n        } else if (\n          limit != null &&\n          results.length === limit &&\n          results.length > 0\n        ) {\n          // For cursor pagination, check if more records exist after the last one\n          const lastResult = results[results.length - 1];\n          const primaryField = orderByFields[0];\n          // Convert to snake_case for database column names\n          const primaryFieldCol = snakeCase(primaryField.field);\n          const primaryValue = lastResult[primaryField.field];\n          const lastId = lastResult.id;\n          const primaryOp = primaryField.direction === \"asc\" ? \">\" : \"<\";\n\n          let nextCheckQuery = db\n            .selectFrom((qb) => this._db.as(this._tableName))\n            .select(\"id\")\n            .limit(1);\n\n          if (primaryValue === null) {\n            if (primaryOp === \">\") {\n              // For \">\" with null: anything non-null is greater, or same null with greater id\n              nextCheckQuery = nextCheckQuery.where((eb) =>\n                eb.or([\n                  eb(`${this._tableName}.${primaryFieldCol}`, \"is not\", null),\n                  eb.and([\n                    eb(`${this._tableName}.${primaryFieldCol}`, \"is\", null),\n                    eb(`${this._tableName}.id`, \">\", lastId),\n                  ]),\n                ])\n              );\n            } else {\n              // For \"<\" with null: nothing is less than null, only tiebreaker\n              nextCheckQuery = nextCheckQuery.where((eb) =>\n                eb.and([\n                  eb(`${this._tableName}.${primaryFieldCol}`, \"is\", null),\n                  eb(`${this._tableName}.id`, \">\", lastId),\n                ])\n              );\n            }\n          } else {\n            // Compound comparison: (field op value) OR (field = value AND id > lastId)\n            nextCheckQuery = nextCheckQuery.where((eb) =>\n              eb.or([\n                eb(\n                  `${this._tableName}.${primaryFieldCol}`,\n                  primaryOp,\n                  primaryValue\n                ),\n                eb.and([\n                  eb(\n                    `${this._tableName}.${primaryFieldCol}`,\n                    \"=\",\n                    primaryValue\n                  ),\n                  eb(`${this._tableName}.id`, \">\", lastId),\n                ]),\n              ])\n            );\n          }\n\n          const nextRecord = await nextCheckQuery.executeTakeFirst();\n          hasNextPage = nextRecord != null;\n        }\n        // If no limit specified, hasNextPage remains false (all results returned)\n\n        // Build pageInfo\n        const pageInfo = {\n          count: results.length,\n          totalCount: totalCount,\n          hasNextPage: hasNextPage,\n          startCursor: results.length > 0 ? results[0].id : \"\",\n          endCursor: results.length > 0 ? results[results.length - 1].id : \"\",\n        };\n\n        // Add pageNumber for offset pagination\n        if (isOffsetPagination && limit > 0) {\n          pageInfo.pageNumber = 1 + Math.floor((params.offset || 0) / limit);\n        }\n\n        return { results, pageInfo };\n      }\n    );\n  }\n}\n\nexport { QueryBuilder };\n","import { ModelAPI } from \"./ModelAPI\";\n\n/**\n * UnionAPI is the model API for a union: a read-only fact set assembled from several models\n * and compiled to a database view.\n *\n * A union is just a relation to read from, so this reuses ModelAPI's query machinery pointed\n * at the view, and exposes only the read methods. The generated TypeScript omits the write\n * methods entirely, so a write is a compile error; this class is the runtime half of that\n * guarantee, and Postgres refuses writes to a UNION ALL view regardless.\n */\nclass UnionAPI {\n  /**\n   * @param {string} viewName The name of the view this union compiles to\n   * @param {import(\"./ModelAPI\").TableConfigMap} tableConfigMap\n   * @param {object} fileFieldsMap\n   */\n  constructor(viewName, tableConfigMap = {}, fileFieldsMap = {}) {\n    // The second argument used to be a default-values function and is no longer used; a union\n    // has no defaults to give in any case, since nothing is ever written to it.\n    this._model = new ModelAPI(\n      viewName,\n      () => ({}),\n      tableConfigMap,\n      fileFieldsMap\n    );\n  }\n\n  /**\n   * Finds a single fact.\n   */\n  async findOne(where = {}) {\n    return this._model.findOne(where);\n  }\n\n  /**\n   * Finds multiple facts.\n   */\n  async findMany(params) {\n    return this._model.findMany(params);\n  }\n\n  /**\n   * Builds a query over the fact set.\n   */\n  where(conditions) {\n    return this._model.where(conditions);\n  }\n}\n\nexport { UnionAPI };\n","import * as tracing from \"./tracing\";\nimport jwt from \"jsonwebtoken\";\nimport { ModelAPI } from \"./ModelAPI\";\nimport { snakeCase } from \"./casing\";\nimport { buildServiceAuthHeaders } from \"./auth/serviceToken\";\nimport { isInDatabaseTransaction } from \"./database\";\n\n/**\n * Builds the headers for the API request including authentication.\n * @param {Object|null} identity Optional identity object for authentication\n * @param {string|null} authToken Optional auth token for authentication\n * @returns {Record<string, string>} Headers object\n */\nfunction buildHeaders(identity, authToken) {\n  // Default: trusted server-to-server call from backend code. Mint a subjectless `tasks`\n  // service token; the runtime treats it as a service principal and skips authorization.\n  if (identity === null && authToken === null) {\n    return buildServiceAuthHeaders(\"tasks\");\n  }\n\n  const headers = { \"Content-Type\": \"application/json\" };\n\n  // An Identity instance is provided - make a person-subject JWT (explicit, user-scoped:\n  // the tasks API authenticates as this identity and enforces its topic permissions).\n  if (identity !== null) {\n    const base64pk = process.env.KEEL_PRIVATE_KEY;\n    let privateKey = undefined;\n\n    if (base64pk) {\n      privateKey = Buffer.from(base64pk, \"base64\").toString(\"utf8\");\n    }\n\n    headers[\"Authorization\"] =\n      \"Bearer \" +\n      jwt.sign({}, privateKey, {\n        algorithm: privateKey ? \"RS256\" : \"none\",\n        expiresIn: 60 * 60 * 24,\n        subject: identity.id,\n        issuer: \"https://keel.so\",\n      });\n  }\n\n  // If an auth token is provided that can be sent as-is\n  if (authToken !== null) {\n    headers[\"Authorization\"] = \"Bearer \" + authToken;\n  }\n\n  return headers;\n}\n\n// Exported for unit testing only.\nexport const __buildHeadersForTest = buildHeaders;\n\n/**\n * Gets the API URL from environment variables.\n * @returns {string} The API URL\n * @throws {Error} If the API URL is not set\n */\nfunction getApiUrl() {\n  const apiUrl = process.env.KEEL_API_URL;\n  if (!apiUrl) {\n    throw new Error(\"KEEL_API_URL environment variable is not set\");\n  }\n  return apiUrl;\n}\n\n/**\n * Task provides action methods for task instances.\n * These methods are attached to entities returned from findOne/findMany.\n */\nclass Task {\n  /**\n   * Sets the identity for authentication and returns this instance.\n   * @param {Object} identity The identity object\n   * @returns {Task} This Task instance with the identity set\n   */\n  withIdentity(identity) {\n    this._identity = identity;\n    this._authToken = null;\n    return this;\n  }\n\n  /**\n   * Sets the auth token for authentication and returns this instance.\n   * @param {string} token The auth token to use\n   * @returns {Task} This Task instance with the auth token set\n   */\n  withAuthToken(token) {\n    this._identity = null;\n    this._authToken = token;\n    return this;\n  }\n\n  /**\n   * Updates the current task instance with data from the API response.\n   * The API returns camelCase fields matching the Go struct JSON tags.\n   * @param {Object} data The API response data\n   */\n  _updateFromResponse(data) {\n    this.id = data.id;\n    this.status = data.status;\n    this.deferredUntil = data.deferredUntil\n      ? new Date(data.deferredUntil)\n      : null;\n    this.createdAt = new Date(data.createdAt);\n    this.updatedAt = new Date(data.updatedAt);\n    this.assignedToUserId = data.assignedToUser ?? null;\n    this.assignedToTeam = data.assignedToTeam ?? null;\n    this.assignedAt = data.assignedAt ? new Date(data.assignedAt) : null;\n    this.resolvedAt = data.resolvedAt ? new Date(data.resolvedAt) : null;\n    this.flowRunId = data.flowRunId ?? null;\n\n    // We do not copy the data fields as they wont have changed.\n  }\n\n  /**\n   * Assigns the task to a user or team.\n   * @param {Object} options Options containing userId or teamName (exactly one required)\n   * @param {string} [options.userId] The ID of the user to assign the task to\n   * @param {string} [options.teamName] The name of the team to assign the task to\n   * @returns {Promise<void>}\n   */\n  async assign({ userId, teamName }) {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"assign_task\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/assign`;\n\n      const body = {};\n      if (userId !== undefined) {\n        body.assigned_to_user = userId;\n      }\n      if (teamName !== undefined) {\n        body.assigned_to_team = teamName;\n      }\n\n      const response = await fetch(url, {\n        method: \"PUT\",\n        headers: buildHeaders(this._identity, this._authToken),\n        body: JSON.stringify(body),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to assign task: ${response.status} ${response.statusText} - ${\n            errorBody.message || JSON.stringify(errorBody)\n          }`\n        );\n      }\n\n      const result = await response.json();\n      this._updateFromResponse(result);\n    });\n  }\n\n  /**\n   * Starts the task, creating and running the associated flow.\n   * @returns {Promise<void>}\n   */\n  async start() {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"start_task\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/start`;\n\n      const response = await fetch(url, {\n        method: \"PUT\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to start task: ${response.status} ${response.statusText} - ${\n            errorBody.message || JSON.stringify(errorBody)\n          }`\n        );\n      }\n\n      const result = await response.json();\n      this._updateFromResponse(result);\n    });\n  }\n\n  /**\n   * Completes the task.\n   * @returns {Promise<void>}\n   */\n  async complete() {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"complete_task\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/complete`;\n\n      const response = await fetch(url, {\n        method: \"PUT\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to complete task: ${response.status} ${\n            response.statusText\n          } - ${errorBody.message || JSON.stringify(errorBody)}`\n        );\n      }\n\n      const result = await response.json();\n      this._updateFromResponse(result);\n    });\n  }\n\n  /**\n   * Defers the task until a specified date.\n   * @param {Object} options Options containing deferUntil\n   * @param {Date} options.deferUntil The date to defer the task until\n   * @returns {Promise<void>}\n   */\n  async defer({ deferUntil }) {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"defer_task\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/defer`;\n\n      const response = await fetch(url, {\n        method: \"PUT\",\n        headers: buildHeaders(this._identity, this._authToken),\n        body: JSON.stringify({ defer_until: deferUntil.toISOString() }),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to defer task: ${response.status} ${response.statusText} - ${\n            errorBody.message || JSON.stringify(errorBody)\n          }`\n        );\n      }\n\n      const result = await response.json();\n      this._updateFromResponse(result);\n    });\n  }\n\n  /**\n   * Cancels the task.\n   * @returns {Promise<void>}\n   */\n  async cancel() {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"cancel_task\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/cancel`;\n\n      const response = await fetch(url, {\n        method: \"PUT\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to cancel task: ${response.status} ${response.statusText} - ${\n            errorBody.message || JSON.stringify(errorBody)\n          }`\n        );\n      }\n\n      const result = await response.json();\n      this._updateFromResponse(result);\n    });\n  }\n\n  /**\n   * Unassigns the task, removing the current assignee.\n   * @returns {Promise<void>}\n   */\n  async unassign() {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"unassign_task\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/unassign`;\n\n      const response = await fetch(url, {\n        method: \"PUT\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to unassign task: ${response.status} ${\n            response.statusText\n          } - ${errorBody.message || JSON.stringify(errorBody)}`\n        );\n      }\n\n      const result = await response.json();\n      this._updateFromResponse(result);\n    });\n  }\n}\n\n/**\n * TaskAPI provides methods for creating and querying tasks.\n * It combines HTTP API calls for task actions (create, assign, complete, etc.)\n * with ModelAPI for querying (findOne, findMany).\n */\nclass TaskAPI {\n  /**\n   * @param {string} taskName The name of the task/topic\n   * @param {Object} tableConfigMap Configuration for table relationships\n   * @param {Object|null} identity Optional identity object for authentication\n   * @param {string|null} authToken Optional auth token for authentication\n   */\n  constructor(\n    taskName,\n    tableConfigMap = {},\n    identity = null,\n    authToken = null\n  ) {\n    this._taskName = taskName;\n    this._tableName = snakeCase(taskName);\n    this._tableConfigMap = tableConfigMap;\n    this._identity = identity;\n    this._authToken = authToken;\n\n    // Use ModelAPI internally for database queries\n    this._modelAPI = new ModelAPI(this._tableName, null, tableConfigMap);\n  }\n\n  /**\n   * Returns a new TaskAPI instance that will use the given identity for authentication.\n   * @param {Object} identity The identity object\n   * @returns {TaskAPI} A new TaskAPI instance with the identity set\n   */\n  withIdentity(identity) {\n    return new TaskAPI(this._taskName, this._tableConfigMap, identity, null);\n  }\n\n  /**\n   * Returns a new TaskAPI instance that will use the given auth token for authentication.\n   * @param {string} token The auth token to use\n   * @returns {TaskAPI} A new TaskAPI instance with the auth token set\n   */\n  withAuthToken(token) {\n    return new TaskAPI(this._taskName, this._tableConfigMap, null, token);\n  }\n\n  /**\n   * Creates a new task with the given data by calling the tasks API.\n   * After creation, fetches the full task data from the database to include all fields.\n   * @param {Object} data The task data fields\n   * @param {Object} options Optional settings like deferredUntil\n   * @returns {Promise<Task>} The created task with all fields\n   */\n  async create(data = {}, options = {}) {\n    const name = tracing.spanNameForServiceAPI(\"tasks\", \"create_task\");\n\n    return tracing.withSpan(name, async () => {\n      if (isInDatabaseTransaction()) {\n        throw new Error(\n          `tasks.${this._taskName}.create() cannot be called from a transactional function because the Tasks API cannot observe uncommitted database writes. Set the function's config.dbTransaction to false or create the task after the transaction commits.`\n        );\n      }\n\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/topics/json/${this._taskName}/tasks`;\n\n      const body = {\n        data: data,\n      };\n\n      if (options.deferredUntil) {\n        body.defer_until = options.deferredUntil.toISOString();\n      }\n\n      const response = await fetch(url, {\n        method: \"POST\",\n        headers: buildHeaders(this._identity, this._authToken),\n        body: JSON.stringify(body),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to create task: ${response.status} ${response.statusText} - ${\n            errorBody.message || JSON.stringify(errorBody)\n          }`\n        );\n      }\n\n      const result = await response.json();\n\n      // Fetch the full task data from the database to get all fields (including custom fields like orderId)\n      const task = await this.findOne({ id: result.id });\n      if (!task) {\n        throw new Error(`Failed to fetch created task with id: ${result.id}`);\n      }\n\n      return task;\n    });\n  }\n\n  /**\n   * Wraps an entity with Task methods by setting its prototype and adding required fields.\n   * @param {Object} entity The entity from ModelAPI\n   * @returns {Task} The entity with Task methods\n   */\n  _wrapAsTask(entity) {\n    if (!entity) return null;\n\n    entity._taskName = this._taskName;\n    entity._identity = this._identity;\n    entity._authToken = this._authToken;\n    Object.setPrototypeOf(entity, Task.prototype);\n\n    return entity;\n  }\n\n  /**\n   * Finds a single task matching the given conditions.\n   * Returns a Task instance with both entity fields and action methods.\n   * @param {Object} where Conditions to match\n   * @returns {Promise<Task|null>} The Task instance or null if not found\n   */\n  async findOne(where = {}) {\n    const entity = await this._modelAPI.findOne(where);\n    return this._wrapAsTask(entity);\n  }\n\n  /**\n   * Finds multiple tasks matching the given conditions.\n   * Returns Task instances with both entity fields and action methods.\n   * @param {Object} params Query parameters including where, limit, offset, orderBy\n   * @returns {Promise<Array<Task>>} Array of Task instances\n   */\n  async findMany(params = {}) {\n    const entities = await this._modelAPI.findMany(params);\n    return entities.map((entity) => this._wrapAsTask(entity));\n  }\n}\n\nexport { TaskAPI, Task };\n","import jwt from \"jsonwebtoken\";\nimport { getServiceToken } from \"./serviceTokenStore\";\n\n// buildServiceAuthHeaders returns ready-to-send request headers carrying the first-party service\n// token for `audience`. In a normal invocation the token is minted by the Go runtime (which holds\n// the signing key) and passed to this process in the invoke meta, so the signing key never enters\n// the deployed functions process. The Keel runtime verifies the audience to confirm the caller is\n// trusted first-party backend code (not an end user). Service tokens are subjectless by rule: the\n// audience is the trust signal, and no acting identity is carried today.\nexport function buildServiceAuthHeaders(\n  audience: string\n): Record<string, string> {\n  const token = getServiceToken(audience) ?? signServiceToken(audience);\n  if (!token) {\n    throw new Error(\n      `no ${audience} service token available for this invocation; the runtime did not provide one`\n    );\n  }\n\n  return {\n    \"Content-Type\": \"application/json\",\n    Authorization: `Bearer ${token}`,\n  };\n}\n\n// signServiceToken is the fallback for contexts that drive the SDK directly rather than through a\n// runtime invocation — e.g. `keel test` / `keel run`, where this process holds KEEL_PRIVATE_KEY and\n// there is no invoke meta to carry a runtime-minted token. Deployed function invocations never reach\n// this path: they receive their token via the invoke meta and the signing key is absent from the\n// process, so this returns undefined and buildServiceAuthHeaders surfaces the missing-token error.\nfunction signServiceToken(audience: string): string | undefined {\n  const base64pk = process.env.KEEL_PRIVATE_KEY;\n  if (!base64pk) {\n    return undefined;\n  }\n  const privateKey = Buffer.from(base64pk, \"base64\").toString(\"utf8\");\n\n  return jwt.sign({}, privateKey, {\n    algorithm: \"RS256\",\n    expiresIn: 60 * 60 * 24,\n    audience,\n    issuer: \"https://keel.so\",\n  });\n}\n","import { AsyncLocalStorage } from \"async_hooks\";\n\n// ServiceTokens maps an audience (e.g. \"notifications\", \"integration-proxy\") to a short-lived\n// first-party service token minted by the Go runtime for the current invocation.\nexport type ServiceTokens = Record<string, string>;\n\nconst serviceTokenStore = new AsyncLocalStorage<ServiceTokens>();\n\n// withServiceTokens makes the runtime-minted service tokens (passed in the invoke meta) available\n// to buildServiceAuthHeaders for the duration of a single function invocation. The functions-runtime\n// no longer signs these tokens itself, so the signing key never enters the functions process.\nexport function withServiceTokens<T>(\n  tokens: ServiceTokens | undefined,\n  cb: () => T\n): T {\n  return serviceTokenStore.run(tokens ?? {}, cb);\n}\n\n// getServiceToken returns the runtime-minted token for the given audience, or undefined if none is\n// available for this invocation (e.g. no token was passed, or the call is outside an invocation).\nexport function getServiceToken(audience: string): string | undefined {\n  return serviceTokenStore.getStore()?.[audience];\n}\n","import * as tracing from \"./tracing\";\nimport jwt from \"jsonwebtoken\";\nimport { getCallerIdentity } from \"./auth/callerIdentityStore\";\nimport { buildServiceAuthHeaders } from \"./auth/serviceToken\";\n\n/**\n * Builds the headers for the API request including authentication.\n *\n * Auth resolution order:\n *   1. Explicit auth token (withAuthToken)\n *   2. Explicit identity (withIdentity)\n *   3. Ambient caller identity (whoever is running the flow/function)\n *   4. Unauthenticated\n *\n * @param {Object|null} identity Optional identity object for authentication\n * @param {string|null} authToken Optional auth token for authentication\n * @returns {Object} Headers object\n */\nfunction buildHeaders(identity, authToken) {\n  const headers = { \"Content-Type\": \"application/json\" };\n\n  // 1. An explicit auth token is sent as-is and takes precedence.\n  if (authToken !== null) {\n    headers[\"Authorization\"] = \"Bearer \" + authToken;\n    return headers;\n  }\n\n  // 2. Explicit withIdentity(...), else 3. the ambient caller identity.\n  const effectiveIdentity = identity !== null ? identity : getCallerIdentity();\n\n  // 4. Neither is available -> unauthenticated (no Authorization header).\n  if (effectiveIdentity) {\n    const base64pk = process.env.KEEL_PRIVATE_KEY;\n    let privateKey = undefined;\n\n    if (base64pk) {\n      privateKey = Buffer.from(base64pk, \"base64\").toString(\"utf8\");\n    }\n\n    headers[\"Authorization\"] =\n      \"Bearer \" +\n      jwt.sign({}, privateKey, {\n        algorithm: privateKey ? \"RS256\" : \"none\",\n        expiresIn: 60 * 60 * 24,\n        subject: effectiveIdentity.id,\n        issuer: \"https://keel.so\",\n      });\n  }\n\n  return headers;\n}\n\n/**\n * Builds the headers for a signed-link (share) request.\n *\n * Unlike buildHeaders, this does NOT consult the ambient caller identity: minting/listing/revoking\n * shareable links from backend code defaults to a first-party `flows` service token, which the\n * runtime treats as trusted and always passes the flow's `share` permission. An explicit identity\n * (withIdentity) or auth token (withAuthToken) opts into user-scoped auth instead, where the flow's\n * @permission(actions: [share]) rule is enforced — this is the \"user's manual minting\" path.\n *\n * @param {Object|null} identity Explicit identity object (withIdentity), or null\n * @param {string|null} authToken Explicit auth token (withAuthToken), or null\n * @returns {Record<string, string>} Headers object\n */\nfunction buildSignedLinkHeaders(identity, authToken) {\n  // Default: trusted server-to-server call. Mint a subjectless `flows` service token; the runtime\n  // treats it as a service principal and skips authorization.\n  if (identity === null && authToken === null) {\n    return buildServiceAuthHeaders(\"flows\");\n  }\n\n  const headers = { \"Content-Type\": \"application/json\" };\n\n  // An explicit identity - make a person-subject JWT (user-scoped: the flows API authenticates as\n  // this identity and enforces its share permission).\n  if (identity !== null) {\n    const base64pk = process.env.KEEL_PRIVATE_KEY;\n    let privateKey = undefined;\n\n    if (base64pk) {\n      privateKey = Buffer.from(base64pk, \"base64\").toString(\"utf8\");\n    }\n\n    headers[\"Authorization\"] =\n      \"Bearer \" +\n      jwt.sign({}, privateKey, {\n        algorithm: privateKey ? \"RS256\" : \"none\",\n        expiresIn: 60 * 60 * 24,\n        subject: identity.id,\n        issuer: \"https://keel.so\",\n      });\n  }\n\n  // An explicit auth token is sent as-is.\n  if (authToken !== null) {\n    headers[\"Authorization\"] = \"Bearer \" + authToken;\n  }\n\n  return headers;\n}\n\n// Exported for unit testing only.\nexport const __buildSignedLinkHeadersForTest = buildSignedLinkHeaders;\n\n/**\n * Gets the API URL from environment variables.\n * @returns {string} The API URL\n * @throws {Error} If the API URL is not set\n */\nfunction getApiUrl() {\n  const apiUrl = process.env.KEEL_API_URL;\n  if (!apiUrl) {\n    throw new Error(\"KEEL_API_URL environment variable is not set\");\n  }\n  return apiUrl;\n}\n\n/**\n * Converts a signed link API record's date fields to Date instances.\n * @param {Object} data The signed link record from the API\n * @returns {Object} The record with date fields as Date instances\n */\nfunction toSignedLinkRecord(data) {\n  return {\n    ...data,\n    expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,\n    revokedAt: data.revokedAt ? new Date(data.revokedAt) : null,\n    createdAt: new Date(data.createdAt),\n    updatedAt: new Date(data.updatedAt),\n  };\n}\n\n/**\n * FlowRun represents a flow run instance with action methods.\n */\nclass FlowRun {\n  /**\n   * @param {Object} data The flow run data from the API\n   * @param {string} flowName The name of the flow\n   * @param {Object|null} identity Optional identity object for authentication\n   * @param {string|null} authToken Optional auth token for authentication\n   */\n  constructor(data, flowName, identity = null, authToken = null) {\n    this.id = data.id;\n    this.name = data.name;\n    this.status = data.status;\n    this.inputs = data.inputs;\n    this.outputs = data.outputs;\n    this.steps = data.steps;\n    this.pendingStep = data.pendingStep;\n    this.createdAt = data.createdAt ? new Date(data.createdAt) : undefined;\n    this.updatedAt = data.updatedAt ? new Date(data.updatedAt) : undefined;\n    this.completedAt = data.completedAt\n      ? new Date(data.completedAt)\n      : undefined;\n\n    // Store auth context for action methods\n    this._flowName = flowName;\n    this._identity = identity;\n    this._authToken = authToken;\n  }\n\n  /**\n   * Returns a new FlowRun instance that will use the given identity for authentication.\n   * @param {Object} identity The identity object\n   * @returns {FlowRun} A new FlowRun instance with the identity set\n   */\n  withIdentity(identity) {\n    const data = this._toApiData();\n    return new FlowRun(data, this._flowName, identity, null);\n  }\n\n  /**\n   * Returns a new FlowRun instance that will use the given auth token for authentication.\n   * @param {string} token The auth token to use\n   * @returns {FlowRun} A new FlowRun instance with the auth token set\n   */\n  withAuthToken(token) {\n    const data = this._toApiData();\n    return new FlowRun(data, this._flowName, null, token);\n  }\n\n  /**\n   * Converts the flow run back to API data format for creating new instances.\n   * @returns {Object} The flow run data in API format\n   */\n  _toApiData() {\n    return {\n      id: this.id,\n      name: this.name,\n      status: this.status,\n      inputs: this.inputs,\n      outputs: this.outputs,\n      steps: this.steps,\n      pendingStep: this.pendingStep,\n      createdAt: this.createdAt?.toISOString(),\n      updatedAt: this.updatedAt?.toISOString(),\n      completedAt: this.completedAt?.toISOString(),\n    };\n  }\n\n  /**\n   * Refreshes the flow run state from the API.\n   * @returns {Promise<FlowRun>} The updated flow run\n   */\n  async refresh() {\n    const name = tracing.spanNameForServiceAPI(\"flows\", \"get_run\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/flows/json/${encodeURIComponent(\n        this._flowName\n      )}/${encodeURIComponent(this.id)}`;\n\n      const response = await fetch(url, {\n        method: \"GET\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to refresh flow run: ${response.status} ${\n            response.statusText\n          } - ${errorBody.message || JSON.stringify(errorBody)}`\n        );\n      }\n\n      const result = await response.json();\n      return new FlowRun(\n        result,\n        this._flowName,\n        this._identity,\n        this._authToken\n      );\n    });\n  }\n\n  /**\n   * Cancels the flow run.\n   * @returns {Promise<FlowRun>} The updated flow run\n   */\n  async cancel() {\n    const name = tracing.spanNameForServiceAPI(\"flows\", \"cancel_run\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/flows/json/${encodeURIComponent(\n        this._flowName\n      )}/${encodeURIComponent(this.id)}/cancel`;\n\n      const response = await fetch(url, {\n        method: \"POST\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to cancel flow run: ${response.status} ${\n            response.statusText\n          } - ${errorBody.message || JSON.stringify(errorBody)}`\n        );\n      }\n\n      const result = await response.json();\n      return new FlowRun(\n        result,\n        this._flowName,\n        this._identity,\n        this._authToken\n      );\n    });\n  }\n}\n\n/**\n * FlowsAPI provides methods for starting and managing flows via the HTTP API.\n */\nclass FlowsAPI {\n  /**\n   * @param {string} flowName The name of the flow\n   * @param {Object|null} identity Optional identity object for authentication\n   * @param {string|null} authToken Optional auth token for authentication\n   */\n  constructor(flowName, identity = null, authToken = null) {\n    this._flowName = flowName;\n    this._identity = identity;\n    this._authToken = authToken;\n  }\n\n  /**\n   * Returns a new FlowsAPI instance that will use the given identity for authentication.\n   * @param {Object} identity The identity object\n   * @returns {FlowsAPI} A new FlowsAPI instance with the identity set\n   */\n  withIdentity(identity) {\n    return new FlowsAPI(this._flowName, identity, null);\n  }\n\n  /**\n   * Returns a new FlowsAPI instance that will use the given auth token for authentication.\n   * @param {string} token The auth token to use\n   * @returns {FlowsAPI} A new FlowsAPI instance with the auth token set\n   */\n  withAuthToken(token) {\n    return new FlowsAPI(this._flowName, null, token);\n  }\n\n  /**\n   * Starts a new flow run with the given inputs.\n   * @param {Object} inputs The flow input data\n   * @returns {Promise<FlowRun>} The created flow run\n   */\n  async start(inputs = {}) {\n    const name = tracing.spanNameForServiceAPI(\"flows\", \"start\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/flows/json/${encodeURIComponent(this._flowName)}`;\n\n      const response = await fetch(url, {\n        method: \"POST\",\n        headers: buildHeaders(this._identity, this._authToken),\n        body: JSON.stringify(inputs),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to start flow: ${response.status} ${response.statusText} - ${\n            errorBody.message || JSON.stringify(errorBody)\n          }`\n        );\n      }\n\n      const result = await response.json();\n      return new FlowRun(\n        result,\n        this._flowName,\n        this._identity,\n        this._authToken\n      );\n    });\n  }\n\n  /**\n   * The signed-link management namespace for this flow: create, list and revoke signed links. The\n   * flow must be declared with @externalAccess (the SDK types only expose `signedLinks` on such\n   * flows). By default each operation authenticates with a first-party `flows` service token that\n   * the runtime trusts, so backend code can manage links without satisfying the flow's `share`\n   * permission. Chaining withIdentity()/withAuthToken() switches to user-scoped auth, where the\n   * flow's @permission(actions: [share]) rule is enforced.\n   * @returns {{create: Function, list: Function, revoke: Function}} The signed links API\n   */\n  get signedLinks() {\n    const flowName = this._flowName;\n    const identity = this._identity;\n    const authToken = this._authToken;\n    const shareUrl = () =>\n      `${getApiUrl()}/flows/json/${encodeURIComponent(flowName)}/share`;\n\n    return {\n      /**\n       * Mints a signed link that lets an external, unauthenticated actor execute this flow. Each\n       * time the link is opened a fresh flow run is created; a reusable link can be opened many\n       * times, otherwise it permits exactly one run.\n       * @param {Object} [options] Signed link options\n       * @param {Object} [options.inputs] Default inputs applied to every run created from the link\n       * @param {Date} [options.expiresAt] When the link stops being valid\n       * @param {boolean} [options.reusable] Whether the link can be opened more than once\n       * @returns {Promise<Object>} The created signed link record\n       */\n      async create(options = {}) {\n        const name = tracing.spanNameForServiceAPI(\"flows\", \"share_create\");\n\n        return tracing.withSpan(name, async () => {\n          const body = {};\n          if (options.inputs !== undefined) body.inputs = options.inputs;\n          if (options.reusable !== undefined) body.reusable = options.reusable;\n          if (options.expiresAt !== undefined && options.expiresAt !== null) {\n            body.expiresAt =\n              options.expiresAt instanceof Date\n                ? options.expiresAt.toISOString()\n                : options.expiresAt;\n          }\n\n          const response = await fetch(shareUrl(), {\n            method: \"POST\",\n            headers: buildSignedLinkHeaders(identity, authToken),\n            body: JSON.stringify(body),\n          });\n\n          if (!response.ok) {\n            const errorBody = await response.json().catch(() => ({}));\n            throw new Error(\n              `Failed to create signed link: ${response.status} ${\n                response.statusText\n              } - ${errorBody.message || JSON.stringify(errorBody)}`\n            );\n          }\n\n          return toSignedLinkRecord(await response.json());\n        });\n      },\n\n      /**\n       * Lists the signed links minted for this flow, optionally filtered by status.\n       * @param {Object} [options] List options\n       * @param {\"active\"|\"revoked\"|\"expired\"} [options.status] Only return links with this status\n       * @returns {Promise<{results: Object[]}>} The signed link records\n       */\n      async list(options = {}) {\n        const name = tracing.spanNameForServiceAPI(\"flows\", \"share_list\");\n\n        return tracing.withSpan(name, async () => {\n          let url = shareUrl();\n          if (options.status !== undefined && options.status !== null) {\n            const queryString = new URLSearchParams({\n              status: options.status,\n            }).toString();\n            url = `${url}?${queryString}`;\n          }\n\n          const response = await fetch(url, {\n            method: \"GET\",\n            headers: buildSignedLinkHeaders(identity, authToken),\n          });\n\n          if (!response.ok) {\n            const errorBody = await response.json().catch(() => ({}));\n            throw new Error(\n              `Failed to list signed links: ${response.status} ${\n                response.statusText\n              } - ${errorBody.message || JSON.stringify(errorBody)}`\n            );\n          }\n\n          const result = await response.json();\n          return {\n            results: (result.signedLinks || []).map(toSignedLinkRecord),\n          };\n        });\n      },\n\n      /**\n       * Revokes a signed link so it can no longer be opened. Idempotent, and scoped to this flow's\n       * links.\n       * @param {string} linkId The signed link ID\n       * @returns {Promise<Object>} The revoked signed link record\n       */\n      async revoke(linkId) {\n        const name = tracing.spanNameForServiceAPI(\"flows\", \"share_revoke\");\n\n        return tracing.withSpan(name, async () => {\n          const response = await fetch(\n            `${shareUrl()}/${encodeURIComponent(linkId)}`,\n            {\n              method: \"DELETE\",\n              headers: buildSignedLinkHeaders(identity, authToken),\n            }\n          );\n\n          if (!response.ok) {\n            const errorBody = await response.json().catch(() => ({}));\n            throw new Error(\n              `Failed to revoke signed link: ${response.status} ${\n                response.statusText\n              } - ${errorBody.message || JSON.stringify(errorBody)}`\n            );\n          }\n\n          return toSignedLinkRecord(await response.json());\n        });\n      },\n    };\n  }\n\n  /**\n   * Gets a flow run by ID.\n   * @param {string} runId The flow run ID\n   * @returns {Promise<FlowRun>} The flow run\n   */\n  async get(runId) {\n    const name = tracing.spanNameForServiceAPI(\"flows\", \"get_run\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const url = `${apiUrl}/flows/json/${encodeURIComponent(\n        this._flowName\n      )}/${encodeURIComponent(runId)}`;\n\n      const response = await fetch(url, {\n        method: \"GET\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to get flow run: ${response.status} ${\n            response.statusText\n          } - ${errorBody.message || JSON.stringify(errorBody)}`\n        );\n      }\n\n      const result = await response.json();\n      return new FlowRun(\n        result,\n        this._flowName,\n        this._identity,\n        this._authToken\n      );\n    });\n  }\n\n  /**\n   * Lists flow runs for this flow.\n   * @param {Object} options Optional pagination options\n   * @param {number} options.limit Maximum number of runs to return\n   * @param {number} options.offset Offset for pagination\n   * @returns {Promise<{results: FlowRun[], pageInfo: Object}>} List of flow runs with pagination info\n   */\n  async list(options = {}) {\n    const name = tracing.spanNameForServiceAPI(\"flows\", \"list_runs\");\n\n    return tracing.withSpan(name, async () => {\n      const apiUrl = getApiUrl();\n      const params = new URLSearchParams();\n      if (options.limit) params.set(\"limit\", options.limit.toString());\n      if (options.offset) params.set(\"offset\", options.offset.toString());\n\n      const url = `${apiUrl}/flows/json/${encodeURIComponent(this._flowName)}${\n        params.toString() ? \"?\" + params.toString() : \"\"\n      }`;\n\n      const response = await fetch(url, {\n        method: \"GET\",\n        headers: buildHeaders(this._identity, this._authToken),\n      });\n\n      if (!response.ok) {\n        const errorBody = await response.json().catch(() => ({}));\n        throw new Error(\n          `Failed to list flow runs: ${response.status} ${\n            response.statusText\n          } - ${errorBody.message || JSON.stringify(errorBody)}`\n        );\n      }\n\n      const result = await response.json();\n\n      // Handle both array response and paginated response\n      if (Array.isArray(result)) {\n        return {\n          results: result.map(\n            (run) =>\n              new FlowRun(run, this._flowName, this._identity, this._authToken)\n          ),\n          pageInfo: {\n            totalCount: result.length,\n            hasNextPage: false,\n          },\n        };\n      }\n\n      return {\n        results: (result.results || []).map(\n          (run) =>\n            new FlowRun(run, this._flowName, this._identity, this._authToken)\n        ),\n        pageInfo: result.pageInfo || {\n          totalCount: (result.results || []).length,\n          hasNextPage: false,\n        },\n      };\n    });\n  }\n}\n\nexport { FlowsAPI, FlowRun };\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\n// CallerIdentity is the identity running the current invocation, as passed by the Go\n// runtime in the invoke meta (request.meta.identity). Only `.id` is consumed by the\n// SDK (to mint a JWT subject when acting as the caller).\nexport type CallerIdentity = { id: string; [key: string]: unknown };\n\nconst callerIdentityStore = new AsyncLocalStorage<CallerIdentity | null>();\n\n// withCallerIdentity makes the ambient caller identity available to FlowsAPI for the\n// duration of a single function invocation, so that share/link calls default to acting\n// as whoever is running the flow or function. An absent identity (e.g. a scheduled\n// flow, where request.meta.identity is undefined) is stored as null.\nexport function withCallerIdentity<T>(\n  identity: CallerIdentity | null | undefined,\n  cb: () => T\n): T {\n  return callerIdentityStore.run(identity ?? null, cb);\n}\n\n// getCallerIdentity returns the ambient caller identity for the current invocation, or\n// null when none is available (no identity was passed, or the call is outside an\n// invocation).\nexport function getCallerIdentity(): CallerIdentity | null {\n  return callerIdentityStore.getStore() ?? null;\n}\n","import * as opentelemetry from \"@opentelemetry/api\";\nimport { buildServiceAuthHeaders } from \"./auth/serviceToken\";\nimport * as tracing from \"./tracing\";\n\n// The proxy logs every call it forwards (keel.integration_request) and names the row in this\n// response header.\nconst REQUEST_ID_HEADER = \"X-Keel-Integration-Request-Id\";\n\nfunction getApiUrl() {\n  const apiUrl = process.env.KEEL_API_URL;\n  if (!apiUrl) {\n    throw new Error(\"KEEL_API_URL environment variable is not set\");\n  }\n  return apiUrl;\n}\n\n// createIntegrationServer returns the `server` accessor for ctx.module(name).server. Its `do`\n// method serializes a request descriptor and sends it to the runtime's integration proxy, which\n// injects the stored credential and forwards the call to the vendor. Tokens never reach here.\n//\n// `identity` is accepted (codegen passes it positionally) but unused: the integration-proxy\n// service token is subjectless, so no acting identity is carried.\nexport function createIntegrationServer(name, identity) {\n  return {\n    do: async (request) => {\n      const url = `${getApiUrl()}/integrations/${encodeURIComponent(\n        name\n      )}/proxy`;\n\n      // The span describes the vendor call, not the hop to the proxy: the method and path are the\n      // caller's, and the status is the vendor's. The query is never recorded - it can carry\n      // anything the caller put there.\n      const attrs = {\n        [tracing.ATTRS.INTEGRATION]: name,\n        \"http.request.method\": (request?.method || \"GET\").toUpperCase(),\n      };\n      if (request?.path) {\n        attrs[\"url.path\"] = request.path;\n      }\n\n      return tracing.withUserFacingSpan(\n        \"integration.request\",\n        attrs,\n        async (span) => {\n          // The traceparent parents the proxy's spans (credential, pacing, one per vendor\n          // attempt) on this one, so the whole call is a single trace.\n          const headers = buildServiceAuthHeaders(\"integration-proxy\");\n          opentelemetry.propagation.inject(\n            opentelemetry.context.active(),\n            headers\n          );\n\n          // This span is already the CLIENT side of the hop, so the patched fetch's own span\n          // would only duplicate it under the proxy's internal URL.\n          const response = await tracing.fetchUntraced(url, {\n            method: \"POST\",\n            headers,\n            body: JSON.stringify(request ?? {}),\n          });\n\n          const requestId = response.headers?.get(REQUEST_ID_HEADER) ?? null;\n          if (requestId) {\n            span.setAttribute(tracing.ATTRS.INTEGRATION_REQUEST_ID, requestId);\n          }\n\n          if (!response.ok) {\n            const text = await response.text();\n            const logged = requestId ? ` (request ${requestId})` : \"\";\n            throw new Error(\n              `integration \"${name}\" proxy request failed (${response.status})${logged}: ${text}`\n            );\n          }\n\n          // { status, headers, body } — the transparent upstream response.\n          const result = await response.json();\n          span.setAttribute(\"http.response.status_code\", result.status);\n          // Semconv for CLIENT spans: a 4xx or 5xx from the server fails the call. It is still\n          // returned, not thrown - what a vendor status means is the caller's business.\n          if (result.status >= 400) {\n            span.setStatus({\n              code: opentelemetry.SpanStatusCode.ERROR,\n              message: `${name} responded ${result.status}`,\n            });\n          }\n          return result;\n        },\n        { kind: tracing.SpanKind.CLIENT }\n      );\n    },\n  };\n}\n","// Module exports let an integration module attach its own operations to ctx.module(name). A\n// module names its exports file in integration.yaml; the file's default export is a factory built\n// with defineModuleExports. The generated functions entrypoint registers every module's factory\n// here, and the generated SDK's ctx.module(name) merges the factory's result over the base API.\n//\n// Registration (rather than the SDK importing the exports files) avoids an import cycle: exports\n// files import @teamkeel/sdk themselves, so the SDK must not import them back.\n\n// The names every ctx.module(name) already carries. A module's exports may not shadow them.\nexport const RESERVED_MODULE_API_NAMES = [\"secret\", \"server\"] as const;\n\nexport type ModuleExportsContext = {\n  name: string;\n  server: unknown;\n  secret(key: string): string;\n};\n\nexport type ModuleExportsFactory<\n  C extends ModuleExportsContext = ModuleExportsContext,\n  T extends object = object,\n> = (ctx: C) => T;\n\n// defineModuleExports is an identity function that pins the factory's type. The generated SDK\n// declares a schema-aware overload with the module context typed.\nexport function defineModuleExports<T extends object>(\n  factory: ModuleExportsFactory<ModuleExportsContext, T>\n): ModuleExportsFactory<ModuleExportsContext, T> {\n  return factory;\n}\n\nconst factories = new Map<string, ModuleExportsFactory>();\n\n// registerModuleExports records each module's exports factory, keyed by module name. Called once\n// by the generated functions entrypoint; a later registration for the same module replaces it.\nexport function registerModuleExports(\n  map: Record<string, ModuleExportsFactory | undefined>\n): void {\n  for (const [name, factory] of Object.entries(map)) {\n    if (typeof factory !== \"function\") {\n      throw new Error(\n        `module \"${name}\" exports: the default export must be a function created with defineModuleExports`\n      );\n    }\n    factories.set(name, factory);\n  }\n}\n\n// buildModuleAPI returns the object ctx.module(name) resolves to: the base { secret, server } with\n// the module's exports, if any, spread over it. The generated SDK memoises the result per context.\nexport function buildModuleAPI(\n  name: string,\n  base: Omit<ModuleExportsContext, \"name\">\n): Record<string, unknown> {\n  const factory = factories.get(name);\n  if (!factory) {\n    return base;\n  }\n\n  let result: unknown;\n  try {\n    result = factory({ name, server: base.server, secret: base.secret });\n  } catch (e) {\n    const message = e instanceof Error ? e.message : String(e);\n    const err = new Error(`module \"${name}\" exports: ${message}`);\n    (err as Error & { cause?: unknown }).cause = e;\n    throw err;\n  }\n\n  if (result === null || typeof result !== \"object\") {\n    throw new Error(\n      `module \"${name}\" exports: the factory must return an object of operations`\n    );\n  }\n\n  for (const reserved of RESERVED_MODULE_API_NAMES) {\n    if (Object.prototype.hasOwnProperty.call(result, reserved)) {\n      throw new Error(\n        `module \"${name}\" exports: \"${reserved}\" is reserved and cannot be exported`\n      );\n    }\n  }\n\n  return { ...base, ...result };\n}\n\n// resetModuleExports clears the registry. Test-only.\nexport function resetModuleExports(): void {\n  factories.clear();\n}\n","interface RequestHeadersMap {\n  [key: string]: string;\n}\n\nexport class RequestHeaders {\n  private _headers: Headers;\n\n  /**\n   * @param {{Object.<string, string>}} requestHeaders Map of request headers submitted from the client\n   */\n\n  constructor(requestHeaders: RequestHeadersMap) {\n    this._headers = new Headers(requestHeaders);\n  }\n\n  get: Headers[\"get\"] = (key: string) => {\n    return this._headers.get(key);\n  };\n\n  has: Headers[\"has\"] = (key: string) => {\n    return this._headers.has(key);\n  };\n}\n","import {\n  createJSONRPCErrorResponse,\n  createJSONRPCSuccessResponse,\n  JSONRPCErrorCode,\n} from \"json-rpc-2.0\";\nimport { createDatabaseClient } from \"./database\";\nimport { tryExecuteFunction } from \"./tryExecuteFunction\";\nimport { errorToJSONRPCResponse, RuntimeErrors } from \"./errors\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport { withSpan, ATTRS, SpanKind, markUserFacing } from \"./tracing\";\nimport { parseInputs, parseOutputs } from \"./parsing\";\nimport { withRuntimeMeta } from \"./runtimeMeta\";\nimport { withCallerIdentity } from \"./auth/callerIdentityStore\";\nimport { withActionInvocation } from \"./actions/invocationStore\";\nimport { log } from \"./logger\";\n\n// Generic handler function that is agnostic to runtime environment (local or lambda)\n// to execute a custom function based on the contents of a jsonrpc-2.0 payload object.\n// To read more about jsonrpc request and response shapes, please read https://www.jsonrpc.org/specification\nasync function handleRequest(request, config) {\n  // Handle ping request for health checks - returns immediately without needing a function\n  if (request.method === \"__ping\") {\n    return createJSONRPCSuccessResponse(request.id, { status: \"ok\" });\n  }\n\n  // Try to extract trace context from caller\n  const activeContext = opentelemetry.propagation.extract(\n    opentelemetry.context.active(),\n    request.meta?.tracing\n  );\n\n  // Redact sensitive meta (DB secrets, runtime-minted service tokens) from debug output.\n  // log.debug is itself gated on KEEL_LOG_LEVEL, so no explicit level check is needed here.\n  log.debug(\"handling request\", {\n    ...request,\n    meta: request.meta && {\n      ...request.meta,\n      secrets: request.meta.secrets ? \"[redacted]\" : request.meta.secrets,\n      serviceTokens: request.meta.serviceTokens\n        ? \"[redacted]\"\n        : request.meta.serviceTokens,\n    },\n  });\n\n  // Make the platform-supplied invoke meta (service tokens, project brand) available to the notify /\n  // integration-proxy calls the function makes, then run the request.\n  return withRuntimeMeta(request.meta, () => {\n    // Make the caller's identity ambiently available so FlowsAPI calls default to\n    // acting as whoever is running the function.\n    return withCallerIdentity(request.meta?.identity, () => {\n      // Make the depth of the action chain that led here ambiently available so ActionsAPI\n      // calls the function makes are counted towards the runtime's recursion guard.\n      return withActionInvocation(request.meta, () => {\n        return opentelemetry.context.with(activeContext, () => {\n          // Wrapping span for the whole request\n          return withSpan(\n            request.method,\n            async (span) => {\n              // Checkpoint L: this is the customer's own code running - the\n              // \"function\" archetype (Migration step 1 adoption table). The\n              // transport hop that got us here (Go's function.invoke CLIENT\n              // span) stays internal.\n              markUserFacing(span, \"function\");\n\n              span.setAttribute(ATTRS.ACTION, request.method);\n              span.setAttribute(ATTRS.ACTION_TYPE, request.type);\n\n              if (request.meta?.httpPath) {\n                span.setAttribute(\"url.path\", request.meta.httpPath);\n              }\n\n              let db = null;\n\n              try {\n                const {\n                  createContextAPI,\n                  functions,\n                  permissionFns,\n                  actionTypes,\n                } = config;\n\n                if (!functions[request.method]) {\n                  const message = `function '${request.method}' does not exist or has not been implemented`;\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: message,\n                  });\n                  return createJSONRPCErrorResponse(\n                    request.id,\n                    JSONRPCErrorCode.MethodNotFound,\n                    message\n                  );\n                }\n\n                // headers reference passed to custom function where object data can be modified\n                const headers = new Headers();\n\n                // The ctx argument passed into the custom function.\n                const ctx = createContextAPI({\n                  responseHeaders: headers,\n                  meta: request.meta,\n                  span,\n                });\n\n                // The Go runtime does *some* permissions checks up front before the request reaches\n                // this method, so we pass in a permissionState object on the request.meta object that\n                // indicates whether a call to a custom function has already been authorised\n                const permitted =\n                  request.meta &&\n                  request.meta.permissionState.status === \"granted\"\n                    ? true\n                    : null;\n\n                db = createDatabaseClient({\n                  connString: request.meta?.secrets?.KEEL_DB_CONN,\n                });\n                const customFunction = functions[request.method];\n                const actionType = actionTypes[request.method];\n\n                const functionConfig = customFunction?.config ?? {};\n\n                const result = await tryExecuteFunction(\n                  {\n                    request,\n                    ctx,\n                    permitted,\n                    db,\n                    permissionFns,\n                    actionType,\n                    functionConfig,\n                  },\n                  async () => {\n                    // parse request params to convert objects into rich field types (e.g. InlineFile)\n                    const inputs = parseInputs(request.params);\n\n                    // Return the custom function to the containing tryExecuteFunction block\n                    // Once the custom function is called, tryExecuteFunction will check the schema's permission rules to see if it can continue committing\n                    // the transaction to the db. If a permission rule is violated, any changes made inside the transaction are rolled back.\n                    const result = await customFunction(ctx, inputs);\n\n                    return parseOutputs(result);\n                  }\n                );\n\n                if (result instanceof Error) {\n                  span.recordException(result);\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: result.message,\n                  });\n                  return errorToJSONRPCResponse(request, result);\n                }\n\n                const response = createJSONRPCSuccessResponse(\n                  request.id,\n                  result\n                );\n\n                const responseHeaders = {};\n                for (const pair of headers.entries()) {\n                  responseHeaders[pair[0]] = pair[1].split(\", \");\n                }\n                response.meta = {\n                  headers: responseHeaders,\n                  status: ctx.response.status,\n                };\n\n                return response;\n              } catch (e) {\n                if (e instanceof Error) {\n                  span.recordException(e);\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: e.message,\n                  });\n                  return errorToJSONRPCResponse(request, e);\n                }\n\n                const message = JSON.stringify(e);\n\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: message,\n                });\n\n                return createJSONRPCErrorResponse(\n                  request.id,\n                  RuntimeErrors.UnknownError,\n                  message\n                );\n              } finally {\n                if (db) {\n                  await db.destroy();\n                }\n              }\n            },\n            { kind: SpanKind.SERVER }\n          );\n        });\n      });\n    });\n  });\n}\n\nexport { handleRequest, RuntimeErrors };\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport { PermissionError } from \"./errors\";\n\nexport const PERMISSION_STATE = {\n  UNKNOWN: \"unknown\",\n  PERMITTED: \"permitted\",\n  UNPERMITTED: \"unpermitted\",\n} as const;\n\nexport type PermissionState =\n  (typeof PERMISSION_STATE)[keyof typeof PERMISSION_STATE];\n\n/**\n * Permissions class for managing access control in the runtime\n */\nexport class Permissions {\n  // The Go runtime performs role based permission rule checks prior to calling the functions\n  // runtime, so the status could already be granted. If already granted, then we need to inherit that permission state as the state is later used to decide whether to run in process permission checks\n  // TLDR if a role based permission is relevant and it is granted, then it is effectively the same as the end user calling api.permissions.allow() explicitly in terms of behaviour.\n\n  /**\n   * Explicitly permit access to an action\n   */\n  allow(): void {\n    const store = permissionsApiInstance.getStore();\n    if (store) {\n      store.permitted = true;\n    }\n  }\n\n  /**\n   * Explicitly deny access to an action\n   */\n  deny(): never {\n    // if a user is explicitly calling deny() then we want to throw an error\n    // so that any further execution of the custom function stops abruptly\n    const store = permissionsApiInstance.getStore();\n    if (store) {\n      store.permitted = false;\n    }\n    throw new PermissionError();\n  }\n\n  getState(): PermissionState {\n    const permitted = permissionsApiInstance.getStore()?.permitted;\n\n    switch (true) {\n      case permitted === false:\n        return PERMISSION_STATE.UNPERMITTED;\n      case permitted === null:\n        return PERMISSION_STATE.UNKNOWN;\n      case permitted === true:\n        return PERMISSION_STATE.PERMITTED;\n      default:\n        return PERMISSION_STATE.UNKNOWN;\n    }\n  }\n}\n\ninterface PermissionStore {\n  permitted: boolean | null;\n}\n\nconst permissionsApiInstance = new AsyncLocalStorage<PermissionStore>();\n\ninterface PermissionCallback {\n  getPermissionState: () => PermissionState;\n}\n\n// withPermissions sets the initial permission state from the go runtime in the AsyncLocalStorage so consumers further down the hierarchy can read or mutate the state\n// at will\nexport const withPermissions = async <T>(\n  initialValue: boolean | null,\n  cb: (permissions: PermissionCallback) => Promise<T>\n): Promise<T> => {\n  const permissions = new Permissions();\n\n  return await permissionsApiInstance.run({ permitted: initialValue }, () => {\n    return cb({ getPermissionState: permissions.getState });\n  });\n};\n\ninterface CheckBuiltInPermissionsParams {\n  rows: any[];\n  permissionFns: Array<(rows: any[], ctx: any, db: any) => Promise<boolean>>;\n  ctx: any;\n  db: any;\n  functionName: string;\n}\n\nexport const checkBuiltInPermissions = async ({\n  rows,\n  permissionFns,\n  ctx,\n  db,\n  functionName,\n}: CheckBuiltInPermissionsParams): Promise<void> => {\n  for (const permissionFn of permissionFns) {\n    const result = await permissionFn(rows, ctx, db);\n    // if any of the permission functions return true,\n    // then we return early\n    if (result) {\n      return;\n    }\n  }\n\n  throw new PermissionError(`Not permitted to access ${functionName}`);\n};\n\nexport { PermissionError };\nexport { permissionsApiInstance };\n","const PROTO_ACTION_TYPES = {\n  UNKNOWN: \"ACTION_TYPE_UNKNOWN\",\n  CREATE: \"ACTION_TYPE_CREATE\",\n  GET: \"ACTION_TYPE_GET\",\n  LIST: \"ACTION_TYPE_LIST\",\n  UPDATE: \"ACTION_TYPE_UPDATE\",\n  DELETE: \"ACTION_TYPE_DELETE\",\n  READ: \"ACTION_TYPE_READ\",\n  WRITE: \"ACTION_TYPE_WRITE\",\n  JOB: \"JOB_TYPE\",\n  SUBSCRIBER: \"SUBSCRIBER_TYPE\",\n  FLOW: \"FLOW_TYPE\",\n};\n\nexport { PROTO_ACTION_TYPES };\n","import { withDatabase } from \"./database\";\nimport { withAuditContext } from \"./auditing\";\nimport {\n  withPermissions,\n  PERMISSION_STATE,\n  checkBuiltInPermissions,\n} from \"./permissions\";\nimport { PermissionError } from \"./errors\";\nimport { PROTO_ACTION_TYPES } from \"./consts\";\n\n// tryExecuteFunction will create a new database transaction around a function call\n// and handle any permissions checks. If a permission check fails, then an Error will be thrown and the catch block will be hit.\nfunction tryExecuteFunction(\n  { request, db, permitted, permissionFns, actionType, ctx, functionConfig },\n  cb\n) {\n  return withPermissions(permitted, async ({ getPermissionState }) => {\n    let requiresTransaction = true;\n    switch (actionType) {\n      case PROTO_ACTION_TYPES.GET:\n      case PROTO_ACTION_TYPES.LIST:\n      case PROTO_ACTION_TYPES.READ:\n        requiresTransaction = false;\n        break;\n    }\n\n    if (functionConfig?.dbTransaction !== undefined) {\n      requiresTransaction = functionConfig.dbTransaction;\n    }\n\n    return withDatabase(db, requiresTransaction, async ({ transaction }) => {\n      const fnResult = await withAuditContext(request, async () => {\n        return cb();\n      });\n\n      // api.permissions maintains an internal state of whether the current function has been *explicitly* permitted/denied by the user in the course of their custom function, or if execution has already been permitted by a role based permission (evaluated in the main runtime).\n      // we need to check that the final state is permitted or unpermitted. if it's not, then it means that the user has taken no explicit action to permit/deny\n      // and therefore we default to checking the permissions defined in the schema automatically.\n      switch (getPermissionState()) {\n        case PERMISSION_STATE.PERMITTED:\n          return fnResult;\n        case PERMISSION_STATE.UNPERMITTED:\n          throw new PermissionError(\n            `Not permitted to access ${request.method}`\n          );\n        default:\n          // unknown state, proceed with checking against the built in permissions in the schema\n          const relevantPermissions = permissionFns[request.method];\n\n          const peakInsideTransaction =\n            actionType === PROTO_ACTION_TYPES.CREATE;\n\n          let rowsForPermissions = [];\n          if (fnResult != null) {\n            switch (actionType) {\n              case PROTO_ACTION_TYPES.LIST:\n                // Handle both { results, pageInfo } structure and plain arrays\n                // Ensure we always get an array, even if results is explicitly null\n                if (Array.isArray(fnResult)) {\n                  rowsForPermissions = fnResult;\n                } else if (\n                  fnResult.results != null &&\n                  Array.isArray(fnResult.results)\n                ) {\n                  rowsForPermissions = fnResult.results;\n                }\n                // If neither condition matches, rowsForPermissions stays as empty array\n                break;\n              case PROTO_ACTION_TYPES.DELETE:\n                rowsForPermissions = [{ id: fnResult }];\n                break;\n              case (PROTO_ACTION_TYPES.GET, PROTO_ACTION_TYPES.CREATE):\n                rowsForPermissions = [fnResult];\n                break;\n              default:\n                rowsForPermissions = [fnResult];\n                break;\n            }\n          }\n\n          // check will throw a PermissionError if a permission rule is invalid\n          await checkBuiltInPermissions({\n            rows: rowsForPermissions,\n            permissionFns: relevantPermissions,\n            // it is important that we pass db here as db represents the connection to the database\n            // *outside* of the current transaction. Given that any changes inside of a transaction\n            // are opaque to the outside, we can utilize this when running permission rules and then deciding to\n            // rollback any changes if they do not pass. However, for creates we need to be able to 'peak' inside the transaction to read the created record, as this won't exist outside of the transaction.\n            db: peakInsideTransaction ? transaction : db,\n            ctx,\n            functionName: request.method,\n          });\n\n          // If the built in permission check above doesn't throw, then it means that the request is permitted and we can continue returning the return value from the custom function out of the transaction\n          return fnResult;\n      }\n    });\n  });\n}\n\nexport { tryExecuteFunction };\n","import { AsyncLocalStorage } from \"async_hooks\";\nimport type { EmailBrand } from \"./types\";\n\nconst brandStore = new AsyncLocalStorage<EmailBrand | undefined>();\n\n// withBrand makes the project brand the runtime passed in the invoke meta available to notify.email()\n// for the duration of a single invocation. The host platform sets it on the Go runtime; it is absent\n// when none was supplied (e.g. local `keel run`).\nexport function withBrand<T>(brand: EmailBrand | undefined, cb: () => T): T {\n  return brandStore.run(brand, cb);\n}\n\n// getBrand returns the current invocation's brand, or undefined when none was supplied or the call is\n// outside an invocation.\nexport function getBrand(): EmailBrand | undefined {\n  return brandStore.getStore();\n}\n","import {\n  withServiceTokens,\n  type ServiceTokens,\n} from \"./auth/serviceTokenStore\";\nimport { withBrand } from \"./notifications/brandStore\";\nimport type { EmailBrand } from \"./notifications/types\";\n\n// withRuntimeMeta makes the platform-supplied parts of the invoke meta ambiently available for a single\n// invocation: the runtime-minted service tokens (notify / integration-proxy callbacks) and the project\n// brand (notify.email()).\nexport function withRuntimeMeta<T>(\n  meta:\n    | { serviceTokens?: ServiceTokens; brand?: EmailBrand }\n    | null\n    | undefined,\n  cb: () => T\n): T {\n  return withServiceTokens(meta?.serviceTokens, () =>\n    withBrand(meta?.brand, cb)\n  );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\n// ActionInvocation is what ActionsAPI needs to know about the invocation it is running inside, as\n// passed by the Go runtime in the invoke meta.\nexport type ActionInvocation = {\n  // How many nested action calls deep this invocation already is. ActionsAPI sends depth + 1 on\n  // every outbound call so the runtime can refuse runaway recursion (an action whose function\n  // calls the action again). 0 for an invocation that started no action chain.\n  depth: number;\n  // The user access token for the identity this invocation runs as: the caller's own token for a\n  // request-triggered function, or one the runtime minted for a flow's or job's identity. Absent\n  // for an anonymous invocation, in which case action calls run anonymously too.\n  accessToken: string | null;\n};\n\nconst invocationStore = new AsyncLocalStorage<ActionInvocation>();\n\n// withActionInvocation makes the invoke meta's action-call context available to ActionsAPI for the\n// duration of a single invocation. Missing fields (an invocation that started no action chain, an\n// anonymous caller) are stored as depth 0 and no token.\nexport function withActionInvocation<T>(\n  meta:\n    | { actionCallDepth?: number | null; accessToken?: string | null }\n    | null\n    | undefined,\n  cb: () => T\n): T {\n  return invocationStore.run(\n    {\n      depth: meta?.actionCallDepth ?? 0,\n      accessToken: meta?.accessToken ?? null,\n    },\n    cb\n  );\n}\n\n// getActionCallDepth returns the ambient action-call depth for the current invocation, or 0 when\n// none is available (no depth was passed, or the call is outside an invocation).\nexport function getActionCallDepth(): number {\n  return invocationStore.getStore()?.depth ?? 0;\n}\n\n// getActionAccessToken returns the access token the current invocation's action calls should carry,\n// or null when the invocation is anonymous or the call is outside an invocation.\nexport function getActionAccessToken(): string | null {\n  return invocationStore.getStore()?.accessToken ?? null;\n}\n","import {\n  createJSONRPCErrorResponse,\n  createJSONRPCSuccessResponse,\n  JSONRPCErrorCode,\n} from \"json-rpc-2.0\";\nimport { createDatabaseClient } from \"./database\";\nimport { errorToJSONRPCResponse, RuntimeErrors } from \"./errors\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport { withSpan, ATTRS, SpanKind } from \"./tracing\";\nimport { tryExecuteJob } from \"./tryExecuteJob\";\nimport { parseInputs } from \"./parsing\";\nimport { PROTO_ACTION_TYPES } from \"./consts\";\nimport { withRuntimeMeta } from \"./runtimeMeta\";\nimport { withCallerIdentity } from \"./auth/callerIdentityStore\";\nimport { withActionInvocation } from \"./actions/invocationStore\";\n\n// Generic handler function that is agnostic to runtime environment (local or lambda)\n// to execute a job function based on the contents of a jsonrpc-2.0 payload object.\n// To read more about jsonrpc request and response shapes, please read https://www.jsonrpc.org/specification\nasync function handleJob(request, config) {\n  // Try to extract trace context from caller\n  const activeContext = opentelemetry.propagation.extract(\n    opentelemetry.context.active(),\n    request.meta?.tracing\n  );\n\n  // Make the platform-supplied invoke meta (service tokens, project brand) available to the notify /\n  // integration-proxy calls the job makes, then run the request.\n  return withRuntimeMeta(request.meta, () => {\n    // Make the caller's identity ambiently available so FlowsAPI calls default to\n    // acting as whoever is running the job.\n    return withCallerIdentity(request.meta?.identity, () => {\n      // Make the depth of the action chain that led here ambiently available so ActionsAPI\n      // calls the job makes are counted towards the runtime's recursion guard.\n      return withActionInvocation(request.meta, () => {\n        return opentelemetry.context.with(activeContext, () => {\n          // Wrapping span for the whole request. This is the SERVER half of the\n          // Go runtime's function.invoke CLIENT span (see functions/functions.go).\n          return withSpan(\n            request.method,\n            async (span) => {\n              span.setAttribute(ATTRS.JOB_NAME, request.method);\n\n              let db = null;\n\n              try {\n                const { createJobContextAPI, jobs } = config;\n\n                if (!jobs[request.method]) {\n                  const message = `job '${request.method}' does not exist or has not been implemented`;\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: message,\n                  });\n                  return createJSONRPCErrorResponse(\n                    request.id,\n                    JSONRPCErrorCode.MethodNotFound,\n                    message\n                  );\n                }\n\n                // The ctx argument passed into the job function.\n                const ctx = createJobContextAPI({\n                  meta: request.meta,\n                  span,\n                });\n\n                const permitted =\n                  request.meta &&\n                  request.meta.permissionState.status === \"granted\"\n                    ? true\n                    : null;\n\n                db = createDatabaseClient({\n                  connString: request.meta?.secrets?.KEEL_DB_CONN,\n                });\n                const jobFunction = jobs[request.method];\n                const actionType = PROTO_ACTION_TYPES.JOB;\n\n                const functionConfig = jobFunction?.config ?? {};\n\n                await tryExecuteJob(\n                  { request, permitted, db, actionType, functionConfig },\n                  async () => {\n                    // parse request params to convert objects into rich field types (e.g. InlineFile)\n                    const inputs = parseInputs(request.params);\n\n                    // Return the job function to the containing tryExecuteJob block\n                    return jobFunction(ctx, inputs);\n                  }\n                );\n\n                return createJSONRPCSuccessResponse(request.id, null);\n              } catch (e) {\n                if (e instanceof Error) {\n                  span.recordException(e);\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: e.message,\n                  });\n                  return errorToJSONRPCResponse(request, e);\n                }\n\n                const message = JSON.stringify(e);\n\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: message,\n                });\n\n                return createJSONRPCErrorResponse(\n                  request.id,\n                  RuntimeErrors.UnknownError,\n                  message\n                );\n              } finally {\n                if (db) {\n                  await db.destroy();\n                }\n              }\n            },\n            { kind: SpanKind.SERVER }\n          );\n        });\n      });\n    });\n  });\n}\n\nexport { handleJob, RuntimeErrors };\n","import { withDatabase } from \"./database\";\nimport { withAuditContext } from \"./auditing\";\nimport { withPermissions, PERMISSION_STATE } from \"./permissions\";\nimport { PermissionError } from \"./errors\";\n\n// tryExecuteJob will create a new database transaction around a function call\n// and handle any permissions checks. If a permission check fails, then an Error will be thrown and the catch block will be hit.\nfunction tryExecuteJob({ db, permitted, request, functionConfig }, cb) {\n  return withPermissions(permitted, async ({ getPermissionState }) => {\n    let requiresTransaction = false;\n    if (functionConfig?.dbTransaction !== undefined) {\n      requiresTransaction = functionConfig.dbTransaction;\n    }\n    return withDatabase(db, requiresTransaction, async () => {\n      await withAuditContext(request, async () => {\n        return cb();\n      });\n\n      // api.permissions maintains an internal state of whether the current operation has been *explicitly* permitted/denied by the user in the course of their custom function, or if execution has already been permitted by a role based permission (evaluated in the main runtime).\n      // we need to check that the final state is permitted or unpermitted. if it's not, then it means that the user has taken no explicit action to permit/deny\n      // and therefore we default to checking the permissions defined in the schema automatically.\n      if (getPermissionState() === PERMISSION_STATE.UNPERMITTED) {\n        throw new PermissionError(`Not permitted to access ${request.method}`);\n      }\n    });\n  });\n}\n\nexport { tryExecuteJob };\n","import {\n  createJSONRPCErrorResponse,\n  createJSONRPCSuccessResponse,\n  JSONRPCErrorCode,\n} from \"json-rpc-2.0\";\nimport { createDatabaseClient } from \"./database\";\nimport { errorToJSONRPCResponse, RuntimeErrors } from \"./errors\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport { withSpan, ATTRS, SpanKind, markUserFacing } from \"./tracing\";\nimport { PROTO_ACTION_TYPES } from \"./consts\";\nimport { tryExecuteSubscriber } from \"./tryExecuteSubscriber\";\nimport { parseInputs } from \"./parsing\";\nimport { withRuntimeMeta } from \"./runtimeMeta\";\nimport { withActionInvocation } from \"./actions/invocationStore\";\n\n// Generic handler function that is agnostic to runtime environment (local or lambda)\n// to execute a subscriber function based on the contents of a jsonrpc-2.0 payload object.\n// To read more about jsonrpc request and response shapes, please read https://www.jsonrpc.org/specification\nasync function handleSubscriber(request, config) {\n  // Try to extract trace context from caller\n  const activeContext = opentelemetry.propagation.extract(\n    opentelemetry.context.active(),\n    request.meta?.tracing\n  );\n\n  // Make the platform-supplied invoke meta (service tokens, project brand) available to the notify /\n  // integration-proxy calls the subscriber makes, then run the request.\n  return withRuntimeMeta(request.meta, () => {\n    // Make the depth of the action chain that led here ambiently available so ActionsAPI\n    // calls the subscriber makes are counted towards the runtime's recursion guard.\n    return withActionInvocation(request.meta, () => {\n      return opentelemetry.context.with(activeContext, () => {\n        // Wrapping span for the whole request. This is the SERVER half of the\n        // Go runtime's function.invoke CLIENT span (see functions/functions.go).\n        return withSpan(\n          request.method,\n          async (span) => {\n            // Checkpoint L: this is the ONE span that carries the\n            // \"subscriber\" archetype (not the Go event.deliver span - see\n            // telemetry/README.md \"User-facing tracing\" for why: this span\n            // has the queued time available via request.meta.queuedMs below,\n            // and event.deliver may not even exist for a local-dev immediate\n            // delivery, so marking here is the only choice that works in both\n            // deployed and local-dev traces without double-counting toward\n            // the per-request span budget).\n            markUserFacing(span, \"subscriber\");\n\n            span.setAttribute(ATTRS.SUBSCRIBER, request.method);\n            // The params of a subscriber invocation are the event itself.\n            if (request.params?.eventName) {\n              span.setAttribute(ATTRS.EVENT_NAME, request.params.eventName);\n            }\n            // keel.queued_ms (principle 7, \"no unexplained time\"): the Go\n            // runtime computes this from the SQS SentTimestamp -> event.deliver\n            // gap (deploy/lambdas/runtime/events.go) when running behind SQS,\n            // and threads it through via the function.invoke meta\n            // (functions/functions.go CallSubscriber). Absent for local-dev\n            // immediate delivery, which has no queue to wait in.\n            if (typeof request.meta?.queuedMs === \"number\") {\n              span.setAttribute(ATTRS.QUEUED_MS, request.meta.queuedMs);\n            }\n\n            let db = null;\n\n            try {\n              const { createSubscriberContextAPI, subscribers } = config;\n\n              if (!subscribers[request.method]) {\n                const message = `subscriber '${request.method}' does not exist or has not been implemented`;\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: message,\n                });\n                return createJSONRPCErrorResponse(\n                  request.id,\n                  JSONRPCErrorCode.MethodNotFound,\n                  message\n                );\n              }\n\n              // The ctx argument passed into the subscriber function.\n              const ctx = createSubscriberContextAPI({\n                meta: request.meta,\n                span,\n              });\n\n              db = createDatabaseClient({\n                connString: request.meta?.secrets?.KEEL_DB_CONN,\n              });\n              const subscriberFunction = subscribers[request.method];\n              const actionType = PROTO_ACTION_TYPES.SUBSCRIBER;\n\n              const functionConfig = subscriberFunction?.config ?? {};\n\n              await tryExecuteSubscriber(\n                { request, db, actionType, functionConfig },\n                async () => {\n                  // parse request params to convert objects into rich field types (e.g. InlineFile)\n                  const inputs = parseInputs(request.params);\n\n                  // Return the subscriber function to the containing tryExecuteSubscriber block\n                  return subscriberFunction(ctx, inputs);\n                }\n              );\n\n              return createJSONRPCSuccessResponse(request.id, null);\n            } catch (e) {\n              if (e instanceof Error) {\n                span.recordException(e);\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: e.message,\n                });\n                return errorToJSONRPCResponse(request, e);\n              }\n\n              const message = JSON.stringify(e);\n\n              span.setStatus({\n                code: opentelemetry.SpanStatusCode.ERROR,\n                message: message,\n              });\n\n              return createJSONRPCErrorResponse(\n                request.id,\n                RuntimeErrors.UnknownError,\n                message\n              );\n            } finally {\n              if (db) {\n                await db.destroy();\n              }\n            }\n          },\n          { kind: SpanKind.SERVER }\n        );\n      });\n    });\n  });\n}\n\nexport { handleSubscriber, RuntimeErrors };\n","import { withDatabase } from \"./database\";\nimport { withAuditContext } from \"./auditing\";\n\n// tryExecuteSubscriber will create a new database connection and execute the function call.\nfunction tryExecuteSubscriber({ request, db, functionConfig }, cb) {\n  let requiresTransaction = false;\n  if (functionConfig?.dbTransaction !== undefined) {\n    requiresTransaction = functionConfig.dbTransaction;\n  }\n  return withDatabase(db, requiresTransaction, async () => {\n    await withAuditContext(request, async () => {\n      return cb();\n    });\n  });\n}\n\nexport { tryExecuteSubscriber };\n","import {\n  createJSONRPCErrorResponse,\n  createJSONRPCSuccessResponse,\n  JSONRPCErrorCode,\n} from \"json-rpc-2.0\";\nimport { createDatabaseClient, withDatabase } from \"./database\";\nimport { withAuditContext } from \"./auditing\";\nimport { errorToJSONRPCResponse, RuntimeErrors } from \"./errors\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport { withSpan, SpanKind } from \"./tracing\";\nimport { withRuntimeMeta } from \"./runtimeMeta\";\nimport { withActionInvocation } from \"./actions/invocationStore\";\n\nasync function handleRoute(request, config) {\n  // Try to extract trace context from caller\n  const activeContext = opentelemetry.propagation.extract(\n    opentelemetry.context.active(),\n    request.meta?.tracing\n  );\n\n  // Make the platform-supplied invoke meta (service tokens, project brand) available to the notify /\n  // integration-proxy calls the route makes, then run the request.\n  return withRuntimeMeta(request.meta, () => {\n    // Make the depth of the action chain that led here ambiently available so ActionsAPI\n    // calls the route makes are counted towards the runtime's recursion guard.\n    return withActionInvocation(request.meta, () => {\n      return opentelemetry.context.with(activeContext, () => {\n        // Wrapping span for the whole request. This is the SERVER half of the\n        // Go runtime's function.invoke CLIENT span (see functions/functions.go).\n        return withSpan(\n          request.method,\n          async (span) => {\n            // The params of a route invocation carry the original HTTP request\n            // (body, method, path, query) - see functions.RouteRequest in Go.\n            if (request.params?.path) {\n              span.setAttribute(\"url.path\", request.params.path);\n            }\n            if (request.params?.method) {\n              span.setAttribute(\"http.request.method\", request.params.method);\n            }\n\n            let db = null;\n\n            try {\n              const { createContextAPI, functions } = config;\n\n              if (!functions[request.method]) {\n                const message = `route function '${request.method}' does not exist or has not been implemented`;\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: message,\n                });\n                return createJSONRPCErrorResponse(\n                  request.id,\n                  JSONRPCErrorCode.MethodNotFound,\n                  message\n                );\n              }\n\n              // For route functions context doesn't need request headers or the response object as this is handled by\n              // params and the function response respectively\n              const {\n                headers,\n                response: __,\n                ...ctx\n              } = createContextAPI({\n                responseHeaders: new Headers(),\n                meta: request.meta,\n                span,\n              });\n\n              // Add request headers to params\n              request.params.headers = headers;\n\n              db = createDatabaseClient({\n                connString: request.meta?.secrets?.KEEL_DB_CONN,\n              });\n              const routeHandler = functions[request.method];\n\n              const result = await withDatabase(db, false, () => {\n                return withAuditContext(request, () => {\n                  return routeHandler(request.params, ctx);\n                });\n              });\n\n              if (result instanceof Error) {\n                span.recordException(result);\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: result.message,\n                });\n                return errorToJSONRPCResponse(request, result);\n              }\n\n              const response = createJSONRPCSuccessResponse(request.id, result);\n\n              return response;\n            } catch (e) {\n              if (e instanceof Error) {\n                span.recordException(e);\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: e.message,\n                });\n                return errorToJSONRPCResponse(request, e);\n              }\n\n              const message = JSON.stringify(e);\n\n              span.setStatus({\n                code: opentelemetry.SpanStatusCode.ERROR,\n                message: message,\n              });\n\n              return createJSONRPCErrorResponse(\n                request.id,\n                RuntimeErrors.UnknownError,\n                message\n              );\n            } finally {\n              if (db) {\n                await db.destroy();\n              }\n            }\n          },\n          { kind: SpanKind.SERVER }\n        );\n      });\n    });\n  });\n}\n\nexport { handleRoute, RuntimeErrors };\n","import {\n  createJSONRPCErrorResponse,\n  createJSONRPCSuccessResponse,\n  JSONRPCErrorCode,\n} from \"json-rpc-2.0\";\nimport { createDatabaseClient } from \"./database\";\nimport { Kysely } from \"kysely\";\nimport { errorToJSONRPCResponse, RuntimeErrors } from \"./errors\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport {\n  withSpan,\n  KEEL_INTERNAL_ATTR,\n  KEEL_INTERNAL_TRUE,\n  KEEL_INTERNAL_CHILDREN,\n  SpanKind,\n  ATTRS,\n} from \"./tracing\";\nimport { withRuntimeMeta } from \"./runtimeMeta\";\nimport { withCallerIdentity } from \"./auth/callerIdentityStore\";\nimport { withActionInvocation } from \"./actions/invocationStore\";\nimport { tryExecuteFlow } from \"./tryExecuteFlow\";\nimport { parseInputs } from \"./parsing\";\nimport { createFlowContext, FlowConfig, STEP_STATUS, STEP_TYPE } from \"./flows\";\nimport {\n  CompleteOptions,\n  UiCompleteApiResponse,\n  complete,\n} from \"./flows/ui/complete\";\n\nimport {\n  StepCreatedDisrupt,\n  UIRenderDisrupt,\n  ExhuastedRetriesDisrupt,\n  CallbackDisrupt,\n  HandoffDisrupt,\n  DuplicateSubmissionDisrupt,\n} from \"./flows/disrupts\";\nimport { sentenceCase } from \"change-case\";\n\nfunction normaliseFlowConfig(method: string, rawFlowConfig: FlowConfig) {\n  const config = {\n    ...rawFlowConfig,\n    title: rawFlowConfig.title || sentenceCase(method || \"flow\"),\n    stages: rawFlowConfig.stages?.map((stage) => {\n      if (typeof stage === \"string\") {\n        return {\n          key: stage,\n          name: stage,\n        };\n      }\n      return stage;\n    }),\n  };\n\n  if (config.externalAccess) {\n    config.externalAccess = {\n      ...config.externalAccess,\n      branded: config.externalAccess.branded ?? true,\n    };\n  }\n\n  return config;\n}\n\nfunction externalFlowConfig(config: ReturnType<typeof normaliseFlowConfig>) {\n  const externalAccess = config.externalAccess;\n  if (!externalAccess) {\n    return config;\n  }\n\n  return {\n    ...config,\n    title: externalAccess.title ?? config.title,\n    description: externalAccess.description ?? config.description,\n    externalAccess,\n  };\n}\n\nfunction metadataFlowConfig(\n  method: string,\n  rawFlowConfig: FlowConfig,\n  externalAccess: boolean\n) {\n  const config = normaliseFlowConfig(method, rawFlowConfig);\n  return externalAccess ? externalFlowConfig(config) : config;\n}\n\nasync function handleFlow(request: any, config: any) {\n  // Try to extract trace context from caller\n  const activeContext = opentelemetry.propagation.extract(\n    opentelemetry.context.active(),\n    request.meta?.tracing\n  );\n\n  // Make the platform-supplied invoke meta (service tokens, project brand) available to the notify /\n  // integration-proxy calls the flow makes, then run the request.\n  return withRuntimeMeta(request.meta, () => {\n    // Make the caller's identity ambiently available so FlowsAPI calls default to\n    // acting as whoever is running the flow.\n    return withCallerIdentity(request.meta?.identity, () => {\n      // Make the depth of the action chain that led here ambiently available so ActionsAPI\n      // calls the flow makes are counted towards the runtime's recursion guard.\n      return withActionInvocation(request.meta, () => {\n        return opentelemetry.context.with(activeContext, () => {\n          // Wrapping span for the whole request\n          return withSpan(\n            request.method,\n            async (span: opentelemetry.Span) => {\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_TRUE);\n\n              let db: Kysely<any> | null = null;\n              let flowConfig = null;\n              const runId = request.meta?.runId;\n\n              try {\n                const { flows, createFlowContextAPI } = config;\n\n                if (\n                  request.meta?.metadataOnly &&\n                  Array.isArray(request.meta.flows)\n                ) {\n                  return createJSONRPCSuccessResponse(request.id, {\n                    flows: request.meta.flows.map((method: string) => {\n                      if (!flows[method]) {\n                        throw new Error(\n                          `flow '${method}' does not exist or has not been implemented`\n                        );\n                      }\n                      return {\n                        name: method,\n                        config: metadataFlowConfig(\n                          method,\n                          flows[method].config,\n                          request.meta?.externalAccess === true\n                        ),\n                      };\n                    }),\n                  });\n                }\n\n                if (!flows[request.method]) {\n                  const message = `flow '${request.method}' does not exist or has not been implemented`;\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: message,\n                  });\n                  return createJSONRPCErrorResponse(\n                    request.id,\n                    JSONRPCErrorCode.MethodNotFound,\n                    message\n                  );\n                }\n\n                // Normalise the flow config\n                const rawFlowConfig: FlowConfig = flows[request.method].config;\n                flowConfig = normaliseFlowConfig(request.method, rawFlowConfig);\n\n                if (request.meta?.metadataOnly) {\n                  return createJSONRPCSuccessResponse(request.id, {\n                    name: request.method,\n                    config:\n                      request.meta?.externalAccess === true\n                        ? externalFlowConfig(flowConfig)\n                        : flowConfig,\n                  });\n                }\n\n                if (!runId) {\n                  throw new Error(\"no runId provided\");\n                }\n\n                db = createDatabaseClient({\n                  connString: request.meta?.secrets?.KEEL_DB_CONN,\n                });\n\n                const ctx = createFlowContext(\n                  request.meta.runId,\n                  request.meta.data,\n                  request.meta.action,\n                  request.meta.callback,\n                  request.meta.element,\n                  request.meta.expectedStepId ?? null,\n                  span.spanContext().spanId,\n                  {\n                    ...createFlowContextAPI({\n                      meta: request.meta,\n                      span,\n                    }),\n                    // The platform AI gateway config rides in on the invoke meta\n                    // rather than through createFlowContextAPI — that function is\n                    // generated code, frozen in customer bundles at build time.\n                    aiGateway: request.meta?.aiGateway,\n                    // The invoked flow's name (the JSON-RPC method) — used for\n                    // usage attribution at the platform AI proxy.\n                    flowName: request.method,\n                  }\n                );\n\n                const flowFunction = flows[request.method].fn;\n\n                // parse request params to convert objects into rich field types (e.g. InlineFile)\n                const inputs = parseInputs(request.meta?.inputs);\n\n                let response:\n                  | CompleteOptions<FlowConfig, unknown>\n                  | any\n                  | void = undefined;\n\n                try {\n                  response = await tryExecuteFlow(db, request, async () => {\n                    return flowFunction(ctx, inputs);\n                  });\n                } catch (e) {\n                  // The flow is disrupted as a new step has been created\n                  if (e instanceof StepCreatedDisrupt) {\n                    // the step was just created, so this span should be internal\n                    span.setAttribute(\n                      KEEL_INTERNAL_ATTR,\n                      KEEL_INTERNAL_CHILDREN\n                    );\n\n                    return createJSONRPCSuccessResponse(request.id, {\n                      runId: runId,\n                      runCompleted: false,\n                      config: flowConfig,\n                      executeAfter: e.executeAfter,\n                    });\n                  }\n\n                  // The page being submitted was already recorded by another\n                  // request, so this one stopped before executing anything else.\n                  // Nothing was written to the run and it is not completed: the\n                  // orchestrator leaves it to the request that recorded the page\n                  // and rejects this submission as ERR_STEP_ALREADY_SUBMITTED.\n                  // It is an error rather than a result so it can't be mistaken\n                  // for one, including whatever a UI callback returns.\n                  if (e instanceof DuplicateSubmissionDisrupt) {\n                    span.addEvent(\"duplicate submission\", {\n                      [ATTRS.FLOW_RUN_ID]: runId,\n                      [ATTRS.STEP_ID]: e.stepId,\n                    });\n                    return createJSONRPCErrorResponse(\n                      request.id,\n                      RuntimeErrors.StepAlreadySubmittedError,\n                      \"step has already been submitted\"\n                    );\n                  }\n\n                  // The flow is disrupted as it has just executed a UI callback.\n                  if (e instanceof CallbackDisrupt) {\n                    if (e.error) {\n                      return createJSONRPCErrorResponse(\n                        request.id,\n                        500,\n                        e.response\n                      );\n                    }\n                    return createJSONRPCSuccessResponse(request.id, e.response);\n                  }\n\n                  // The flow is disrupted by a pending UI step\n                  if (e instanceof UIRenderDisrupt) {\n                    return createJSONRPCSuccessResponse(request.id, {\n                      runId: runId,\n                      stepId: e.stepId,\n                      config: flowConfig,\n                      ui: e.contents,\n                    });\n                  }\n\n                  // The flow has handed off the rest of this journey to a successor\n                  // run. The successor was already durably created (and journaled)\n                  // by ctx.flows.handoff, so this run is done — report it completed\n                  // and let the orchestrator start the successor and complete this\n                  // run (see the completion branch in orchestrator.go).\n                  if (e instanceof HandoffDisrupt) {\n                    return createJSONRPCSuccessResponse(request.id, {\n                      runId: runId,\n                      runCompleted: true,\n                      config: flowConfig,\n                      handoffTo: { flow: e.flow, runId: e.runId },\n                      // Set for a deferred ctx.continue: the orchestrator schedules\n                      // the successor's kick instead of sending it immediately.\n                      executeAfter: e.executeAfter,\n                    });\n                  }\n\n                  if (e instanceof Error) {\n                    span.recordException(e);\n                    span.setStatus({\n                      code: opentelemetry.SpanStatusCode.ERROR,\n                      message: e instanceof Error ? e.message : \"unknown error\",\n                    });\n                  }\n\n                  // The flow has failed due to exhausted step retries\n                  if (e instanceof ExhuastedRetriesDisrupt) {\n                    return createJSONRPCSuccessResponse(request.id, {\n                      runId: runId,\n                      runCompleted: true,\n                      error: \"flow failed due to exhausted step retries\",\n                      config: flowConfig,\n                    });\n                  }\n\n                  return createJSONRPCSuccessResponse(request.id, {\n                    runId: runId,\n                    runCompleted: true,\n                    error: e instanceof Error ? e.message : \"unknown error\",\n                    config: flowConfig,\n                  });\n                }\n\n                let ui: UiCompleteApiResponse | null = null;\n                let data: any = null;\n\n                // TODO: this is not a thorough enough check for the response type\n                if (\n                  response &&\n                  typeof response == \"object\" &&\n                  \"__type\" in response &&\n                  response.__type === \"ui.complete\"\n                ) {\n                  ui = await complete(response);\n\n                  const completeStep = await db\n                    .selectFrom(\"keel.flow_step\")\n                    .where(\"run_id\", \"=\", runId)\n                    .where(\"type\", \"=\", STEP_TYPE.COMPLETE)\n                    .selectAll()\n                    .executeTakeFirst();\n\n                  if (!completeStep) {\n                    await db\n                      .insertInto(\"keel.flow_step\")\n                      .values({\n                        run_id: runId,\n                        name: \"\",\n                        stage: response.stage,\n                        status: STEP_STATUS.COMPLETED,\n                        type: STEP_TYPE.COMPLETE,\n                        startTime: new Date(),\n                        endTime: new Date(),\n                        ui: JSON.stringify(ui),\n                      })\n                      .returningAll()\n                      .executeTakeFirst();\n                  }\n\n                  data = response.data;\n                } else if (response) {\n                  data = response;\n                }\n\n                // If we reach this point, then we know the entire flow completed successfully\n                return createJSONRPCSuccessResponse(request.id, {\n                  runId: runId,\n                  runCompleted: true,\n                  data: data,\n                  config: flowConfig,\n                });\n              } catch (e) {\n                if (e instanceof Error) {\n                  span.recordException(e);\n                  span.setStatus({\n                    code: opentelemetry.SpanStatusCode.ERROR,\n                    message: e.message,\n                  });\n                  return errorToJSONRPCResponse(request, e);\n                }\n\n                const message = JSON.stringify(e);\n\n                span.setStatus({\n                  code: opentelemetry.SpanStatusCode.ERROR,\n                  message: message,\n                });\n\n                return createJSONRPCErrorResponse(\n                  request.id,\n                  RuntimeErrors.UnknownError,\n                  message\n                );\n              } finally {\n                if (db) {\n                  await db.destroy();\n                }\n              }\n            },\n            { kind: SpanKind.SERVER }\n          );\n        });\n      });\n    });\n  });\n}\n\nexport { handleFlow, RuntimeErrors };\n","import { withDatabase } from \"./database\";\nimport { withAuditContext } from \"./auditing\";\n\nfunction tryExecuteFlow(db, request, cb) {\n  return withDatabase(db, false, async () => {\n    return withAuditContext(request, async () => {\n      return cb();\n    });\n  });\n}\n\nexport { tryExecuteFlow };\n","import {\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElement,\n} from \"../..\";\n\ntype ElementDataType = {\n  svg: string;\n  signedAt: string;\n};\n\nexport class Signature {\n  readonly svg: string;\n  readonly signedAt: string;\n\n  constructor(data: ElementDataType) {\n    this.svg = data.svg;\n    this.signedAt = data.signedAt;\n  }\n\n  async toPngDataURL(): Promise<string> {\n    const sharp = (await import(\"sharp\")).default;\n    const png = await sharp(Buffer.from(this.svg), { density: 300 })\n      .png()\n      .toBuffer();\n    return `data:image/png;base64,${png.toString(\"base64\")}`;\n  }\n}\n\nexport type UiElementInputSignature = InputElement<\n  ElementDataType,\n  {},\n  Signature\n>;\n\nexport interface UiElementInputSignatureApiResponse extends BaseUiInputResponse<\n  \"ui.input.signature\",\n  ElementDataType\n> {}\n\nexport const signatureInput: InputElementImplementation<\n  ElementDataType,\n  UiElementInputSignature,\n  UiElementInputSignatureApiResponse,\n  Signature\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.signature\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n    } satisfies UiElementInputSignatureApiResponse,\n    validate: options?.validate,\n    getData: (x: ElementDataType) => new Signature(x),\n  };\n};\n","import type { AllOptional, RedirectInputs } from \"./ui/complete\";\n\n// Type-only brand: a ToolRef can only come from a generated `tools.<name>(...)`\n// accessor, never from a hand-written `{ toolId: \"...\" }` literal, so a flow\n// can only point at a tool the project actually has. Nothing is set at runtime.\ndeclare const toolRefBrand: unique symbol;\n\n/**\n * A reference to a console tool and the inputs it opens with. This is what a\n * generated `tools.<name>(...)` accessor returns; it carries nothing about how\n * or where it is used, so the same value can point at a tool from a flow's\n * completion redirect today and from other surfaces later.\n */\nexport type ToolRef<K extends string, In> = {\n  readonly [toolRefBrand]: true;\n  readonly toolId: K;\n} & RedirectInputs<In>;\n\n/**\n * A generated `tools.<name>` accessor: takes the tool's inputs and returns a\n * ToolRef. The inputs can be omitted only when every input of the tool is\n * optional.\n */\nexport type ToolAccessor<K extends string, In> =\n  AllOptional<In> extends true\n    ? (inputs?: In) => ToolRef<K, In>\n    : (inputs: In) => ToolRef<K, In>;\n\n/**\n * Builds the SDK's `tools` object from `{ accessorName: toolId }`, which the\n * generated SDK passes in. Each accessor only pairs the baked-in tool id with\n * the inputs it is given.\n */\nexport function createToolsAPI<M extends Record<string, string>>(\n  ids: M\n): { [N in keyof M]: (inputs?: unknown) => ToolRef<M[N], unknown> } {\n  const api = {} as {\n    [N in keyof M]: (inputs?: unknown) => ToolRef<M[N], unknown>;\n  };\n  for (const name of Object.keys(ids) as (keyof M)[]) {\n    const toolId = ids[name];\n    api[name] = (inputs?: unknown) =>\n      (inputs === undefined ? { toolId } : { toolId, inputs }) as ToolRef<\n        M[typeof name],\n        unknown\n      >;\n  }\n  return api;\n}\n","import { UI } from \"./ui\";\nimport { AnyToolInputs, Complete, CompleteOptions } from \"./ui/complete\";\nexport type { AnyToolInputs, RedirectConfig } from \"./ui/complete\";\nexport { createToolsAPI } from \"./tools\";\nexport type { ToolAccessor, ToolRef } from \"./tools\";\nimport { useDatabase } from \"../database\";\nimport {\n  withSpan,\n  withUserSpan,\n  KEEL_INTERNAL_ATTR,\n  KEEL_INTERNAL_CHILDREN,\n  ATTRS,\n  markUserFacing,\n} from \"../tracing\";\nimport * as opentelemetry from \"@opentelemetry/api\";\nimport { log } from \"../logger\";\nimport type { TraceAPI } from \"../traceTypes\";\nimport { textInput } from \"./ui/elements/input/text\";\nimport { numberInput } from \"./ui/elements/input/number\";\nimport { divider } from \"./ui/elements/display/divider\";\nimport { booleanInput } from \"./ui/elements/input/boolean\";\nimport { markdown } from \"./ui/elements/display/markdown\";\nimport { table } from \"./ui/elements/display/table\";\nimport { selectOne } from \"./ui/elements/select/one\";\nimport { page, callbackFn, UiPage, applyElementGetData } from \"./ui/page\";\nimport {\n  StepCreatedDisrupt,\n  UIRenderDisrupt,\n  ExhuastedRetriesDisrupt,\n  CallbackDisrupt,\n  HandoffDisrupt,\n  DuplicateSubmissionDisrupt,\n} from \"./disrupts\";\nimport { banner } from \"./ui/elements/display/banner\";\nimport { image } from \"./ui/elements/display/image\";\nimport { code } from \"./ui/elements/display/code\";\nimport { grid } from \"./ui/elements/display/grid\";\nimport { list } from \"./ui/elements/display/list\";\nimport { header } from \"./ui/elements/display/header\";\nimport { keyValue } from \"./ui/elements/display/keyValue\";\nimport { selectTable } from \"./ui/elements/select/table\";\nimport { dataGridInput } from \"./ui/elements/input/dataGrid\";\nimport { datePickerInput } from \"./ui/elements/input/datePicker\";\nimport { fileInput } from \"./ui/elements/input/file\";\nimport { imageCapture } from \"./ui/elements/input/imageCapture\";\nimport { signatureInput } from \"./ui/elements/input/signature\";\nimport { iterator } from \"./ui/elements/iterator\";\nimport { print } from \"./ui/elements/interactive/print\";\nimport { pickList } from \"./ui/elements/interactive/pickList\";\nimport { NonRetriableError } from \"./errors\";\nimport { scan } from \"./ui/elements/input/scan\";\nimport { file } from \"./ui/elements/display/file\";\nimport { summary } from \"./ui/elements/display/summary\";\nimport { timeline } from \"./ui/elements/display/timeline\";\nimport { transformRichDataTypes } from \"../parsing\";\nimport {\n  ProgressWriter,\n  type ProgressHandle,\n  type ProgressPatch,\n  type StepProgress,\n} from \"./progress\";\nimport { Kysely, sql } from \"kysely\";\nimport { ENGINE, type TurnEngine } from \"../agents/engine\";\nimport {\n  resolveEngine,\n  resolveDecisionEngine,\n  resolveExtractionEngine,\n} from \"../agents/engineResolver\";\nimport { DECISION_ENGINE, type DecisionEngine } from \"../agents/decision\";\nimport { EXTRACTION_ENGINE, type ExtractionEngine } from \"../agents/extraction\";\nimport KSUID from \"ksuid\";\n\nexport const enum STEP_STATUS {\n  NEW = \"NEW\",\n  RUNNING = \"RUNNING\",\n  PENDING = \"PENDING\",\n  COMPLETED = \"COMPLETED\",\n  FAILED = \"FAILED\",\n}\n\nexport const enum STEP_TYPE {\n  FUNCTION = \"FUNCTION\",\n  UI = \"UI\",\n  DELAY = \"DELAY\",\n  COMPLETE = \"COMPLETE\",\n  FLOW = \"FLOW\",\n}\n\n// Default ceiling on flow composition depth (parent -> child -> grandchild...)\n// and on the total number of runs in a journey (root run + every descendant and\n// handoff successor). Both are runaway backstops, mirroring maxStepsPerRun in\n// runtime/flows/orchestrator.go, and are overridable via env for tests. Read at\n// call time (not captured into a module-level constant) so tests can change the\n// env var per-test without needing to reload the module.\nconst DEFAULT_FLOWS_MAX_DEPTH = 8;\nconst DEFAULT_FLOWS_MAX_JOURNEY_RUNS = 1000;\n\nfunction getMaxFlowDepth(): number {\n  const v = process.env.KEEL_FLOWS_MAX_DEPTH;\n  if (v) {\n    const n = parseInt(v, 10);\n    if (!isNaN(n) && n > 0) {\n      return n;\n    }\n  }\n  return DEFAULT_FLOWS_MAX_DEPTH;\n}\n\nfunction getMaxJourneyRuns(): number {\n  const v = process.env.KEEL_FLOWS_MAX_JOURNEY_RUNS;\n  if (v) {\n    const n = parseInt(v, 10);\n    if (!isNaN(n) && n > 0) {\n      return n;\n    }\n  }\n  return DEFAULT_FLOWS_MAX_JOURNEY_RUNS;\n}\n\n/** A function used to calculate the delay between attempting a retry. The returned value is the number of ms of delay. */\ntype RetryPolicyFn = (retry: number) => number;\n\n/**\n * Returns a linear backoff retry delay.\n * @param intervalS duration in seconds before the first retry. The second retry will double it, the third triple it and so on.\n */\nexport const RetryBackoffLinear = (intervalS: number): RetryPolicyFn => {\n  return (retry: number) => retry * intervalS * 1000;\n};\n\n/**\n * Retuns a constant retry delay.\n * @param intervalS duration in seconds between retries.\n */\nexport const RetryConstant = (intervalS: number): RetryPolicyFn => {\n  return (retry: number) => (retry > 0 ? intervalS * 1000 : 0);\n};\n\n/**\n * Returns an exponential backoff retry delay.\n * @param intervalS the base duration in seconds.\n */\nexport const RetryBackoffExponential = (intervalS: number): RetryPolicyFn => {\n  return (retry: number) => {\n    if (retry < 1) {\n      return 0;\n    }\n    return Math.pow(intervalS, retry) * 1000;\n  };\n};\n\nconst defaultOpts = {\n  retries: 4,\n  timeout: 60000,\n};\n\n// Soft limit above which a step's return value is flagged as oversized.\nconst STEP_VALUE_WARN_BYTES = 1024 * 1024; // 1 MiB\n\n// serializeStepValue JSON-serializes a step's return value for storage and, as a\n// side effect, records its byte size on the span and warns when it exceeds the\n// soft limit. Returns the serialized string — undefined for a void step, which\n// stores SQL NULL. Step values are reloaded on every flow invocation during\n// replay, so a large value is re-transferred and re-parsed once per remaining\n// step of the run; the warning surfaces that cost. We don't reject (yet), to\n// avoid breaking existing flows.\nfunction serializeStepValue(\n  span: opentelemetry.Span,\n  name: string,\n  value: unknown\n): string | undefined {\n  const serialized = JSON.stringify(value);\n  const bytes = serialized == null ? 0 : Buffer.byteLength(serialized, \"utf8\");\n  span.setAttribute(ATTRS.STEP_VALUE_BYTES, bytes);\n  if (bytes > STEP_VALUE_WARN_BYTES) {\n    log.warn(\n      \"flow step returned an oversized value; step values are reloaded on \" +\n        \"every flow invocation during replay, so large values slow the whole \" +\n        \"run down - consider storing large data as a file and returning a \" +\n        \"reference to it instead\",\n      { step: name, bytes, limit_bytes: STEP_VALUE_WARN_BYTES }\n    );\n  }\n  return serialized;\n}\n\n// StepRow is the lean projection of keel.flow_step that the replay path reads:\n// scalar columns plus `value` as text (valueRaw). The jsonb value/ui columns are\n// deliberately absent — see loadStepsSnapshot.\ntype StepRow = {\n  id: string;\n  name: string;\n  status: string;\n  type: string;\n  action: string | null;\n  valueRaw: string | null;\n};\n\n// A flow definition, as produced by the codegen'd flow wrapper (see\n// node/codegen.go): `name` is the proto flow name (PascalCase) the runtime\n// resolves child runs by, distinct from the camelCase JS identifier bound to it.\nexport type FlowDefinition<I, R> = {\n  name: string;\n  config: FlowConfig;\n  fn: (ctx: any, inputs: I) => R;\n};\n\n// The `inputs` field is only required when the child flow declares a message\n// type. A flow without inputs uses `never` as I (see writeFlowFunctionWrapperType\n// in node/codegen.go), and `never` has no valid value to pass — so `inputs`\n// must become omittable rather than a required-but-unsatisfiable property.\ntype FlowRunOptions<C extends FlowConfig, I> = ([I] extends [never]\n  ? { inputs?: never }\n  : { inputs: I }) & {\n  /** Step name; defaults to flow.name. Required when calling the same flow more than once (e.g. in a loop). */\n  name?: string;\n  stage?: ExtractStageKeys<C>;\n  /** Number of times to retry creating the child run after it fails. Defaults to 0. */\n  retries?: number;\n};\n\n// Same never-inputs relaxation as FlowRunOptions, for handoff's narrower options.\ntype FlowHandoffOptions<I> = [I] extends [never]\n  ? { inputs?: never }\n  : { inputs: I };\n\n// Options for ctx.continue. `after` defers the successor run's first\n// execution until the given time (routed through the same scheduler path as\n// step-retry backoff).\nexport type ContinueOptions = { after?: Date };\n\n// FlowResult unwraps a child flow's ctx.complete(...) return value to its data\n// payload, matching how the console/API layer treats a completed run's data.\nexport type FlowResult<R> = R extends { __type: \"ui.complete\"; data?: infer D }\n  ? D\n  : R;\n\nexport interface FlowContext<\n  C extends FlowConfig,\n  E,\n  S,\n  Id,\n  I,\n  H extends NullableHardware,\n  // Map of console tool id -> tool input type, used to narrow the `redirect`\n  // option of ctx.complete. Permissive by default; the generated SDK passes\n  // the project's `ToolInputs`.\n  T = AnyToolInputs,\n> {\n  // Defines a function step that will be run in the flow.\n  step: Step<C>;\n  // Defines a UI step that will be run in the flow.\n  ui: UI<C, H>;\n  complete: Complete<C, I, T>;\n  env: E;\n  now(): Date;\n  secrets: S;\n  identity: Id;\n  trace: TraceAPI;\n  // Access an integration module's secrets and its credential-injecting HTTP proxy.\n  module(name: string): {\n    secret(key: string): string;\n    server: {\n      do(request: {\n        method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n        path: string;\n        query?: Record<string, string | string[]>;\n        headers?: Record<string, string>;\n        body?: unknown;\n      }): Promise<{\n        status: number;\n        headers: Record<string, string[]>;\n        body: unknown;\n      }>;\n    };\n  };\n  flows: {\n    // Durably calls a child flow: creates a FLOW step and a child run, then\n    // parks (disrupts) until the orchestrator completes or fails that step.\n    run<I2, R>(\n      flow: FlowDefinition<I2, R>,\n      opts: FlowRunOptions<C, I2>\n    ): Promise<FlowResult<Awaited<R>>>;\n    // Hands off the rest of this journey to a successor flow: journals a\n    // COMPLETED FLOW step recording the handoff, creates the successor run as\n    // a sibling (same journey root, no parent), and always throws\n    // HandoffDisrupt — a handoff never returns to its caller, the successor\n    // continues the journey independently. Not supported from a child run\n    // (one with a parent_run_id); return a result and let the parent decide\n    // instead.\n    handoff<I2, R>(\n      flow: FlowDefinition<I2, R>,\n      opts: FlowHandoffOptions<I2>\n    ): Promise<never>;\n  };\n  // Completes this run and starts a fresh run of the SAME flow with the given\n  // inputs — a typed self-handoff. Use it to carry unbounded work (e.g. a\n  // paginated walk) past a single run's step budget and replay cost: the\n  // successor starts with a fresh step budget and an empty replay baseline,\n  // and the inputs are the continuation state. `after` defers the successor's\n  // first execution. Never returns to its caller. Not supported from a child\n  // run (one started by ctx.flows.run); return a result and let the parent\n  // decide instead.\n  continue: [I] extends [never]\n    ? (inputs?: never, opts?: ContinueOptions) => Promise<never>\n    : (inputs: I, opts?: ContinueOptions) => Promise<never>;\n}\n\nexport type NullableHardware = Hardware | undefined;\n\nexport type Hardware = {\n  printers: Printer[];\n};\nexport interface Printer {\n  name: string;\n}\n\n// Recursively maps a type to its JSON-serializable form: primitives and null\n// pass through, arrays and objects are mapped element-/property-wise, and\n// anything that can't survive a JSON round-trip collapses to `never`.\n//\n// Functions are matched (and rejected) before the object case: a function is an\n// `object` with no keys, so without this guard it would map to `{}` and slip\n// through. Rejecting functions here also rejects class instances that carry\n// methods (e.g. `Date`, `Map`), since their method properties become `never` —\n// which is correct, as those do not round-trip through JSON.stringify/parse.\n//\n// Broad, keyless object types (`object`, `{}`) are likewise rejected: they carry\n// no guarantee about their contents (an `object`-typed field could hold a `Date`\n// or a function at runtime), so mapping them would produce a permissive `{}`\n// that anything satisfies. A real data shape always has known keys.\ntype JsonValue<T> = T extends string | number | boolean | null\n  ? T\n  : T extends (...args: any[]) => any\n    ? never\n    : T extends (infer E)[]\n      ? JsonValue<E>[]\n      : T extends object\n        ? keyof T extends never\n          ? never\n          : { [K in keyof T]: JsonValue<T[K]> }\n        : never;\n\n// The values a step is allowed to return: the string, number and boolean\n// primitives, null, void (a step that returns nothing), and arrays/objects made\n// up of them. Used as the step's return-type constraint (`R extends\n// Serializable<R>`).\n//\n// The object case is written as a homomorphic mapped type over `T` rather than\n// an object type with an index signature (`{ [key: string]: ... }`). An index\n// signature constraint rejects named `interface` return types, because an\n// interface has no implicit index signature — only `type` aliases do. That\n// mismatch surfaced as confusing \"not assignable\" errors on otherwise valid\n// step return types (e.g. a step returning a value typed as an interface).\n// Mapping over `keyof T` accepts interfaces and type aliases alike.\n//\n// This mapping is also what validates nested fields: a non-serializable\n// property collapses to `never` via JsonValue, so the return type no longer\n// satisfies the constraint.\ntype Serializable<T> =\n  | string\n  | number\n  | boolean\n  | null\n  | void\n  | { [K in keyof T]: JsonValue<T[K]> };\n\n// Validates the step's *top-level* return type. The `Serializable<R>`\n// constraint maps over keys, so a top-level value with no usable keys — a bare\n// function, `bigint`, `symbol`, or `object` — slips through as a permissive\n// shape. Running R through JsonValue (which collapses those to `never`) and\n// using the result as the callback's expected return type forces a type error\n// for non-serializable top-level returns, while leaving valid returns (and\n// `void`) untouched.\ntype StepReturn<R> = [R] extends [JsonValue<R> | void] ? R : JsonValue<R>;\n\ntype StepOptions<C extends FlowConfig> = {\n  stage?: ExtractStageKeys<C>;\n  /** Number of times to retry the step after it fails. Defaults to 4. */\n  retries?: number;\n  /** Function to calculate the delay before retrying this step. By default steps will be retried immediately. */\n  retryPolicy?: RetryPolicyFn;\n  /** Maximum time in milliseconds to wait for the step to complete. Defaults to 60000 (1 minute). */\n  timeout?: number;\n  /** A function to call if the step fails after it exhausts all retries. */\n  onFailure?: () => Promise<void> | void;\n  /** Message shown as the step's progress while it runs. Sugar for an initial `progress.set({ message })`. */\n  loadingMessage?: string;\n};\n\nexport type Step<C extends FlowConfig> = {\n  <R extends Serializable<R>>(\n    /** The unique name of this step. */\n    name: string,\n    /** Configuration options for the step. */\n    options: StepOptions<C>,\n    /** The step function to execute. */\n    fn: StepFunction<C, StepReturn<R>>\n  ): Promise<R>;\n  <R extends Serializable<R>>(\n    /** The unique name of this step. */\n    name: string,\n    /** The step function to execute. */\n    fn: StepFunction<C, StepReturn<R>>\n  ): Promise<R>;\n};\n\ntype StepArgs<C extends FlowConfig> = {\n  attempt: number;\n  stepOptions: StepOptions<C>;\n  /** Report what the step is doing while it runs. Updates are throttled, written to the run's state, and surfaced by the flows API. */\n  progress: ProgressHandle;\n};\n\ntype StepFunction<C extends FlowConfig, R> = (args: StepArgs<C>) => Promise<R>;\n\nexport interface FlowConfig {\n  /** The stages to organise the steps in the flow. */\n  stages?: StageConfig[];\n  /**\n   * The internal title of the flow as shown to authenticated Console users.\n   *\n   * For public/shareable flow links, set `externalAccess.title` when the\n   * externally visible title should differ from this internal title.\n   */\n  title?: string;\n  /**\n   * The internal description of the flow as shown to authenticated Console users.\n   *\n   * For public/shareable flow links, set `externalAccess.description` when the\n   * externally visible description should differ from this internal description.\n   */\n  description?: string;\n  /**\n   * Content and presentation options for public/shareable flow links.\n   *\n   * These values are used before an external visitor starts the flow. If\n   * `title` or `description` are set here, they replace the top-level internal\n   * `title` or `description` in external metadata responses so internal copy is\n   * not exposed to public/shared users.\n   */\n  externalAccess?: FlowExternalAccessConfig;\n}\n\nexport interface FlowExternalAccessConfig {\n  /**\n   * The title shown to public/shareable link visitors before the flow starts.\n   *\n   * When set, this is returned as `config.title` in external metadata responses\n   * instead of the top-level internal `title`.\n   */\n  title?: string;\n  /**\n   * The description shown to public/shareable link visitors before the flow starts.\n   *\n   * When set, this is returned as `config.description` in external metadata\n   * responses instead of the top-level internal `description`.\n   */\n  description?: string;\n  /**\n   * Additional introduction content shown on the external start screen before\n   * the visitor starts the flow.\n   */\n  introduction?: string;\n  /**\n   * Whether the external flow should show company branding when branding is\n   * available and configured in the project settings.\n   *\n   * Defaults to `true`.\n   *\n   * @default true\n   */\n  branded?: boolean;\n}\n\n// What is returned as the config to the API\nexport interface FlowConfigAPI {\n  stages?: StageConfigObject[];\n  title: string;\n  description?: string;\n  externalAccess?: FlowExternalAccessConfig;\n}\n\nexport type FlowFunction<\n  C extends FlowConfig,\n  E,\n  S,\n  Id,\n  I = undefined,\n  H extends NullableHardware = undefined,\n> = (\n  ctx: FlowContext<C, E, S, Id, I, H>,\n  inputs: I\n) => Promise<CompleteOptions<C, I> | any | void>;\n\n// TaskFlowFunction is like FlowFunction but with the second parameter named \"task\"\n// for flows that are associated with a task entity.\nexport type TaskFlowFunction<\n  C extends FlowConfig,\n  E,\n  S,\n  Id,\n  T,\n  H extends NullableHardware = undefined,\n> = (\n  ctx: FlowContext<C, E, S, Id, T, H>,\n  task: T\n) => Promise<CompleteOptions<C, T> | any | void>;\n\n// Extract the stage keys from the flow config supporting either a string or an object with a key property\nexport type ExtractStageKeys<T extends FlowConfig> = T extends {\n  stages: infer S;\n}\n  ? S extends ReadonlyArray<infer U>\n    ? U extends string\n      ? U\n      : U extends { key: infer K extends string }\n        ? K\n        : never\n    : never\n  : never;\n\ntype StageConfigObject = {\n  /** The unique key of the stage. */\n  key: string;\n  /** The name of the stage as shown in the Console. */\n  name: string;\n  /** The description of the stage as shown in the Console. */\n  description?: string;\n  /** Whether the stage is initially hidden in the Console. */\n  initiallyHidden?: boolean;\n  /** For a stage spliced in from a composed child flow, the namespaced key of the parent flow's stage it nests under. Absent on top-level stages. */\n  parentKey?: string;\n};\n\ntype StageConfig = string | StageConfigObject;\n\n// insertNewStep inserts a NEW flow_step row for the given (runId, name) only if no NEW or\n// RUNNING row already exists for it (a COMPLETED row does not block insertion). It serialises\n// concurrent callers via a SELECT FOR UPDATE on the parent flow_run row, so SQS at-least-once\n// delivery, double-submitted UI callbacks and other duplicate invocations cannot produce a\n// second runnable row for a step that is already pending or in flight.\nexport async function insertNewStep(\n  db: Kysely<any>,\n  runId: string,\n  name: string,\n  stage: string | undefined\n): Promise<void> {\n  await db.transaction().execute(async (trx) => {\n    await trx\n      .selectFrom(\"keel.flow_run\")\n      .select(\"id\")\n      .where(\"id\", \"=\", runId)\n      .forUpdate()\n      .executeTakeFirst();\n\n    // Don't create another runnable row when one is already in flight: a NEW\n    // row waiting to be claimed, or a RUNNING row another invocation owns.\n    // Without the RUNNING check a stale invocation (which read the step list\n    // before the step was claimed) would insert a duplicate NEW row alongside\n    // the RUNNING one; that duplicate then gets independently claimed and the\n    // step function runs twice, defeating the atomic claim. A COMPLETED row is\n    // deliberately not treated as a blocker here — the COMPLETED + NEW invariant\n    // detection in the step body governs that case instead of being silently\n    // swallowed.\n    const existing = await trx\n      .selectFrom(\"keel.flow_step\")\n      .select(\"id\")\n      .where(\"run_id\", \"=\", runId)\n      .where(\"name\", \"=\", name)\n      .where(\"status\", \"in\", [STEP_STATUS.NEW, STEP_STATUS.RUNNING])\n      .executeTakeFirst();\n\n    if (existing) {\n      return;\n    }\n\n    await trx\n      .insertInto(\"keel.flow_step\")\n      .values({\n        id: KSUID.randomSync().string,\n        run_id: runId,\n        name: name,\n        stage: stage,\n        status: STEP_STATUS.NEW,\n        type: STEP_TYPE.FUNCTION,\n      })\n      // AuditContextPlugin (src/auditing.js) replaces the RETURNING clause on every\n      // INSERT/UPDATE/DELETE and emits an empty clause when there is no audit context.\n      .returningAll()\n      .executeTakeFirst();\n  });\n}\n\n// ChildRunOpts is the subset of FlowRunOptions that createChildRun needs —\n// kept structural (rather than importing FlowRunOptions<C, I>) so the helper\n// isn't generic over the caller's stage config.\ntype ChildRunOpts = {\n  inputs: unknown;\n  stage?: string;\n  // The number of FAILED FLOW step rows the caller observed for (runId,\n  // stepName) before entering the lock. Used to detect a stale read: if the\n  // live count differs once we hold the lock, another invocation has already\n  // advanced this step (e.g. inserted its own FAILED row for the same guard\n  // failure), and we must race out rather than act on stale information.\n  expectedFailures: number;\n};\n\n// Signals that another invocation has already advanced this step (a\n// non-terminal FLOW step exists, or the FAILED count moved since the caller's\n// read) and this invocation should disrupt and let replay resolve on the next\n// invocation, rather than acting on stale information.\nconst RACED = Symbol(\"raced\");\n\n// createChildRun durably creates a FLOW step and its child flow_run in one\n// transaction, mirroring insertNewStep's locking: a SELECT ... FOR UPDATE on\n// the parent run serialises concurrent invocations so a redelivered message\n// cannot create two child runs for the same step. Depth and journey-size\n// guards run inside the same lock, so a run cannot slip past them via a race.\nexport async function createChildRun(\n  db: Kysely<any>,\n  runId: string,\n  stepName: string,\n  childFlowName: string,\n  opts: ChildRunOpts\n): Promise<void> {\n  // The success path (existing non-terminal step check below) is already\n  // race-safe: the loser finds the winner's row and returns RACED. Guard\n  // failures need the same treatment — without it, two concurrent invocations\n  // that both read a stale FAILED count can both pass the guard check and both\n  // insert a FAILED row, duplicating it. So the FAILED insert happens INSIDE\n  // this transaction (nothing after it can throw, so there is no rollback\n  // hazard), and the NonRetriableError is thrown from the caller after commit\n  // to preserve the existing return-a-value-then-throw-after-commit pattern.\n  const result = await db.transaction().execute(async (trx) => {\n    const parent = await trx\n      .selectFrom(\"keel.flow_run\")\n      .select([\n        \"traceparent\",\n        \"traceId\",\n        \"startedBy\",\n        \"signedLinkId\",\n        \"rootRunId\",\n        \"parentRunId\",\n      ])\n      .where(\"id\", \"=\", runId)\n      .forUpdate()\n      .executeTakeFirst();\n\n    // Same double-insert guard as insertNewStep: don't create a second child\n    // run when a non-terminal FLOW step already exists for this (run, name).\n    const existing = await trx\n      .selectFrom(\"keel.flow_step\")\n      .select(\"id\")\n      .where(\"run_id\", \"=\", runId)\n      .where(\"name\", \"=\", stepName)\n      .where(\"status\", \"in\", [\n        STEP_STATUS.NEW,\n        STEP_STATUS.PENDING,\n        STEP_STATUS.RUNNING,\n      ])\n      .executeTakeFirst();\n\n    if (existing) {\n      return RACED;\n    }\n\n    // Re-count FAILED rows under the lock. If it differs from what the caller\n    // observed before entering the lock, another invocation has already acted\n    // on this step (most likely: inserted a FAILED row for the same guard\n    // failure) since that read — a stale-read race, not a fresh guard\n    // evaluation. Bail out and let the next invocation replay and resolve.\n    const failedCountRow = await trx\n      .selectFrom(\"keel.flow_step\")\n      .select(({ fn }) => [fn.countAll().as(\"count\")])\n      .where(\"run_id\", \"=\", runId)\n      .where(\"name\", \"=\", stepName)\n      .where(\"status\", \"=\", STEP_STATUS.FAILED)\n      .executeTakeFirst();\n    const liveFailures = Number(failedCountRow?.count ?? 0);\n\n    if (liveFailures !== opts.expectedFailures) {\n      return RACED;\n    }\n\n    const rootRunId = parent?.rootRunId ?? runId;\n\n    // Depth guard: walk parent_run_id from this run up to its root, counting\n    // hops. A child created here would sit one hop deeper than that count.\n    const depthRow = await sql<{ depth: number }>`\n      WITH RECURSIVE ancestors AS (\n        SELECT id, parent_run_id, 0 AS depth\n        FROM keel.flow_run\n        WHERE id = ${runId}\n        UNION ALL\n        SELECT r.id, r.parent_run_id, a.depth + 1\n        FROM keel.flow_run r\n        JOIN ancestors a ON r.id = a.parent_run_id\n      )\n      SELECT max(depth) AS depth FROM ancestors\n    `.execute(trx);\n    const currentDepth = Number(depthRow.rows[0]?.depth ?? 0);\n    const childDepth = currentDepth + 1;\n    const maxDepth = getMaxFlowDepth();\n\n    if (childDepth >= maxDepth) {\n      const message = `maximum flow composition depth (${maxDepth}) exceeded`;\n      await trx\n        .insertInto(\"keel.flow_step\")\n        .values({\n          id: KSUID.randomSync().string,\n          run_id: runId,\n          name: stepName,\n          stage: opts.stage,\n          status: STEP_STATUS.FAILED,\n          type: STEP_TYPE.FLOW,\n          error: message,\n          startTime: new Date(),\n          endTime: new Date(),\n        })\n        .returningAll()\n        .executeTakeFirst();\n      return message;\n    }\n\n    // Journey guard: every run in the journey has root_run_id = rootRunId\n    // EXCEPT the root run itself, whose root_run_id is NULL (it is its own\n    // root — see EffectiveRootID in runtime/flows/flow.go). So the existing\n    // journey size is this count plus 1 (for the root), and creating a child\n    // here would add one more; that total must stay within budget.\n    const journeyCountRow = await trx\n      .selectFrom(\"keel.flow_run\")\n      .select(({ fn }) => [fn.countAll().as(\"count\")])\n      .where(\"rootRunId\", \"=\", rootRunId)\n      .executeTakeFirst();\n    const existingJourneySize = Number(journeyCountRow?.count ?? 0) + 1;\n    const maxJourneyRuns = getMaxJourneyRuns();\n\n    if (existingJourneySize + 1 > maxJourneyRuns) {\n      const message = `maximum flow journey run count (${maxJourneyRuns}) exceeded`;\n      await trx\n        .insertInto(\"keel.flow_step\")\n        .values({\n          id: KSUID.randomSync().string,\n          run_id: runId,\n          name: stepName,\n          stage: opts.stage,\n          status: STEP_STATUS.FAILED,\n          type: STEP_TYPE.FLOW,\n          error: message,\n          startTime: new Date(),\n          endTime: new Date(),\n        })\n        .returningAll()\n        .executeTakeFirst();\n      return message;\n    }\n\n    const childId = KSUID.randomSync().string;\n    await trx\n      .insertInto(\"keel.flow_run\")\n      .values({\n        id: childId,\n        name: childFlowName,\n        status: \"NEW\",\n        input: opts.inputs ?? null,\n        traceparent: parent?.traceparent,\n        traceId: parent?.traceId,\n        startedBy: parent?.startedBy,\n        signedLinkId: parent?.signedLinkId,\n        rootRunId: rootRunId,\n        parentRunId: runId,\n      })\n      .returningAll()\n      .executeTakeFirst();\n\n    const step = await trx\n      .insertInto(\"keel.flow_step\")\n      .values({\n        id: KSUID.randomSync().string,\n        run_id: runId,\n        name: stepName,\n        stage: opts.stage,\n        status: STEP_STATUS.PENDING,\n        type: STEP_TYPE.FLOW,\n        value: JSON.stringify({ flow: childFlowName, runId: childId }),\n        startTime: new Date(),\n      })\n      .returningAll()\n      .executeTakeFirst();\n\n    await trx\n      .updateTable(\"keel.flow_run\")\n      .set({ parentStepId: step!.id })\n      .where(\"id\", \"=\", childId)\n      .returningAll()\n      .executeTakeFirst();\n\n    return null;\n  });\n\n  if (result === RACED) {\n    // Another invocation already advanced this step (existing non-terminal\n    // step, or a FAILED row landed since our caller's read). Disrupt so the\n    // orchestrator re-invokes; the next invocation re-reads and resolves via\n    // normal replay logic instead of acting on stale information.\n    throw new StepCreatedDisrupt();\n  }\n\n  if (result) {\n    // A guard failure. The FAILED step row was already inserted inside the\n    // transaction above (so it commits atomically with the guard check and\n    // cannot race with another invocation's stale read) — only the throw\n    // happens out here, after commit.\n    throw new NonRetriableError(result);\n  }\n}\n\n// createHandoffRun durably creates a \"handoff:<flow>\" FLOW step and the\n// successor flow_run in one transaction, mirroring createChildRun's locking\n// (a SELECT ... FOR UPDATE on the parent run). It differs from createChildRun\n// in three ways that make a handoff a sibling rather than a child:\n//   - the FLOW step is inserted directly as COMPLETED (it is a journal entry\n//     recording that the handoff happened, not a wait for a result);\n//   - the successor's root_run_id is this run's *effective* root, and its\n//     parent_run_id/parent_step_id are NULL — it does not nest under this run;\n//   - only the journey-size guard applies. The depth guard does not, because\n//     handoff successors are siblings in the journey, not descendants.\n// Returns the successor run id (and, for a deferred ctx.continue, the\n// executeAfter journaled with it — journaled so a replay after a crash\n// between commit and response re-reports the same deferral).\nasync function createHandoffRun(\n  db: Kysely<any>,\n  runId: string,\n  stepName: string,\n  successorFlowName: string,\n  inputs: unknown,\n  executeAfter?: Date\n): Promise<{ runId: string; executeAfter?: Date }> {\n  const result = await db.transaction().execute(async (trx) => {\n    const parent = await trx\n      .selectFrom(\"keel.flow_run\")\n      .select([\n        \"traceparent\",\n        \"traceId\",\n        \"startedBy\",\n        \"signedLinkId\",\n        \"rootRunId\",\n      ])\n      .where(\"id\", \"=\", runId)\n      .forUpdate()\n      .executeTakeFirst();\n\n    // Idempotency: a prior invocation may have already journaled this handoff\n    // (this invocation is a replay after a crash/redelivery between commit and\n    // the disrupt reaching the caller), or a concurrent invocation of the same\n    // still-RUNNING predecessor may have already recorded a guard failure for\n    // it (SQS at-least-once: the first invocation hit the journey-size guard\n    // and committed a FAILED row with no value; this one is serialized behind\n    // the lock above and finds it). Branch on status rather than assuming\n    // COMPLETED, mirroring createChildRun's RACED handling.\n    const existing = await trx\n      .selectFrom(\"keel.flow_step\")\n      .select([\n        \"status\",\n        \"error\",\n        sql<string | null>`value::text`.as(\"valueRaw\"),\n      ])\n      .where(\"run_id\", \"=\", runId)\n      .where(\"name\", \"=\", stepName)\n      .executeTakeFirst();\n\n    if (existing) {\n      if (existing.status === STEP_STATUS.COMPLETED) {\n        const value = existing.valueRaw ? JSON.parse(existing.valueRaw) : null;\n        if (value?.runId) {\n          return {\n            runId: value.runId as string,\n            executeAfter: value.executeAfter\n              ? new Date(value.executeAfter)\n              : undefined,\n          };\n        }\n      }\n\n      if (existing.status === STEP_STATUS.FAILED) {\n        return { failed: existing.error || \"handoff failed\" };\n      }\n\n      // Any other status (e.g. a COMPLETED row without a parseable runId)\n      // shouldn't occur for a directly-journaled handoff, but don't guess:\n      // disrupt and let the next invocation replay and resolve.\n      return RACED;\n    }\n\n    const rootRunId = parent?.rootRunId ?? runId;\n\n    // Journey guard: same accounting as createChildRun — every run in the\n    // journey has root_run_id = rootRunId except the root itself (NULL, its\n    // own root), so existing journey size is this count plus 1.\n    const journeyCountRow = await trx\n      .selectFrom(\"keel.flow_run\")\n      .select(({ fn }) => [fn.countAll().as(\"count\")])\n      .where(\"rootRunId\", \"=\", rootRunId)\n      .executeTakeFirst();\n    const existingJourneySize = Number(journeyCountRow?.count ?? 0) + 1;\n    const maxJourneyRuns = getMaxJourneyRuns();\n\n    if (existingJourneySize + 1 > maxJourneyRuns) {\n      const message = `maximum flow journey run count (${maxJourneyRuns}) exceeded`;\n      await trx\n        .insertInto(\"keel.flow_step\")\n        .values({\n          id: KSUID.randomSync().string,\n          run_id: runId,\n          name: stepName,\n          status: STEP_STATUS.FAILED,\n          type: STEP_TYPE.FLOW,\n          error: message,\n          startTime: new Date(),\n          endTime: new Date(),\n        })\n        .returningAll()\n        .executeTakeFirst();\n      // Return (rather than throw) so the FAILED insert commits atomically\n      // with the guard check, and the NonRetriableError is thrown from the\n      // caller after commit — same return-a-value-then-throw-after-commit\n      // pattern as createChildRun.\n      return { failed: message };\n    }\n\n    const successorId = KSUID.randomSync().string;\n    await trx\n      .insertInto(\"keel.flow_run\")\n      .values({\n        id: successorId,\n        name: successorFlowName,\n        status: \"NEW\",\n        input: inputs ?? null,\n        traceparent: parent?.traceparent,\n        traceId: parent?.traceId,\n        startedBy: parent?.startedBy,\n        signedLinkId: parent?.signedLinkId,\n        rootRunId: rootRunId,\n        parentRunId: null,\n      })\n      .returningAll()\n      .executeTakeFirst();\n\n    // Journaled directly as COMPLETED: a handoff step records that the\n    // handoff happened, it does not wait for the successor to finish.\n    await trx\n      .insertInto(\"keel.flow_step\")\n      .values({\n        id: KSUID.randomSync().string,\n        run_id: runId,\n        name: stepName,\n        status: STEP_STATUS.COMPLETED,\n        type: STEP_TYPE.FLOW,\n        value: JSON.stringify({\n          flow: successorFlowName,\n          runId: successorId,\n          handoff: true,\n          ...(executeAfter ? { executeAfter } : {}),\n        }),\n        startTime: new Date(),\n        endTime: new Date(),\n      })\n      .returningAll()\n      .executeTakeFirst();\n\n    return { runId: successorId, executeAfter };\n  });\n\n  if (result === RACED) {\n    // Another invocation already advanced this step in a way we don't\n    // recognise as a terminal handoff journal. Disrupt so the orchestrator\n    // re-invokes; the next invocation re-reads and resolves via normal\n    // replay logic instead of acting on stale information.\n    throw new StepCreatedDisrupt();\n  }\n\n  if (typeof result === \"object\" && result !== null && \"failed\" in result) {\n    // A guard failure — either just recorded inside the transaction above,\n    // or (the race this idempotency check exists for) already recorded by a\n    // concurrent invocation of the same still-RUNNING predecessor. Either\n    // way, surface it as the same NonRetriableError the first invocation to\n    // observe the guard failure threw, rather than crashing.\n    throw new NonRetriableError(result.failed);\n  }\n\n  return result;\n}\n\nexport function createFlowContext<\n  C extends FlowConfig,\n  E,\n  S,\n  Id,\n  I,\n  H extends NullableHardware,\n>(\n  runId: string,\n  data: any,\n  action: string | null,\n  callback: string | null,\n  element: string | null,\n  expectedStepId: string | null,\n  spanId: string,\n  ctx: {\n    env: E;\n    now: () => Date;\n    secrets: S;\n    identity: Id;\n    trace: TraceAPI;\n    engine?: TurnEngine;\n    decisionEngine?: DecisionEngine;\n    extractionEngine?: ExtractionEngine;\n    /** Platform AI gateway (the flows AI proxy) config, delivered via the\n     * invoke meta when the environment has one configured. Used by\n     * resolveEngine as the fallback when no customer API key is set. */\n    aiGateway?: { baseUrl: string };\n    /** Name of the flow being invoked (the JSON-RPC method). Forwarded to the\n     * platform AI proxy as the x-keel-flow-name attribution header on the\n     * gateway path. */\n    flowName?: string;\n    module: FlowContext<C, E, S, Id, I, H>[\"module\"];\n  }\n): FlowContext<C, E, S, Id, I, H> {\n  // Track step and page names to prevent duplicates\n  const usedNames = new Set<string>();\n\n  // Per-invocation snapshot of all of this run's steps, loaded once on first\n  // access. A flow replays its whole body top-to-bottom on every invocation, so\n  // reading every step row up front collapses what used to be one SELECT per\n  // step (O(N) reads per invocation, O(N²) over a run) into a single read.\n  //\n  // `value` is read via a value::text cast rather than as jsonb because the cast\n  // is load-bearing for fidelity: it keeps a void step (SQL NULL → undefined on\n  // replay) distinct from an explicit-null return (jsonb 'null' → \"null\" → null),\n  // a distinction a parsed jsonb read collapses to null, and it preserves the\n  // stored value's keys verbatim through the camelCase plugin. The `ui` jsonb\n  // column is never read on replay, so it is omitted to avoid transferring the\n  // rendered-component blob for every replayed step, every invocation.\n  let stepsSnapshot: Map<string, StepRow[]> | null = null;\n\n  // Set once a completed UI page has been replayed this invocation. A UI page is\n  // the only thing BackFlowRun rewinds to (it resets that page to PENDING and\n  // deletes the steps created after it), so after crossing one we stop trusting\n  // the snapshot and read later steps per-step — exactly as the pre-snapshot code\n  // did — so a concurrent back-deletion is observed on the next step. Steps before\n  // the first UI page are never back-deletable, so they still use the snapshot;\n  // flows with no UI between steps (the O(N²) case) keep the full benefit.\n  let uiBoundaryCrossed = false;\n\n  // For explicit UI submissions, only the expected pending step may consume the\n  // posted data/action. Once that happens, later UI pages in the same replay are\n  // allowed to render normally.\n  let expectedSubmissionConsumed = !expectedStepId;\n\n  async function loadStepsSnapshot(\n    db: Kysely<any>\n  ): Promise<Map<string, StepRow[]>> {\n    if (stepsSnapshot) {\n      return stepsSnapshot;\n    }\n    const rows = (await db\n      .selectFrom(\"keel.flow_step\")\n      .where(\"run_id\", \"=\", runId)\n      .select([\"id\", \"name\", \"status\", \"type\", \"action\"])\n      .select(sql<string | null>`value::text`.as(\"valueRaw\"))\n      .execute()) as StepRow[];\n\n    const map = new Map<string, StepRow[]>();\n    for (const row of rows) {\n      const existing = map.get(row.name);\n      if (existing) {\n        existing.push(row);\n      } else {\n        map.set(row.name, [row]);\n      }\n    }\n    stepsSnapshot = map;\n    return map;\n  }\n\n  // readStepRows reads the rows for a single step directly (lean projection). Used\n  // for the not-yet-completed frontier step, and for every step once a UI boundary\n  // has been crossed.\n  async function readStepRows(\n    db: Kysely<any>,\n    name: string\n  ): Promise<StepRow[]> {\n    return (await db\n      .selectFrom(\"keel.flow_step\")\n      .where(\"run_id\", \"=\", runId)\n      .where(\"name\", \"=\", name)\n      .select([\"id\", \"name\", \"status\", \"type\", \"action\"])\n      .select(sql<string | null>`value::text`.as(\"valueRaw\"))\n      .execute()) as StepRow[];\n  }\n\n  const context: FlowContext<C, E, S, Id, I, H> = {\n    identity: ctx.identity,\n    env: ctx.env,\n    now: ctx.now,\n    secrets: ctx.secrets,\n    trace: ctx.trace,\n    module: ctx.module,\n    complete: (options) => {\n      return {\n        __type: \"ui.complete\",\n        ...options,\n      };\n    },\n    step: async (name, optionsOrFn, fn?) => {\n      return withSpan(\"flow.step\", async (span: opentelemetry.Span) => {\n        return withUserSpan(span, async () => {\n          span.setAttribute(ATTRS.STEP_TYPE, STEP_TYPE.FUNCTION);\n          span.setAttribute(ATTRS.STEP_NAME, name);\n\n          // We need to check the type of the arguments due to the step function being overloaded\n          const options = typeof optionsOrFn === \"function\" ? {} : optionsOrFn;\n          const actualFn = (\n            typeof optionsOrFn === \"function\" ? optionsOrFn : fn!\n          ) as StepFunction<C, any>;\n\n          options.retries = options.retries ?? defaultOpts.retries;\n          options.timeout = options.timeout ?? defaultOpts.timeout;\n\n          const db = useDatabase();\n\n          // Check for duplicate step names\n          if (usedNames.has(name)) {\n            span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n\n            await db\n              .insertInto(\"keel.flow_step\")\n              .values({\n                id: KSUID.randomSync().string,\n                run_id: runId,\n                name: name,\n                stage: options.stage,\n                status: STEP_STATUS.FAILED,\n                type: STEP_TYPE.FUNCTION,\n                error: `Duplicate step name: ${name}`,\n                startTime: new Date(),\n                endTime: new Date(),\n              })\n              .returningAll()\n              .executeTakeFirst();\n\n            throw new Error(`Duplicate step name: ${name}`);\n          }\n          usedNames.add(name);\n\n          // All prior rows for this step. Once a UI boundary has been crossed we\n          // read every step per-step (a back can delete completed steps after a UI\n          // page; see uiBoundaryCrossed). Otherwise the snapshot is authoritative\n          // for COMPLETED steps — a completed step is terminal, so the N already-\n          // completed steps replay straight from the snapshot (the whole point of\n          // loading it). For any other state we re-read this one step directly,\n          // because a concurrent invocation (SQS at-least-once can run two for the\n          // same run) may have completed it since the snapshot was taken; trusting\n          // a stale \"absent\" here would insert a NEW row beside that COMPLETED one\n          // and stall the run. Only the not-yet-completed frontier step pays this\n          // read, so replay stays O(1) reads per invocation.\n          let past: StepRow[];\n          if (uiBoundaryCrossed) {\n            past = await readStepRows(db, name);\n          } else {\n            past = (await loadStepsSnapshot(db)).get(name) ?? [];\n            if (!past.some((step) => step.status === STEP_STATUS.COMPLETED)) {\n              past = await readStepRows(db, name);\n            }\n          }\n\n          const newSteps = past.filter(\n            (step) => step.status === STEP_STATUS.NEW\n          );\n          const completedSteps = past.filter(\n            (step) => step.status === STEP_STATUS.COMPLETED\n          );\n          const failedSteps = past.filter(\n            (step) => step.status === STEP_STATUS.FAILED\n          );\n          const runningSteps = past.filter(\n            (step) => step.status === STEP_STATUS.RUNNING\n          );\n\n          if (newSteps.length > 1) {\n            throw new Error(\"Multiple NEW steps found for the same step\");\n          }\n\n          if (completedSteps.length > 1) {\n            throw new Error(\"Multiple completed steps found for the same step\");\n          }\n\n          if (completedSteps.length === 1 && newSteps.length === 1) {\n            throw new Error(\n              \"Found both a completed and a pending NEW step for the same step\"\n            );\n          }\n\n          if (completedSteps.length === 1) {\n            // step already executed, so this tracing span is internal\n            span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n            span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n            // valueRaw is value::text (see loadStepsSnapshot). SQL NULL means the\n            // step returned undefined (a void step), so replay returns undefined\n            // to match first execution; an explicit null is stored as jsonb 'null'\n            // (\"null\") and parses back to null.\n            const raw = completedSteps[0].valueRaw;\n            return raw == null ? undefined : JSON.parse(raw);\n          }\n\n          // A concurrent invocation has already claimed this step and is executing\n          // it (NEW -> RUNNING). Bail before the NEW claim below: if a stray NEW\n          // row ever coexists with the RUNNING one, claiming and running it would\n          // execute the step a second time. The winning invocation will complete\n          // the step and drive the run forward.\n          if (runningSteps.length >= 1) {\n            span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n            span.addEvent(\"status\", { status: STEP_STATUS.RUNNING });\n            throw new StepCreatedDisrupt();\n          }\n\n          // Do we have a NEW step waiting to be run?\n          if (newSteps.length === 1) {\n            let result = null;\n\n            // Atomically claim the step before executing it. Two orchestrator\n            // invocations can run concurrently for the same run (SQS at-least-once\n            // delivery, redelivered FlowRunUpdated events). Only the invocation that\n            // flips NEW -> RUNNING here gets a row back and goes on to run the\n            // function, so the user's step function executes exactly once.\n            const claimed = await db\n              .updateTable(\"keel.flow_step\")\n              .set({\n                status: STEP_STATUS.RUNNING,\n                startTime: new Date(),\n              })\n              .where(\"id\", \"=\", newSteps[0].id)\n              .where(\"status\", \"=\", STEP_STATUS.NEW)\n              .returning(\"id\")\n              .executeTakeFirst();\n\n            if (!claimed) {\n              // Another concurrent invocation claimed this step and is executing it.\n              // Bail without running the function; the winner will drive the run on.\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n              span.addEvent(\"status\", { status: STEP_STATUS.RUNNING });\n              throw new StepCreatedDisrupt();\n            }\n\n            // Checkpoint L: the \"flow.step\" archetype (Migration step 1 adoption table), marked\n            // ONLY on this invocation - the one that actually claimed the step and is about to run\n            // the customer's function. Every other exit from this span (already completed replay,\n            // a concurrent invocation racing it, losing the claim race, or \"just created, not yet\n            // claimed\") already marks the span keel.internal=children above/below - marking this\n            // span audience=user unconditionally at the top of step() (an earlier version of this\n            // code did) would have coexisted with keel.internal on those occurrences, which the\n            // dual-marking conformance test (main.test.ts) correctly rejects: a span can't be both\n            // \"shown to customers\" and \"hidden from customers\" at once.\n            markUserFacing(span, \"flow.step\");\n\n            // The step owns this row until it reaches a terminal state, so the\n            // writer can update its progress column freely; stop() below\n            // flushes the last snapshot before the terminal status is written.\n            const progress = new ProgressWriter({ stepId: newSteps[0].id, db });\n            if (options.loadingMessage) {\n              progress.handle.set({ message: options.loadingMessage });\n            }\n\n            try {\n              const stepArgs: StepArgs<C> = {\n                attempt: failedSteps.length + 1,\n                stepOptions: options,\n                progress: progress.handle,\n              };\n\n              const stepTimeoutMs = options.timeout;\n              result = await runWithStatementTimeout(db, stepTimeoutMs, () =>\n                withTimeout(\n                  actualFn(stepArgs),\n                  stepTimeoutMs,\n                  STEP_TIMEOUT_JS_GRACE_MS\n                )\n              );\n            } catch (e) {\n              await progress.stop();\n\n              await db\n                .updateTable(\"keel.flow_step\")\n                .set({\n                  status: STEP_STATUS.FAILED,\n                  spanId: spanId,\n                  endTime: new Date(),\n                  error: isQueryCancelledError(e)\n                    ? `Step timed out after ${options.timeout}ms (database query cancelled)`\n                    : e instanceof Error\n                      ? e.message\n                      : \"An error occurred\",\n                })\n                .where(\"id\", \"=\", newSteps[0].id)\n                .returningAll()\n                .executeTakeFirst();\n\n              if (e instanceof NonRetriableError) {\n                span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n\n                if (options.onFailure) {\n                  await options.onFailure!();\n                }\n\n                throw e;\n              }\n\n              if (failedSteps.length >= options.retries) {\n                span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n\n                if (options.onFailure) {\n                  await options.onFailure!();\n                }\n\n                throw new ExhuastedRetriesDisrupt();\n              }\n\n              // If we have retries left, create a new step.\n              // The flow_run row is locked FOR UPDATE so that concurrent invocations\n              // (e.g. a redelivered SQS message or a double-submitted UI step) serialise\n              // here and only one ends up inserting a NEW row for this (run_id, name).\n              await insertNewStep(db, runId, name, options.stage);\n\n              span.addEvent(\"status\", { status: STEP_STATUS.NEW });\n\n              throw new StepCreatedDisrupt(\n                options.retryPolicy\n                  ? new Date(\n                      Date.now() + options.retryPolicy(failedSteps.length + 1)\n                    )\n                  : undefined\n              );\n            }\n\n            await progress.stop();\n\n            // Store the result in the database\n            await db\n              .updateTable(\"keel.flow_step\")\n              .set({\n                status: STEP_STATUS.COMPLETED,\n                value: serializeStepValue(span, name, result),\n                spanId: spanId,\n                endTime: new Date(),\n              })\n              .where(\"id\", \"=\", newSteps[0].id)\n              .returningAll()\n              .executeTakeFirst();\n\n            span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n            return result;\n          }\n\n          // The step hasn't yet run successfully, so we need to create a NEW row.\n          // The flow_run row is locked FOR UPDATE so that concurrent invocations\n          // (e.g. a redelivered SQS message or a double-submitted UI step) serialise\n          // here and only one ends up inserting a NEW row for this (run_id, name).\n          await insertNewStep(db, runId, name, options.stage);\n\n          // step was just created, so this tracing span should be internal\n          span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n          span.addEvent(\"status\", { status: STEP_STATUS.NEW });\n          throw new StepCreatedDisrupt();\n        });\n      });\n    },\n    flows: {\n      run: async (flow, opts) => {\n        return withSpan(\"flow.call\", async (span: opentelemetry.Span) => {\n          return withUserSpan(span, async () => {\n            const name = opts?.name ?? flow.name;\n            const retries = opts?.retries ?? 0;\n            span.setAttribute(ATTRS.STEP_TYPE, STEP_TYPE.FLOW);\n            span.setAttribute(ATTRS.STEP_NAME, name);\n            const db = useDatabase();\n\n            // Check for duplicate step names — same handling as step()/ui.page().\n            if (usedNames.has(name)) {\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n\n              await db\n                .insertInto(\"keel.flow_step\")\n                .values({\n                  id: KSUID.randomSync().string,\n                  run_id: runId,\n                  name: name,\n                  stage: opts?.stage,\n                  status: STEP_STATUS.FAILED,\n                  type: STEP_TYPE.FLOW,\n                  error: `Duplicate step name: ${name}`,\n                  startTime: new Date(),\n                  endTime: new Date(),\n                })\n                .returningAll()\n                .executeTakeFirst();\n\n              throw new Error(`Duplicate step name: ${name}`);\n            }\n            usedNames.add(name);\n\n            // FLOW steps are read per-step, not from the snapshot: their status\n            // is driven by another run (the orchestrator completes/fails them\n            // when the child run finishes) and can change between the snapshot\n            // being taken and this call being reached.\n            const past = await readStepRows(db, name);\n\n            const completed = past.find(\n              (s) => s.status === STEP_STATUS.COMPLETED\n            );\n            if (completed) {\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n              const value = completed.valueRaw\n                ? JSON.parse(completed.valueRaw)\n                : {};\n              return value.data;\n            }\n\n            const inFlight = past.some((s) =>\n              [\n                STEP_STATUS.NEW,\n                STEP_STATUS.PENDING,\n                STEP_STATUS.RUNNING,\n              ].includes(s.status as any)\n            );\n            if (inFlight) {\n              // The child run is in progress; park here. The orchestrator\n              // resumes this run (completing or failing the FLOW step) once\n              // the child run reaches a terminal state.\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n              span.addEvent(\"status\", { status: STEP_STATUS.PENDING });\n              throw new StepCreatedDisrupt();\n            }\n\n            // Unlike step()'s `failedSteps.length >= options.retries` (checked\n            // before the attempt that would exceed it), this counts a\n            // post-failure live read taken here, before the *next* attempt —\n            // so the comparison is `>` rather than `>=`. Both forms yield the\n            // same \"N retries = N+1 attempts\" semantics.\n            const failures = past.filter(\n              (s) => s.status === STEP_STATUS.FAILED\n            );\n            if (failures.length > retries) {\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n              throw new ExhuastedRetriesDisrupt();\n            }\n\n            // Create the FLOW step + child run atomically under the flow_run\n            // lock, guarded by composition depth and journey size. The FAILED\n            // count observed above is passed through so the lock can detect a\n            // stale read (see createChildRun) and avoid duplicating a FAILED\n            // row on a guard failure.\n            await createChildRun(db, runId, name, flow.name, {\n              inputs: opts.inputs,\n              stage: opts?.stage,\n              expectedFailures: failures.length,\n            });\n\n            span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n            span.addEvent(\"status\", { status: STEP_STATUS.PENDING });\n            throw new StepCreatedDisrupt();\n          });\n        });\n      },\n      handoff: async (flow, opts) => {\n        await withSpan(\n          `Handoff - ${flow.name}`,\n          async (span: opentelemetry.Span) => {\n            return withUserSpan(span, async () => {\n              span.setAttribute(ATTRS.STEP_TYPE, STEP_TYPE.FLOW);\n              span.setAttribute(ATTRS.STEP_NAME, flow.name);\n              const db = useDatabase();\n\n              const self = await db\n                .selectFrom(\"keel.flow_run\")\n                .select([\"parentRunId\"])\n                .where(\"id\", \"=\", runId)\n                .executeTakeFirst();\n\n              if (self?.parentRunId) {\n                throw new NonRetriableError(\n                  \"handoff is not supported in child flows in v1; return a result and let the parent decide\"\n                );\n              }\n\n              const stepName = `handoff:${flow.name}`;\n              const successor = await createHandoffRun(\n                db,\n                runId,\n                stepName,\n                flow.name,\n                opts.inputs\n              );\n\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n              throw new HandoffDisrupt(flow.name, successor.runId);\n            });\n          }\n        );\n        // Unreachable: withSpan/withUserSpan (untyped JS) always propagate the\n        // HandoffDisrupt (or NonRetriableError) thrown above rather than\n        // returning, but their lack of type info means TS can't see that this\n        // function never resolves. This satisfies the Promise<never> contract.\n        throw new Error(\"unreachable\");\n      },\n    },\n    continue: (async (inputs: unknown, opts?: ContinueOptions) => {\n      await withSpan(`Continue`, async (span: opentelemetry.Span) => {\n        return withUserSpan(span, async () => {\n          span.setAttribute(\"step.type\", STEP_TYPE.FLOW);\n          const db = useDatabase();\n\n          // A continuation is a self-handoff, so the successor's flow name is\n          // this run's own (proto) flow name, read from the run row.\n          const self = await db\n            .selectFrom(\"keel.flow_run\")\n            .select([\"name\", \"parentRunId\"])\n            .where(\"id\", \"=\", runId)\n            .executeTakeFirst();\n\n          if (!self) {\n            throw new NonRetriableError(`flow run not found: ${runId}`);\n          }\n          if (self.parentRunId) {\n            throw new NonRetriableError(\n              \"continue is not supported in child flows; return a result and let the parent decide\"\n            );\n          }\n\n          span.setAttribute(ATTRS.STEP_NAME, self.name);\n\n          // One journal step per run: a run continues at most once, so the\n          // step name needs no discriminator — a replay after the journal\n          // committed finds it and re-reports the same successor.\n          const stepName = `continue:${self.name}`;\n          const successor = await createHandoffRun(\n            db,\n            runId,\n            stepName,\n            self.name,\n            inputs,\n            opts?.after\n          );\n\n          span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n          span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n          throw new HandoffDisrupt(\n            self.name,\n            successor.runId,\n            successor.executeAfter\n          );\n        });\n      });\n      // Unreachable — see the same pattern in ctx.flows.handoff above.\n      throw new Error(\"unreachable\");\n    }) as FlowContext<C, E, S, Id, I, H>[\"continue\"],\n    ui: {\n      page: (async (name, options) => {\n        return withSpan(\"flow.page\", async (span: opentelemetry.Span) => {\n          return withUserSpan(span, async () => {\n            span.setAttribute(ATTRS.STEP_TYPE, STEP_TYPE.UI);\n            span.setAttribute(ATTRS.STEP_NAME, name);\n\n            const db = useDatabase();\n\n            const isCallback = element && callback;\n\n            // Check for duplicate step names\n            if (usedNames.has(name)) {\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n\n              await db\n                .insertInto(\"keel.flow_step\")\n                .values({\n                  id: KSUID.randomSync().string,\n                  run_id: runId,\n                  name: name,\n                  stage: options.stage,\n                  status: STEP_STATUS.FAILED,\n                  type: STEP_TYPE.UI,\n                  error: `Duplicate step name: ${name}`,\n                  startTime: new Date(),\n                  endTime: new Date(),\n                })\n                .returningAll()\n                .executeTakeFirst();\n\n              throw new Error(`Duplicate step name: ${name}`);\n            }\n            usedNames.add(name);\n\n            // Replays a terminal (COMPLETED) UI step: parse the stored form data\n            // (value::text, so keys round-trip verbatim) and return it, plus the\n            // submitted action when the page defined actions.\n            //\n            // UI steps are read under the flow_run lock below rather than from the\n            // per-invocation snapshot: a UI step is NOT reliably terminal because\n            // \"back\" (BackFlowRun) resets the last completed UI step to PENDING and\n            // deletes the steps after it. A stale snapshot could otherwise replay a\n            // page the user has already navigated back past. The UI page is the\n            // gate that protects the function-step snapshot from the same hazard —\n            // a reset always lands on a UI step, and the flow must pass through this\n            // fresh locked read to reach any later (now-deleted) function steps.\n            const replayCompletedUiStep = async (completed: StepRow) => {\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n\n              const rawValue = completed.valueRaw;\n              const storedData = rawValue == null ? null : JSON.parse(rawValue);\n              const parsedData = await applyElementGetData(\n                options.content as any,\n                transformRichDataTypes(storedData)\n              );\n\n              if (completed.action) {\n                // With actions the flow always returns { data, action }.\n                return { data: parsedData, action: completed.action };\n              }\n              return parsedData;\n            };\n\n            // Serialise concurrent bodies for this run via SELECT FOR UPDATE on\n            // the parent flow_run row, matching insertNewStep above. Without\n            // this, two concurrent invocations can both SELECT (find nothing)\n            // and both INSERT a PENDING row, stranding the run in AWAITING_INPUT\n            // once one of the duplicates is later completed.\n            const { step, inserted } = await db\n              .transaction()\n              .execute(async (trx) => {\n                await trx\n                  .selectFrom(\"keel.flow_run\")\n                  .select(\"id\")\n                  .where(\"id\", \"=\", runId)\n                  .forUpdate()\n                  .executeTakeFirst();\n\n                // `value` is also selected as raw text so the KeelCamelCasePlugin's\n                // recursive mapRow never transforms keys inside the stored form\n                // data (same fidelity fix as the function-step read above).\n                const existing = await trx\n                  .selectFrom(\"keel.flow_step\")\n                  .where(\"run_id\", \"=\", runId)\n                  .where(\"name\", \"=\", name)\n                  .selectAll()\n                  .select(sql<string | null>`value::text`.as(\"valueRaw\"))\n                  .executeTakeFirst();\n\n                if (existing) {\n                  return { step: existing, inserted: false };\n                }\n\n                if (expectedStepId && !expectedSubmissionConsumed) {\n                  return { step: undefined, inserted: false };\n                }\n\n                const created = await trx\n                  .insertInto(\"keel.flow_step\")\n                  .values({\n                    id: KSUID.randomSync().string,\n                    run_id: runId,\n                    name: name,\n                    stage: options.stage,\n                    status: STEP_STATUS.PENDING,\n                    type: STEP_TYPE.UI,\n                    startTime: new Date(),\n                  })\n                  .returningAll()\n                  .executeTakeFirstOrThrow();\n\n                return { step: created, inserted: true };\n              });\n\n            // The page this request is submitting has already been recorded by\n            // another request (e.g. a double submit milliseconds apart that both\n            // passed the Go pending-step check). Replaying it would carry this\n            // request on with full powers, claiming and running whatever comes\n            // next concurrently with the request that actually recorded the\n            // page, so stop here and leave the run untouched. Only the submitted\n            // page is affected: earlier completed pages have other ids and\n            // replay below.\n            if (\n              expectedStepId &&\n              !expectedSubmissionConsumed &&\n              step?.id === expectedStepId &&\n              step.status === STEP_STATUS.COMPLETED\n            ) {\n              span.setAttribute(KEEL_INTERNAL_ATTR, KEEL_INTERNAL_CHILDREN);\n              span.addEvent(\"duplicate submission\", {\n                [ATTRS.FLOW_RUN_ID]: runId,\n                [ATTRS.STEP_ID]: step.id,\n                [ATTRS.STEP_STATUS]: step.status,\n              });\n              throw new DuplicateSubmissionDisrupt(step.id);\n            }\n\n            // A previously-submitted UI step replays here, from the row read\n            // under the lock above (so a \"back\" reset is always observed). Steps\n            // are only ever run to completion once. The locked read selects\n            // value::text (valueRaw) too, so this row satisfies StepRow.\n            if (step && step.status === STEP_STATUS.COMPLETED) {\n              // Crossing a completed UI page: from here on, stop serving steps\n              // from the snapshot (see uiBoundaryCrossed) so later steps are\n              // re-read per-step and a concurrent BackFlowRun deletion of those\n              // steps is observed — matching the pre-snapshot per-step reads.\n              uiBoundaryCrossed = true;\n              return replayCompletedUiStep(step as StepRow);\n            }\n\n            // Checkpoint L: the \"flow.page\" archetype (Migration step 1 adoption table), marked\n            // only once we know this occurrence is NOT the internal replay of an already-completed\n            // page (that branch, above, sets keel.internal=children on the same span - see the\n            // matching comment on ctx.step() above for why marking has to be conditional rather\n            // than unconditional at span creation). Every path below this point (render, callback,\n            // submission processing, completion) is a genuine, currently-happening customer-visible\n            // occurrence of this page.\n            markUserFacing(span, \"flow.page\");\n\n            if (\n              expectedStepId &&\n              !expectedSubmissionConsumed &&\n              step?.id !== expectedStepId\n            ) {\n              span.addEvent(\"status\", { status: step?.status ?? \"MISSING\" });\n              throw new Error(\"invalid pending UI step\");\n            }\n\n            if (expectedStepId && step?.id === expectedStepId) {\n              expectedSubmissionConsumed = true;\n            }\n\n            if (inserted) {\n              span.setAttribute(ATTRS.STEP_RENDERED, true);\n              span.addEvent(\"status\", { status: STEP_STATUS.PENDING });\n\n              // We now render the UI by disrupting the step with UIRenderDisrupt.\n              throw new UIRenderDisrupt(\n                step?.id,\n                (await page(options, null, null)).page\n              );\n            }\n\n            if (isCallback) {\n              span.setAttribute(\"callback\", callback);\n              span.addEvent(\"status\", { status: STEP_STATUS.PENDING });\n\n              // we now need to resolve a UI callback.\n              try {\n                const response = await callbackFn(\n                  options.content,\n                  element,\n                  callback,\n                  data\n                );\n                throw new CallbackDisrupt(response, false);\n              } catch (e) {\n                if (e instanceof CallbackDisrupt) {\n                  throw e;\n                }\n\n                throw new CallbackDisrupt(\n                  e instanceof Error ? e.message : `An error occurred`,\n                  true\n                );\n              }\n            }\n\n            if (!data) {\n              span.addEvent(\"status\", { status: STEP_STATUS.PENDING });\n              // If no data has been passed in, render the UI by disrupting the step with UIRenderDisrupt.\n              throw new UIRenderDisrupt(\n                step?.id,\n                (await page(options, null, null)).page\n              );\n            }\n\n            try {\n              const p = await page(options, data, action);\n\n              if (p.hasValidationErrors) {\n                throw new UIRenderDisrupt(step?.id, p.page);\n              }\n            } catch (e) {\n              if (e instanceof UIRenderDisrupt) {\n                span.addEvent(\"status\", { status: STEP_STATUS.PENDING });\n                throw e;\n              }\n\n              // Guarded on PENDING like the completion below: if another request\n              // has recorded this page meanwhile, the run is theirs, and failing\n              // it over this request's submission would be wrong.\n              const failed = await db\n                .updateTable(\"keel.flow_step\")\n                .set({\n                  status: STEP_STATUS.FAILED,\n                  spanId: spanId,\n                  endTime: new Date(),\n                  error: e instanceof Error ? e.message : \"An error occurred\",\n                })\n                .where(\"id\", \"=\", step!.id)\n                .where(\"status\", \"=\", STEP_STATUS.PENDING)\n                .returningAll()\n                .executeTakeFirst();\n\n              if (!failed) {\n                span.addEvent(\"duplicate submission\", {\n                  [ATTRS.FLOW_RUN_ID]: runId,\n                  [ATTRS.STEP_ID]: step!.id,\n                });\n                throw new DuplicateSubmissionDisrupt(step!.id);\n              }\n\n              span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.FAILED);\n              throw e;\n            }\n\n            // If the data has been passed in and is valid, persist the data (and action if applicable) and mark the step as COMPLETED, and then return the data.\n            //\n            // The PENDING guard makes completion atomic: the page was read\n            // PENDING under the flow_run lock above, but that lock has since been\n            // released, so two submissions can both get here. Only one UPDATE\n            // can match; the other request recorded nothing and must stop.\n            const completed = await db\n              .updateTable(\"keel.flow_step\")\n              .set({\n                status: STEP_STATUS.COMPLETED,\n                value: serializeStepValue(span, name, data),\n                action: action,\n                spanId: spanId,\n                endTime: new Date(),\n              })\n              .where(\"id\", \"=\", step!.id)\n              .where(\"status\", \"=\", STEP_STATUS.PENDING)\n              .returningAll()\n              .executeTakeFirst();\n\n            if (!completed) {\n              span.addEvent(\"duplicate submission\", {\n                [ATTRS.FLOW_RUN_ID]: runId,\n                [ATTRS.STEP_ID]: step!.id,\n              });\n              throw new DuplicateSubmissionDisrupt(step!.id);\n            }\n\n            span.setAttribute(ATTRS.STEP_STATUS, STEP_STATUS.COMPLETED);\n\n            // Completing a UI page here (a fresh submit) crosses the same\n            // back-boundary as replaying an already-completed one above: from now\n            // on, read later steps per-step rather than from the snapshot, in case\n            // a concurrent BackFlowRun reset this page and deleted those steps.\n            uiBoundaryCrossed = true;\n\n            const parsedData = await applyElementGetData(\n              options.content as any,\n              transformRichDataTypes(data)\n            );\n\n            // Only return the { data, action } wrapper when actions are defined\n            if (action) {\n              return { data: parsedData, action };\n            }\n            return parsedData;\n          });\n        });\n      }) as UiPage<C>,\n      inputs: {\n        text: textInput as any,\n        number: numberInput as any,\n        boolean: booleanInput as any,\n        dataGrid: dataGridInput as any,\n        datePicker: datePickerInput as any,\n        scan: scan as any,\n        file: fileInput as any,\n        imageCapture: imageCapture as any,\n        signature: signatureInput as any,\n      },\n      display: {\n        divider: divider as any,\n        markdown: markdown as any,\n        table: table as any,\n        header: header as any,\n        banner: banner as any,\n        image: image as any,\n        code: code as any,\n        grid: grid as any,\n        list: list as any,\n        keyValue: keyValue as any,\n        file: file as any,\n        summary: summary as any,\n        timeline: timeline as any,\n      },\n      select: {\n        one: selectOne as any,\n        table: selectTable as any,\n      },\n      iterator: iterator as any,\n      interactive: {\n        print: print as any,\n        pickList: pickList as any,\n      },\n    },\n  };\n\n  (context as any)[ENGINE] = () =>\n    resolveEngine(ctx.engine, ctx.secrets, ctx.aiGateway, runId, ctx.flowName);\n  (context as any)[DECISION_ENGINE] = () =>\n    resolveDecisionEngine(\n      ctx.decisionEngine,\n      ctx.aiGateway,\n      runId,\n      ctx.flowName\n    );\n  (context as any)[EXTRACTION_ENGINE] = () =>\n    resolveExtractionEngine(\n      ctx.extractionEngine,\n      ctx.aiGateway,\n      runId,\n      ctx.flowName\n    );\n\n  return context;\n}\n\nfunction wait(milliseconds: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\n// How long the JS-level step timeout waits beyond the declared step timeout.\n// The server-side statement_timeout (see runWithStatementTimeout) is the\n// primary enforcement mechanism - it cancels the query in Postgres and raises\n// a catchable error (57014) even when the Node event loop is blocked. The JS\n// race is a secondary signal for steps that are slow without any SQL in\n// flight, so it fires slightly later to let the deterministic server-side\n// error win for SQL-bound steps.\nconst STEP_TIMEOUT_JS_GRACE_MS = 1000;\n\nfunction withTimeout<T>(\n  promiseFn: Promise<T>,\n  timeout: number,\n  graceMs = 0\n): Promise<T> {\n  return Promise.race([\n    promiseFn,\n    wait(timeout + graceMs).then(() => {\n      throw new Error(`Step function timed out after ${timeout}ms`);\n    }),\n  ]);\n}\n\nfunction isQueryCancelledError(e: any): boolean {\n  // 57014 = query_canceled, raised by Postgres when statement_timeout fires.\n  // Either a raw pg error or the DatabaseError wrapper from errors.js, which\n  // keeps the original error on .error.\n  return e?.code === \"57014\" || e?.error?.code === \"57014\";\n}\n\n// Applies a session-level statement_timeout for the duration of fn, then\n// restores the pool default. Flow invocations are pinned to a single pooled\n// connection (see tryExecuteFlow/withDatabase), so the setting covers exactly\n// the step's queries. set_config is used because SET does not accept bind\n// parameters. Best-effort: if session config can't be applied (e.g.\n// transaction-pooled endpoints) the JS timeout remains the fallback.\n//\n// The finally-RESET runs before the caller's catch block, which matters: the\n// catch marks the step FAILED on the same connection, and a small step\n// timeout still in force could cancel that update too, stranding the step in\n// RUNNING.\nasync function runWithStatementTimeout<T>(\n  db: Kysely<any>,\n  timeoutMs: number,\n  fn: () => Promise<T>\n): Promise<T> {\n  let applied = false;\n  try {\n    await sql`select set_config('statement_timeout', ${String(Math.max(1, Math.round(timeoutMs)))}, false)`.execute(\n      db\n    );\n    applied = true;\n  } catch {\n    // proceed without server-side enforcement\n  }\n  try {\n    return await fn();\n  } finally {\n    if (applied) {\n      // RESET restores the session default, which is the pool-level\n      // statement_timeout sent in the connection startup packet.\n      await sql`reset statement_timeout`.execute(db).catch(() => {});\n    }\n  }\n}\n\nexport { UI, NonRetriableError };\n// exported for tests only\nexport { runWithStatementTimeout };\nexport type { ProgressHandle, ProgressPatch, StepProgress };\nexport { Signature } from \"./ui/elements/input/signature\";\nexport type {\n  DataGridOption,\n  DataGridSummaryBlock,\n  DataGridSummaryItem,\n  DataGridTotal,\n  DataGridTotals,\n} from \"./ui/elements/input/dataGrid\";\nexport type {\n  ColumnFormat,\n  ColumnNumberFormat,\n  ColumnNumberColor,\n  ColumnTextFormat,\n  ColumnBooleanFormat,\n  ColumnValueFormat,\n} from \"./ui/elements/format\";\nexport type {\n  TimelineGranularity,\n  TimelineItem,\n  TimelineItemInput,\n  TimelineRow,\n} from \"./ui/elements/display/timeline\";\n","import {\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElement,\n} from \"../..\";\n\ntype ElementDataType = string;\n\nexport type UiElementInputText = InputElement<\n  ElementDataType,\n  {\n    placeholder?: string;\n    multiline?: boolean;\n    maxLength?: number;\n    minLength?: number;\n  }\n>;\n\n// The shape of the response over the API\nexport interface UiElementInputTextApiResponse extends BaseUiInputResponse<\n  \"ui.input.text\",\n  ElementDataType\n> {\n  placeholder?: string;\n  multiline?: boolean;\n  maxLength?: number;\n  minLength?: number;\n}\n\nexport const textInput: InputElementImplementation<\n  ElementDataType,\n  UiElementInputText,\n  UiElementInputTextApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.text\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n      defaultValue: options?.defaultValue,\n      placeholder: options?.placeholder,\n      multiline: options?.multiline,\n      maxLength: options?.maxLength,\n      minLength: options?.minLength,\n    } satisfies UiElementInputTextApiResponse,\n    validate: options?.validate,\n    onLeave: options?.onLeave,\n    getData: (x: ElementDataType) => x,\n  };\n};\n","import {\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElement,\n} from \"../..\";\n\ntype ElementDataType = number;\n\nexport type UiElementInputNumber = InputElement<\n  ElementDataType,\n  {\n    placeholder?: string;\n    min?: number;\n    max?: number;\n  }\n>;\n\n// The shape of the response over the API\nexport interface UiElementInputNumberApiResponse extends BaseUiInputResponse<\n  \"ui.input.number\",\n  ElementDataType\n> {\n  placeholder?: string;\n  min?: number;\n  max?: number;\n}\n\nexport const numberInput: InputElementImplementation<\n  ElementDataType,\n  UiElementInputNumber,\n  UiElementInputNumberApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.number\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n      defaultValue: options?.defaultValue,\n      placeholder: options?.placeholder,\n      min: options?.min,\n      max: options?.max,\n    } satisfies UiElementInputNumberApiResponse,\n    validate: options?.validate,\n    onLeave: options?.onLeave,\n    getData: (x: any) => x,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\nexport type UiElementDivider = DisplayElement<{}>;\n\n// The shape of the response over the API\nexport interface UiElementDividerApiResponse extends BaseUiDisplayResponse<\"ui.display.divider\"> {}\n\nexport const divider: DisplayElementImplementation<\n  UiElementDivider,\n  UiElementDividerApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.divider\",\n    } satisfies UiElementDividerApiResponse,\n  };\n};\n","import {\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElement,\n} from \"../..\";\n\ntype ElementDataType = boolean;\n\nexport type UiElementInputBoolean = InputElement<\n  ElementDataType,\n  {\n    mode?: \"checkbox\" | \"switch\";\n  }\n>;\n\n// The shape of the response over the API\nexport interface UiElementInputBooleanApiResponse extends BaseUiInputResponse<\n  \"ui.input.boolean\",\n  ElementDataType\n> {\n  mode: \"checkbox\" | \"switch\";\n}\n\nexport const booleanInput: InputElementImplementation<\n  ElementDataType,\n  UiElementInputBoolean,\n  UiElementInputBooleanApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.boolean\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n      defaultValue: options?.defaultValue,\n      mode: options?.mode || \"checkbox\",\n    } satisfies UiElementInputBooleanApiResponse,\n    validate: options?.validate,\n    onLeave: options?.onLeave,\n    getData: (x: any) => x,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\nexport type UiElementMarkdown = DisplayElement<{\n  content: string;\n}>;\n\n// The shape of the response over the API\nexport interface UiElementMarkdownApiResponse extends BaseUiDisplayResponse<\"ui.display.markdown\"> {\n  content: string;\n}\n\nexport const markdown: DisplayElementImplementation<\n  UiElementMarkdown,\n  UiElementMarkdownApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.markdown\",\n      content: options?.content || \"\",\n    } satisfies UiElementMarkdownApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementConfig,\n  DisplayElementResponse,\n} from \"../..\";\n\nexport type TableData<T extends Record<string, any>> = {\n  data: T[];\n  columns?: Array<Extract<keyof T, string>>;\n};\n\nexport type UiElementTable = <\n  const T extends Record<string, any>,\n  K extends string = never,\n>(\n  options: TableData<T> & DisplayElementConfig<K>\n) => DisplayElementResponse<K>;\n\nexport type TableColumn = {\n  name: string;\n  index: number;\n};\n\n// The shape of the response over the API\nexport interface UiElementTableApiResponse extends BaseUiDisplayResponse<\"ui.display.table\"> {\n  data: any[];\n  columns: TableColumn[];\n}\n\nexport const table: DisplayElementImplementation<\n  UiElementTable,\n  UiElementTableApiResponse\n> = (options) => {\n  const { data, columns } = processTableData(options.data, options.columns);\n\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.table\",\n      data: data || [],\n      columns: columns || [],\n    } satisfies UiElementTableApiResponse,\n  };\n};\n\n// Only send data for columns we need\nexport const processTableData = (data: any[], columnsConfig?: string[]) => {\n  const filteredData = columnsConfig\n    ? data.map((item) => {\n        return Object.fromEntries(\n          Object.entries(item).filter(([key]) =>\n            columnsConfig?.includes(key as any)\n          )\n        );\n      })\n    : data;\n\n  const cols = Object.keys(filteredData[0] || {});\n  const columns: TableColumn[] = cols.map((column, index) => ({\n    name: column,\n    index,\n  }));\n\n  return { data: filteredData, columns };\n};\n","import {\n  BaseInputConfig,\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElementResponse,\n} from \"../..\";\n\ntype ElementDataType = string | number | boolean | Date;\n\n// Annoyingly can't use the whole InputElement type and also use a local\n// bounded type parameter to infer the type of the value from the config options\n// So having to duplicate the types of the inputs\nexport type UiElementSelectOne = <\n  const TValue extends ElementDataType,\n  N extends string,\n  O extends boolean = false,\n>(\n  name: N,\n  options?: BaseInputConfig<TValue, O> & {\n    options: (\n      | {\n          label: string;\n          value: TValue;\n        }\n      | TValue\n    )[];\n  }\n) => InputElementResponse<N, O extends true ? TValue | undefined : TValue>;\n\n// The shape of the response over the API\nexport interface UiElementSelectOneApiResponse extends BaseUiInputResponse<\n  \"ui.select.one\",\n  ElementDataType\n> {\n  options: (\n    | {\n        label: string;\n        value: ElementDataType;\n      }\n    | ElementDataType\n  )[];\n}\n\nexport const selectOne: InputElementImplementation<\n  ElementDataType,\n  UiElementSelectOne,\n  UiElementSelectOneApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.select.one\",\n      name,\n      label: options?.label || name,\n      defaultValue: options?.defaultValue,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n      options: options?.options || [],\n    } satisfies UiElementSelectOneApiResponse,\n    validate: options?.validate,\n    getData: (x: ElementDataType) => x,\n  };\n};\n","class CelError extends Error {\n  #node\n  #code\n  #range\n  #summary\n\n  constructor({name, code, message, node, cause, range}) {\n    super(message, cause ? {cause} : undefined)\n\n    this.name = name\n    this.#code = code\n\n    this.#summary = message\n    this.#node = node\n    this.#range = (range && normalizeRange(range)) || normalizeRange(node)\n\n    if (!node?.input) return\n    this.message = formatErrorWithHighlight(this.#summary, node, this.#range)\n  }\n\n  get node() {\n    return this.#node\n  }\n\n  get code() {\n    return this.#code\n  }\n\n  get range() {\n    return this.#range\n  }\n\n  get summary() {\n    return this.#summary\n  }\n\n  withAst(node) {\n    if (this.#node || !node?.input) return this\n    this.#node = node\n    this.#range ??= normalizeRange(node)\n    this.message = formatErrorWithHighlight(this.#summary, node, this.#range)\n    return this\n  }\n}\n\nfunction normalizeArgs(name, defaultCode, message, node, cause) {\n  if (typeof message === 'string') return {name, code: defaultCode, message, node, cause}\n\n  const opts = message\n  if (typeof opts !== 'object') throw new Error('First param to error must be a string or object')\n\n  return {\n    name,\n    code: opts.code || defaultCode,\n    message: opts.message,\n    node: opts.node,\n    cause: opts.cause,\n    range: opts.range\n  }\n}\n\nexport class ParseError extends CelError {\n  constructor(message, node, cause) {\n    super(normalizeArgs('ParseError', 'parse_error', message, node, cause))\n  }\n}\n\nexport class EvaluationError extends CelError {\n  constructor(message, node, cause) {\n    super(normalizeArgs('EvaluationError', 'evaluation_error', message, node, cause))\n  }\n}\n\nexport class TypeError extends CelError {\n  constructor(message, node, cause) {\n    super(normalizeArgs('TypeError', 'type_error', message, node, cause))\n  }\n}\n\nexport function parseError(code, message, node) {\n  if (typeof code === 'object') return new ParseError(code)\n  return new ParseError({code, message, node})\n}\n\nexport function evaluationError(code, message, node) {\n  if (typeof code === 'object') return new EvaluationError(code)\n  return new EvaluationError({code, message, node})\n}\n\nexport function typeError(code, message, node) {\n  if (typeof code === 'object') return new TypeError(code)\n  return new TypeError({code, message, node})\n}\n\nfunction normalizeRange(node) {\n  const start = node?.pos ?? node?.start\n  if (typeof start !== 'number') return\n  const end = typeof node.end === 'number' ? node.end : start\n  return {start, end}\n}\n\nfunction formatErrorWithHighlight(message, node, range) {\n  const pos = node.pos ?? range?.start\n  if (typeof pos !== 'number') return message\n\n  const input = node.input\n\n  let lineNum = 1\n  let currentPos = 0\n  let columnNum = 0\n  while (currentPos < pos) {\n    if (input[currentPos] === '\\n') {\n      lineNum++\n      columnNum = 0\n    } else {\n      columnNum++\n    }\n    currentPos++\n  }\n\n  let contextStart = pos\n  let contextEnd = pos\n  while (contextStart > 0 && input[contextStart - 1] !== '\\n') contextStart--\n  while (contextEnd < input.length && input[contextEnd] !== '\\n') contextEnd++\n\n  const line = input.slice(contextStart, contextEnd)\n  const highlight = `> ${`${lineNum}`.padStart(4, ' ')} | ${line}\\n${' '.repeat(9 + columnNum)}^`\n\n  return `${message}\\n\\n${highlight}`\n}\n\nexport function attachErrorAst(error, node) {\n  if (error instanceof CelError) return error.withAst(node)\n  return error\n}\n","import {evaluationError} from './errors.js'\n\nexport class Optional {\n  #value\n\n  constructor(value) {\n    this.#value = value\n  }\n\n  static of(value) {\n    if (value === undefined) return OPTIONAL_NONE\n    return new Optional(value)\n  }\n\n  static none() {\n    return OPTIONAL_NONE\n  }\n\n  hasValue() {\n    return this.#value !== undefined\n  }\n\n  value() {\n    if (this.#value === undefined) {\n      throw evaluationError('optional_value_missing', 'Optional value is not present')\n    }\n    return this.#value\n  }\n\n  or(optional) {\n    if (this.#value !== undefined) return this\n    if (optional instanceof Optional) return optional\n    throw evaluationError(\n      'invalid_optional_argument',\n      'Optional.or must be called with an Optional argument'\n    )\n  }\n\n  orValue(defaultValue) {\n    return this.#value === undefined ? defaultValue : this.#value\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'optional'\n  }\n\n  [Symbol.for('nodejs.util.inspect.custom')]() {\n    return this.#value === undefined\n      ? `Optional { none }`\n      : `Optional { value: ${JSON.stringify(this.#value)} }`\n  }\n}\n\nexport const OPTIONAL_NONE = Object.freeze(new Optional())\n\nclass OptionalNamespace {}\nconst optionalNamespace = new OptionalNamespace()\n\nexport function toggleOptionalTypes(registry, enable) {\n  const optionalConstant = enable ? optionalNamespace : undefined\n  registry.deleteVariable('optional')\n  registry.registerConstant('optional', 'OptionalNamespace', optionalConstant)\n}\n\nexport function register(registry) {\n  const sync = {async: false}\n  const functionOverload = (sig, handler) => registry.registerFunctionOverload(sig, handler, sync)\n\n  const optionalConstant = registry.enableOptionalTypes ? optionalNamespace : undefined\n  registry.registerType('OptionalNamespace', OptionalNamespace)\n  registry.registerConstant('optional', 'OptionalNamespace', optionalConstant)\n  functionOverload('optional.hasValue(): bool', (v) => v.hasValue())\n  functionOverload('optional<A>.value(): A', (v) => v.value())\n  registry.registerFunctionOverload('OptionalNamespace.none(): optional<T>', () => Optional.none())\n  functionOverload('OptionalNamespace.of(A): optional<A>', (_, value) => Optional.of(value))\n  function ensureOptional(value, ast, description) {\n    if (value instanceof Optional) return value\n    throw evaluationError('optional_expected', `${description} must be optional`, ast)\n  }\n\n  function evaluateOptional(ev, macro, ctx) {\n    const v = ev.run(macro.receiver, ctx)\n    if (v instanceof Promise) return v.then((_v) => handleOptionalResolved(_v, ev, macro, ctx))\n    return handleOptionalResolved(v, ev, macro, ctx)\n  }\n\n  function handleOptionalResolved(value, ev, macro, ctx) {\n    const optional = ensureOptional(value, macro.receiver, `${macro.functionDesc} receiver`)\n    if (optional.hasValue()) return macro.onHasValue(optional)\n    return macro.onEmpty(ev, macro, ctx)\n  }\n\n  function ensureOptionalType(checker, node, ctx, description) {\n    const type = checker.check(node, ctx)\n    if (type.kind === 'optional') return type\n    if (type.kind === 'dyn') return checker.getType('optional')\n    throw checker.createError('optional_expected', `${description} must be optional, got '${type}'`, node)\n  }\n\n  function createOptionalMacro({functionDesc, evaluate, typeCheck, onHasValue, onEmpty}) {\n    return ({ast, args, receiver}) => ({\n      ast,\n      functionDesc,\n      receiver,\n      arg: args[0],\n      evaluate,\n      typeCheck,\n      onHasValue,\n      onEmpty\n    })\n  }\n\n  const invalidOrValueReceiver = 'optional.orValue() receiver'\n  const invalidOrReceiver = 'optional.or(optional) receiver'\n  const invalidOrArg = 'optional.or(optional) argument'\n  registry.registerFunctionOverload(\n    'optional.or(ast): optional<dyn>',\n    createOptionalMacro({\n      functionDesc: 'optional.or(optional)',\n      evaluate: evaluateOptional,\n      typeCheck(check, macro, ctx) {\n        const l = ensureOptionalType(check, macro.receiver, ctx, invalidOrReceiver)\n        const r = ensureOptionalType(check, macro.arg, ctx, invalidOrArg)\n        if (!(macro.receiver.maybeAsync || macro.arg.maybeAsync)) macro.ast.setMeta('async', false)\n\n        const unified = l.unify(check.registry, r)\n        if (unified) return unified\n        throw check.createError(\n          'incompatible_argument_type',\n          `${macro.functionDesc} argument must be compatible type, got '${l}' and '${r}'`,\n          macro.arg\n        )\n      },\n      onHasValue: (optional) => optional,\n      onEmpty(ev, macro, ctx) {\n        const ast = macro.arg\n        const v = ev.run(ast, ctx)\n        if (v instanceof Promise) return v.then((_v) => ensureOptional(_v, ast, invalidOrArg))\n        return ensureOptional(v, ast, invalidOrArg)\n      }\n    })\n  )\n\n  registry.registerFunctionOverload(\n    'optional.orValue(ast): dyn',\n    createOptionalMacro({\n      functionDesc: 'optional.orValue(value)',\n      onHasValue: (optionalValue) => optionalValue.value(),\n      onEmpty(ev, macro, ctx) {\n        return ev.run(macro.arg, ctx)\n      },\n      evaluate: evaluateOptional,\n      typeCheck(check, macro, ctx) {\n        const l = ensureOptionalType(check, macro.receiver, ctx, invalidOrValueReceiver).valueType\n        const r = check.check(macro.arg, ctx)\n        if (!(macro.receiver.maybeAsync || macro.arg.maybeAsync)) macro.ast.setMeta('async', false)\n\n        const unified = l.unify(check.registry, r)\n        if (unified) return unified\n        throw check.createError(\n          'incompatible_argument_type',\n          `${macro.functionDesc} argument must be compatible type, got '${l}' and '${r}'`,\n          macro.arg\n        )\n      }\n    })\n  )\n}\n","export const hasOwn = Object.hasOwn\nexport const objKeys = Object.keys\nexport const objFreeze = Object.freeze\nexport const objEntries = Object.entries\nexport const isArray = Array.isArray\nexport const arrayFrom = Array.from\n\nexport const MIN_UINT = 0n\nexport const MAX_UINT = 18446744073709551615n\n\nexport const MAX_INT = 9223372036854775807n\nexport const MIN_INT = -9223372036854775808n\n\nexport function isAsync(fn, fallback) {\n  if (fn?.[Symbol.toStringTag] === 'AsyncFunction') return true\n  return typeof fallback === 'boolean' ? fallback : true\n}\n\nexport const RESERVED = new Set([\n  'as',\n  'break',\n  'const',\n  'continue',\n  'else',\n  'for',\n  'function',\n  'if',\n  'import',\n  'let',\n  'loop',\n  'package',\n  'namespace',\n  'return',\n  'var',\n  'void',\n  'while',\n  '__proto__',\n  'prototype'\n])\n","import {evaluationError} from './errors.js'\nimport {TYPES, Type} from './registry.js'\nimport {register as registerOptional} from './optional.js'\nimport {objKeys, arrayFrom, MIN_UINT, MAX_UINT, MIN_INT, MAX_INT} from './globals.js'\n\nexport class UnsignedInt {\n  #value\n  constructor(value) {\n    this.verify(typeof value === 'bigint' ? value : BigInt(value))\n  }\n\n  get value() {\n    return this.#value\n  }\n\n  valueOf() {\n    return this.#value\n  }\n\n  toString() {\n    return `${this.#value}`\n  }\n\n  verify(v) {\n    if (v < MIN_UINT || v > MAX_UINT) {\n      throw evaluationError('numeric_overflow', 'Unsigned integer overflow')\n    }\n    this.#value = v\n  }\n\n  get [Symbol.toStringTag]() {\n    return `value = ${this.#value}`\n  }\n\n  [Symbol.for('nodejs.util.inspect.custom')]() {\n    return `UnsignedInteger { value: ${this.#value} }`\n  }\n}\n\nconst billion = 1_000_000_000\nconst billionBigInt = 1_000_000_000n\n\nconst UNIT_NANOSECONDS = {\n  h: 3_600_000_000_000n,\n  m: 60_000_000_000n,\n  s: billionBigInt,\n  ms: 1_000_000n,\n  us: 1_000n,\n  µs: 1_000n,\n  ns: 1n\n}\n\nexport class Duration {\n  #seconds\n  #nanos\n\n  constructor(seconds, nanos = 0) {\n    this.#seconds = BigInt(seconds)\n    this.#nanos = nanos\n  }\n\n  get seconds() {\n    return this.#seconds\n  }\n\n  get nanos() {\n    return this.#nanos\n  }\n\n  valueOf() {\n    return Number(this.#seconds) * 1000 + this.#nanos / 1_000_000\n  }\n\n  static fromMilliseconds(ms) {\n    const totalNanos = BigInt(Math.trunc(ms * 1_000_000))\n    const seconds = totalNanos / billionBigInt\n    const nanos = Number(totalNanos % billionBigInt)\n    return new Duration(seconds, nanos)\n  }\n\n  addDuration(other) {\n    const nanos = this.#nanos + other.nanos\n    return new Duration(\n      this.#seconds + other.seconds + BigInt(Math.floor(nanos / billion)),\n      nanos % billion\n    )\n  }\n\n  subtractDuration(other) {\n    const nanos = this.#nanos - other.nanos\n    return new Duration(\n      this.#seconds - other.seconds + BigInt(Math.floor(nanos / billion)),\n      (nanos + billion) % billion\n    )\n  }\n\n  extendTimestamp(ts) {\n    return new Date(\n      ts.getTime() + Number(this.#seconds) * 1000 + Math.floor(this.#nanos / 1_000_000)\n    )\n  }\n\n  subtractTimestamp(ts) {\n    return new Date(\n      ts.getTime() - Number(this.#seconds) * 1000 - Math.floor(this.#nanos / 1_000_000)\n    )\n  }\n\n  toString() {\n    const nanos = this.#nanos\n      ? (this.#nanos / billion)\n          .toLocaleString('en-US', {useGrouping: false, maximumFractionDigits: 9})\n          .slice(1)\n      : ''\n    return `${this.#seconds}${nanos}s`\n  }\n\n  getHours() {\n    return this.#seconds / 3600n\n  }\n\n  getMinutes() {\n    return this.#seconds / 60n\n  }\n\n  getSeconds() {\n    return this.#seconds\n  }\n\n  getMilliseconds() {\n    return this.#seconds * 1000n + BigInt(Math.floor(this.#nanos / 1000000))\n  }\n\n  get [Symbol.toStringTag]() {\n    return 'google.protobuf.Duration'\n  }\n\n  [Symbol.for('nodejs.util.inspect.custom')]() {\n    return `google.protobuf.Duration { seconds: ${this.#seconds}, nanos: ${this.#nanos} }`\n  }\n}\n\nexport function registerFunctions(registry) {\n  const sync = {async: false}\n  const functionOverload = (sig, handler) => registry.registerFunctionOverload(sig, handler, sync)\n  const identity = (v) => v\n\n  functionOverload('dyn(dyn): dyn', identity)\n\n  for (const _t in TYPES) {\n    const type = TYPES[_t]\n    if (!(type instanceof Type)) continue\n    functionOverload(`type(${type.name}): type`, () => type)\n  }\n\n  functionOverload('bool(bool): bool', identity)\n  functionOverload('bool(string): bool', (v) => {\n    switch (v) {\n      case '1':\n      case 't':\n      case 'true':\n      case 'TRUE':\n      case 'True':\n        return true\n      case '0':\n      case 'f':\n      case 'false':\n      case 'FALSE':\n      case 'False':\n        return false\n      default:\n        throw evaluationError(\n          'bool_conversion_error',\n          `bool() conversion error: invalid string value \"${v}\"`\n        )\n    }\n  })\n\n  functionOverload('size(string): int', (v) => BigInt(stringSize(v)))\n  functionOverload('size(bytes): int', (v) => BigInt(v.length))\n  functionOverload('size(list): int', (v) => BigInt(v.length ?? v.size))\n  functionOverload('size(map): int', (v) => BigInt(v instanceof Map ? v.size : objKeys(v).length))\n  functionOverload('string.size(): int', (v) => BigInt(stringSize(v)))\n  functionOverload('bytes.size(): int', (v) => BigInt(v.length))\n  functionOverload('list.size(): int', (v) => BigInt(v.length ?? v.size))\n  functionOverload('map.size(): int', (v) => BigInt(v instanceof Map ? v.size : objKeys(v).length))\n\n  functionOverload('bytes(string): bytes', (v) => ByteOpts.fromString(v))\n  functionOverload('bytes(bytes): bytes', identity)\n\n  functionOverload('double(double): double', identity)\n  functionOverload('double(int): double', (v) => Number(v))\n  functionOverload('double(uint): double', (v) => Number(v))\n  functionOverload('double(string): double', (v) => {\n    if (!v || v !== v.trim())\n      throw evaluationError(\n        'double_conversion_error',\n        'double() type error: cannot convert to double'\n      )\n\n    const s = v.toLowerCase()\n    switch (s) {\n      case 'inf':\n      case '+inf':\n      case 'infinity':\n      case '+infinity':\n        return Number.POSITIVE_INFINITY\n      case '-inf':\n      case '-infinity':\n        return Number.NEGATIVE_INFINITY\n      case 'nan':\n        return Number.NaN\n      default: {\n        const parsed = Number(v)\n        if (!Number.isNaN(parsed)) return parsed\n        throw evaluationError(\n          'double_conversion_error',\n          'double() type error: cannot convert to double'\n        )\n      }\n    }\n  })\n\n  functionOverload('int(int): int', identity)\n  functionOverload('int(double): int', (v) => {\n    if (Number.isFinite(v)) return BigInt(Math.trunc(v))\n    throw evaluationError('numeric_overflow', 'int() type error: integer overflow')\n  })\n\n  functionOverload('int(string): int', (v) => {\n    if (v !== v.trim() || v.length > 20 || v.includes('0x')) {\n      throw evaluationError('int_conversion_error', 'int() type error: cannot convert to int')\n    }\n\n    try {\n      const num = BigInt(v)\n      if (num <= MAX_INT && num >= MIN_INT) return num\n    } catch (_e) {}\n\n    throw evaluationError('int_conversion_error', 'int() type error: cannot convert to int')\n  })\n\n  functionOverload('uint(uint): uint', identity)\n  functionOverload('uint(int): uint', (v) => {\n    try {\n      return new UnsignedInt(v)\n    } catch (e) {\n      throw evaluationError('uint_conversion_error', 'uint() type error: cannot convert to uint')\n    }\n  })\n  functionOverload('uint(double): uint', (v) => {\n    try {\n      return new UnsignedInt(Math.trunc(v))\n    } catch (e) {\n      throw evaluationError('numeric_overflow', 'uint() type error: unsigned integer overflow')\n    }\n  })\n\n  functionOverload('uint(string): uint', (v) => {\n    if (v !== v.trim() || v.length > 20 || v.includes('0x')) {\n      throw evaluationError('uint_conversion_error', 'uint() type error: cannot convert to uint')\n    }\n\n    try {\n      return new UnsignedInt(v)\n    } catch (e) {\n      throw evaluationError('uint_conversion_error', 'uint() type error: cannot convert to uint')\n    }\n  })\n\n  functionOverload('string(string): string', identity)\n  functionOverload('string(bool): string', (v) => `${v}`)\n  functionOverload('string(int): string', (v) => `${v}`)\n  functionOverload('string(uint): string', (v) => `${v}`)\n  functionOverload('string(bytes): string', (v) => ByteOpts.toUtf8(v))\n  functionOverload('string(double): string', (v) => {\n    if (v === Infinity) return '+Inf'\n    if (v === -Infinity) return '-Inf'\n    return `${v}`\n  })\n\n  functionOverload('string.startsWith(string): bool', (a, b) => a.startsWith(b))\n  functionOverload('string.endsWith(string): bool', (a, b) => a.endsWith(b))\n  functionOverload('string.contains(string): bool', (a, b) => a.includes(b))\n  functionOverload('string.lowerAscii(): string', (a) => a.toLowerCase())\n  functionOverload('string.upperAscii(): string', (a) => a.toUpperCase())\n  functionOverload('string.trim(): string', (a) => a.trim())\n\n  functionOverload('string.indexOf(string): int', (string, search) =>\n    BigInt(string.indexOf(search))\n  )\n  functionOverload('string.indexOf(string, int): int', (string, search, fromIndex) => {\n    if (search === '') return fromIndex\n\n    fromIndex = Number(fromIndex)\n    if (fromIndex < 0 || fromIndex >= string.length) {\n      throw evaluationError(\n        'index_out_of_range',\n        'string.indexOf(search, fromIndex): fromIndex out of range'\n      )\n    }\n\n    return BigInt(string.indexOf(search, fromIndex))\n  })\n\n  functionOverload('string.lastIndexOf(string): int', (string, search) =>\n    BigInt(string.lastIndexOf(search))\n  )\n\n  functionOverload('string.lastIndexOf(string, int): int', (string, search, fromIndex) => {\n    if (search === '') return fromIndex\n\n    fromIndex = Number(fromIndex)\n    if (fromIndex < 0 || fromIndex >= string.length) {\n      throw evaluationError(\n        'index_out_of_range',\n        'string.lastIndexOf(search, fromIndex): fromIndex out of range'\n      )\n    }\n\n    return BigInt(string.lastIndexOf(search, fromIndex))\n  })\n\n  functionOverload('string.substring(int): string', (string, start) => {\n    start = Number(start)\n    if (start < 0 || start > string.length) {\n      throw evaluationError(\n        'index_out_of_range',\n        'string.substring(start, end): start index out of range'\n      )\n    }\n\n    return string.substring(start)\n  })\n\n  functionOverload('string.substring(int, int): string', (string, start, end) => {\n    start = Number(start)\n    if (start < 0 || start > string.length) {\n      throw evaluationError(\n        'index_out_of_range',\n        'string.substring(start, end): start index out of range'\n      )\n    }\n\n    end = Number(end)\n    if (end < start || end > string.length) {\n      throw evaluationError(\n        'index_out_of_range',\n        'string.substring(start, end): end index out of range'\n      )\n    }\n\n    return string.substring(start, end)\n  })\n\n  functionOverload('string.matches(string): bool', (a, b) => {\n    try {\n      return new RegExp(b).test(a)\n    } catch (_err) {\n      throw evaluationError('invalid_regular_expression', `Invalid regular expression: ${b}`)\n    }\n  })\n\n  functionOverload('string.split(string): list<string>', (s, sep) => s.split(sep))\n  functionOverload('string.split(string, int): list<string>', (s, sep, l) => {\n    l = Number(l)\n    if (l === 0) return []\n    const parts = s.split(sep)\n    if (l < 0 || parts.length <= l) return parts\n    const limited = parts.slice(0, l - 1)\n    limited.push(parts.slice(l - 1).join(sep))\n    return limited\n  })\n\n  functionOverload('list<string>.join(): string', (v) => {\n    for (let i = 0; i < v.length; i++) {\n      if (typeof v[i] !== 'string') {\n        throw evaluationError(\n          'invalid_list_element_type',\n          'string.join(): list must contain only strings'\n        )\n      }\n    }\n    return v.join('')\n  })\n\n  functionOverload('list<string>.join(string): string', (v, sep) => {\n    for (let i = 0; i < v.length; i++) {\n      if (typeof v[i] !== 'string') {\n        throw evaluationError(\n          'invalid_list_element_type',\n          'string.join(separator): list must contain only strings'\n        )\n      }\n    }\n    return v.join(sep)\n  })\n\n  const textEncoder = new TextEncoder('utf8')\n  const textDecoder = new TextDecoder('utf8')\n  const ByteOpts =\n    typeof Buffer !== 'undefined'\n      ? {\n          byteLength: (v) => Buffer.byteLength(v),\n          fromString: (str) => Buffer.from(str, 'utf8'),\n          toHex: (b) => Buffer.prototype.hexSlice.call(b, 0, b.length),\n          toBase64: (b) => Buffer.prototype.base64Slice.call(b, 0, b.length),\n          toUtf8: (b) => Buffer.prototype.utf8Slice.call(b, 0, b.length),\n          jsonParse: (b) => JSON.parse(b)\n        }\n      : {\n          textEncoder: new TextEncoder('utf8'),\n          byteLength: (v) => textEncoder.encode(v).length,\n          fromString: (str) => textEncoder.encode(str),\n          toHex: Uint8Array.prototype.toHex\n            ? (b) => b.toHex()\n            : (b) => arrayFrom(b, (i) => i.toString(16).padStart(2, '0')).join(''),\n          toBase64: Uint8Array.prototype.toBase64\n            ? (b) => b.toBase64()\n            : (b) => btoa(arrayFrom(b, (i) => String.fromCodePoint(i)).join('')),\n          toUtf8: (b) => textDecoder.decode(b),\n          jsonParse: (b) => JSON.parse(textEncoder.decode(b))\n        }\n\n  functionOverload('bytes.json(): map', ByteOpts.jsonParse)\n  functionOverload('bytes.hex(): string', ByteOpts.toHex)\n  functionOverload('bytes.string(): string', ByteOpts.toUtf8)\n  functionOverload('bytes.base64(): string', ByteOpts.toBase64)\n  functionOverload('bytes.at(int): int', (b, index) => {\n    if (index < 0 || index >= b.length) {\n      throw evaluationError('index_out_of_range', 'Bytes index out of range')\n    }\n    return BigInt(b[index])\n  })\n\n  const TS = 'google.protobuf.Timestamp'\n  const GPD = 'google.protobuf.Duration'\n  const TimestampType = registry.registerType(TS, Date).typeType\n  const DurationType = registry.registerType(GPD, Duration).typeType\n  registry.registerConstant('google', 'map<string, map<string, type>>', {\n    protobuf: {Duration: DurationType, Timestamp: TimestampType}\n  })\n\n  function tzDate(d, timeZone) {\n    return new Date(d.toLocaleString('en-US', {timeZone}))\n  }\n\n  function getDayOfYear(d, tz) {\n    const workingDate = tz\n      ? tzDate(d, tz)\n      : new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate())\n\n    const start = new Date(workingDate.getFullYear(), 0, 0)\n    return BigInt(Math.floor((workingDate - start) / 86_400_000) - 1)\n  }\n\n  functionOverload(`timestamp(string): ${TS}`, (v) => {\n    if (v.length < 20 || v.length > 30) {\n      throw evaluationError('invalid_timestamp', 'timestamp() requires a string in ISO 8601 format')\n    }\n\n    const d = new Date(v)\n    if (d <= 253402300799999 && d >= -62135596800000) return d\n    throw evaluationError('invalid_timestamp', 'timestamp() requires a string in ISO 8601 format')\n  })\n\n  functionOverload(`timestamp(int): ${TS}`, (i) => {\n    i = Number(i) * 1000\n    if (i <= 253402300799999 && i >= -62135596800000) return new Date(i)\n    throw evaluationError(\n      'invalid_timestamp',\n      'timestamp() requires a valid integer unix timestamp'\n    )\n  })\n\n  functionOverload(`${TS}.getDate(): int`, (d) => BigInt(d.getUTCDate()))\n  functionOverload(`${TS}.getDate(string): int`, (d, tz) => BigInt(tzDate(d, tz).getDate()))\n  functionOverload(`${TS}.getDayOfMonth(): int`, (d) => BigInt(d.getUTCDate() - 1))\n  functionOverload(`${TS}.getDayOfMonth(string): int`, (d, tz) =>\n    BigInt(tzDate(d, tz).getDate() - 1)\n  )\n  functionOverload(`${TS}.getDayOfWeek(): int`, (d) => BigInt(d.getUTCDay()))\n  functionOverload(`${TS}.getDayOfWeek(string): int`, (d, tz) => BigInt(tzDate(d, tz).getDay()))\n  functionOverload(`${TS}.getDayOfYear(): int`, getDayOfYear)\n  functionOverload(`${TS}.getDayOfYear(string): int`, getDayOfYear)\n  functionOverload(`${TS}.getFullYear(): int`, (d) => BigInt(d.getUTCFullYear()))\n  functionOverload(`${TS}.getFullYear(string): int`, (d, tz) => BigInt(tzDate(d, tz).getFullYear()))\n  functionOverload(`${TS}.getHours(): int`, (d) => BigInt(d.getUTCHours()))\n  functionOverload(`${TS}.getHours(string): int`, (d, tz) => BigInt(tzDate(d, tz).getHours()))\n  functionOverload(`${TS}.getMilliseconds(): int`, (d) => BigInt(d.getUTCMilliseconds()))\n  functionOverload(`${TS}.getMilliseconds(string): int`, (d) => BigInt(d.getUTCMilliseconds()))\n  functionOverload(`${TS}.getMinutes(): int`, (d) => BigInt(d.getUTCMinutes()))\n  functionOverload(`${TS}.getMinutes(string): int`, (d, tz) => BigInt(tzDate(d, tz).getMinutes()))\n  functionOverload(`${TS}.getMonth(): int`, (d) => BigInt(d.getUTCMonth()))\n  functionOverload(`${TS}.getMonth(string): int`, (d, tz) => BigInt(tzDate(d, tz).getMonth()))\n  functionOverload(`${TS}.getSeconds(): int`, (d) => BigInt(d.getUTCSeconds()))\n  functionOverload(`${TS}.getSeconds(string): int`, (d, tz) => BigInt(tzDate(d, tz).getSeconds()))\n\n  const parseDurationPattern = /(\\d*\\.?\\d*)(ns|us|µs|ms|s|m|h)/\n\n  // parseDuration parses a golang-style duration string.\n  // A duration string is a possibly signed sequence of decimal numbers,\n  // each with optional fraction and a unit suffix,\n  // such as \"300ms\", \"-1.5h\" or \"2h45m\". Valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".\n  // https://pkg.go.dev/time#ParseDuration\n  function parseDuration(/** @type {string} */ string) {\n    if (!string) throw evaluationError('invalid_duration', `Invalid duration string: ''`)\n\n    const isNegative = string[0] === '-'\n    if (string[0] === '-' || string[0] === '+') string = string.slice(1)\n\n    let nanoseconds = BigInt(0)\n    while (true) {\n      const match = parseDurationPattern.exec(string)\n      if (!match) throw evaluationError('invalid_duration', `Invalid duration string: ${string}`)\n\n      if (match.index !== 0)\n        throw evaluationError('invalid_duration', `Invalid duration string: ${string}`)\n      string = string.slice(match[0].length)\n\n      const unitNanos = UNIT_NANOSECONDS[match[2]]\n      const [intPart = '0', fracPart = ''] = match[1].split('.')\n      const intVal = BigInt(intPart) * unitNanos\n      const fracNanos = fracPart\n        ? (BigInt(fracPart.slice(0, 13).padEnd(13, '0')) * unitNanos) / 10_000_000_000_000n\n        : 0n\n\n      nanoseconds += intVal + fracNanos\n      if (string === '') break\n    }\n\n    const seconds = nanoseconds >= billionBigInt ? nanoseconds / billionBigInt : 0n\n    const nanos = Number(nanoseconds % billionBigInt)\n\n    if (isNegative) return new Duration(-seconds, -nanos)\n    return new Duration(seconds, nanos)\n  }\n\n  functionOverload(`duration(string): google.protobuf.Duration`, (s) => parseDuration(s))\n  functionOverload(`google.protobuf.Duration.getHours(): int`, (d) => d.getHours())\n  functionOverload(`google.protobuf.Duration.getMinutes(): int`, (d) => d.getMinutes())\n  functionOverload(`google.protobuf.Duration.getSeconds(): int`, (d) => d.getSeconds())\n  functionOverload(`google.protobuf.Duration.getMilliseconds(): int`, (d) => d.getMilliseconds())\n  registerOptional(registry)\n}\n\nfunction stringSize(str) {\n  let count = 0\n  for (const c of str) count++ // eslint-disable-line no-unused-vars\n  return count\n}\n","import {EvaluationError, evaluationError} from './errors.js'\nimport {UnsignedInt} from './functions.js'\nimport {Optional, OPTIONAL_NONE, toggleOptionalTypes} from './optional.js'\nimport {isAsync, hasOwn, objFreeze, objKeys, objEntries, RESERVED} from './globals.js'\n\nexport class Type {\n  #name\n  constructor(name) {\n    this.#name = name\n    objFreeze(this)\n  }\n\n  get name() {\n    return this.#name\n  }\n\n  get [Symbol.toStringTag]() {\n    return `Type<${this.#name}>`\n  }\n\n  toString() {\n    return `Type<${this.#name}>`\n  }\n}\n\nexport const TYPES = {\n  string: new Type('string'),\n  bool: new Type('bool'),\n  int: new Type('int'),\n  uint: new Type('uint'),\n  double: new Type('double'),\n  map: new Type('map'),\n  list: new Type('list'),\n  bytes: new Type('bytes'),\n  null_type: new Type('null'),\n  type: new Type('type')\n}\n\n// not exposed to cel expression\nconst optionalType = new Type('optional')\n\n// prettier-ignore\nconst valueTypeMatchers = {\n  dyn (v, ev) {\n    // prettier-ignore\n    switch (typeof v) {\n      case 'string': case 'bigint': case 'number': case 'boolean': return true\n      case 'object':\n        switch (v ? v.constructor : v) {\n          case null: case undefined: case Object: case Map: case Array: case Set: return true\n          default:\n            if (ev.objectTypesByConstructor.get(v.constructor)) return true\n        }\n    }\n    return !!ev.debugType(v)\n  },\n  string (v) { return typeof v === 'string' },\n  int (v) { return typeof v === 'bigint' },\n  double (v) { return typeof v === 'number' },\n  bool (v) { return typeof v === 'boolean' },\n  null (v) { return v === null },\n  bytes (v) { return v instanceof Uint8Array },\n  uint (v) { return v instanceof UnsignedInt },\n  type (v) { return v instanceof Type },\n  list (v) {\n    switch (v?.constructor) {\n      case Array: case Set: return true\n      default: return false\n    }\n  },\n  map (v) {\n    switch (typeof v === 'object' && v ? v.constructor : null) {\n      case undefined: case Object: case Map: return true\n      default: return false\n    }\n  },\n  optional (v) { return v instanceof Optional },\n  message (v, ev) { return this === ev.debugType(v) }\n}\n\nvalueTypeMatchers.param = valueTypeMatchers.dyn\n\nexport class TypeDeclaration {\n  #matchesCache = new WeakMap()\n  constructor({kind, type, name, keyType, valueType}) {\n    this.kind = kind\n    this.type = type\n    this.name = name\n    this.keyType = keyType\n    this.valueType = valueType\n\n    this.unwrappedType = kind === 'dyn' && valueType ? valueType.unwrappedType : this\n    this.wrappedType = kind === 'dyn' ? this : _createDynType(this.unwrappedType)\n\n    this.hasDynType =\n      this.kind === 'dyn' || this.valueType?.hasDynType || this.keyType?.hasDynType || false\n\n    this.hasPlaceholderType =\n      this.kind === 'param' ||\n      this.keyType?.hasPlaceholderType ||\n      this.valueType?.hasPlaceholderType ||\n      false\n\n    if (kind === 'list') this.fieldLazy = this.#getListField\n    else if (kind === 'map') this.fieldLazy = this.#getMapField\n    else if (kind === 'message') this.fieldLazy = this.#getMessageField\n    else if (kind === 'optional') this.fieldLazy = this.#getOptionalField\n\n    this.matchesValueType = valueTypeMatchers[name] || valueTypeMatchers[kind]\n    objFreeze(this)\n  }\n\n  isDynOrBool() {\n    return this.type === 'bool' || this.kind === 'dyn'\n  }\n\n  isEmpty() {\n    return this.valueType && this.valueType.kind === 'param'\n  }\n\n  unify(r, t2) {\n    const t1 = this\n    if (t1 === t2 || t1.kind === 'dyn' || t2.kind === 'param') return t1\n    if (t2.kind === 'dyn' || t1.kind === 'param') return t2\n    if (t1.kind !== t2.kind) return null\n    if (!(t1.hasPlaceholderType || t2.hasPlaceholderType || t1.hasDynType || t2.hasDynType))\n      return null\n\n    const valueType = t1.valueType.unify(r, t2.valueType)\n    if (!valueType) return null\n    switch (t1.kind) {\n      case 'optional':\n        return r.getOptionalType(valueType)\n      case 'list':\n        return r.getListType(valueType)\n      case 'map':\n        const keyType = t1.keyType.unify(r, t2.keyType)\n        return keyType ? r.getMapType(keyType, valueType) : null\n    }\n  }\n\n  templated(r, bind) {\n    if (!this.hasPlaceholderType) return this\n\n    switch (this.kind) {\n      case 'dyn':\n        return this.valueType.templated(r, bind)\n      case 'param':\n        return bind?.get(this.name) || this\n      case 'map':\n        return r.getMapType(this.keyType.templated(r, bind), this.valueType.templated(r, bind))\n      case 'list':\n        return r.getListType(this.valueType.templated(r, bind))\n      case 'optional':\n        return r.getOptionalType(this.valueType.templated(r, bind))\n      default:\n        return this\n    }\n  }\n\n  toString() {\n    return this.name\n  }\n\n  #getOptionalField(obj, key, ast, ev) {\n    obj = obj instanceof Optional ? obj.orValue() : obj\n    if (obj === undefined) return OPTIONAL_NONE\n\n    const type = ev.debugType(obj)\n    try {\n      return Optional.of(type.fieldLazy(obj, key, ast, ev))\n    } catch (e) {\n      if (e instanceof EvaluationError) return OPTIONAL_NONE\n      throw e\n    }\n  }\n\n  #getMessageField(obj, key, ast, ev) {\n    const message = obj ? ev.objectTypesByConstructor.get(obj.constructor) : undefined\n    if (!message) return\n\n    const type = message.fields ? message.fields[key] : dynType\n    if (!type) return undefined\n\n    const value = obj instanceof Map ? obj.get(key) : obj[key]\n    if (value === undefined) return\n    if (type.matchesValueType(value, ev)) return value\n    throw evaluationError(\n      'field_type_mismatch',\n      `Field '${key}' is not of type '${type}', got '${ev.debugType(value)}'`,\n      ast\n    )\n  }\n\n  #getMapField(obj, key, ast, ev) {\n    // eslint-disable-next-line no-nested-ternary\n    const value = obj instanceof Map ? obj.get(key) : obj && hasOwn(obj, key) ? obj[key] : undefined\n    if (value === undefined) return\n    if (this.valueType.matchesValueType(value, ev)) return value\n\n    throw evaluationError(\n      'field_type_mismatch',\n      `Field '${key}' is not of type '${this.valueType}', got '${ev.debugType(value)}'`,\n      ast\n    )\n  }\n\n  #getListElementAtIndex(list, pos) {\n    switch (list?.constructor) {\n      case Array:\n        return list[pos]\n      case Set: {\n        let i = 0\n        for (const item of list) {\n          if (i++ !== pos) continue\n          return item\n        }\n      }\n    }\n  }\n\n  #getListField(obj, key, ast, ev) {\n    if (typeof key === 'bigint') key = Number(key)\n    else if (typeof key !== 'number') return\n\n    const value = this.#getListElementAtIndex(obj, key)\n    if (value === undefined) {\n      if (!obj) return\n      throw evaluationError(\n        'index_out_of_bounds',\n        `No such key: index out of bounds, index ${key} ${\n          key < 0 ? '< 0' : `>= size ${obj.length || obj.size}`\n        }`,\n        ast\n      )\n    }\n\n    if (this.valueType.matchesValueType(value, ev)) return value\n\n    throw evaluationError(\n      'list_item_type_mismatch',\n      `List item with index '${key}' is not of type '${this.valueType}', got '${ev.debugType(value)}'`,\n      ast\n    )\n  }\n\n  fieldLazy() {}\n\n  field(obj, key, ast, ev) {\n    const v = this.fieldLazy(obj, key, ast, ev)\n    if (v !== undefined) return v\n    throw evaluationError('no_such_key', `No such key: ${key}`, ast)\n  }\n\n  matchesBoth(other) {\n    return this.matches(other) && other.matches(this)\n  }\n\n  matches(o) {\n    const s = this.unwrappedType\n    o = o.unwrappedType\n    if (s === o || s.kind === 'dyn' || o.kind === 'dyn' || o.kind === 'param') return true\n    return this.#matchesCache.get(o) ?? this.#matchesCache.set(o, this.#matches(s, o)).get(o)\n  }\n\n  #matches(s, o) {\n    switch (s.kind) {\n      case 'dyn':\n      case 'param':\n        return true\n      case 'list':\n        return o.kind === 'list' && s.valueType.matches(o.valueType)\n      case 'map':\n        return o.kind === 'map' && s.keyType.matches(o.keyType) && s.valueType.matches(o.valueType)\n      case 'optional':\n        return o.kind === 'optional' && s.valueType.matches(o.valueType)\n      default:\n        return s.name === o.name\n    }\n  }\n}\n\nconst macroEvaluateErr = `have a .callAst property or .evaluate(checker, macro, ctx) method.`\nconst macroTypeCheckErr = `have a .callAst property or .typeCheck(checker, macro, ctx) method.`\nfunction wrapMacroExpander(name, handler) {\n  const p = `Macro '${name}' must`\n  return function macroExpander(opts) {\n    const macro = handler(opts)\n    if (!macro || typeof macro !== 'object') throw new Error(`${p} return an object.`)\n    if (macro.callAst) return macro\n    if (!macro.evaluate) throw new Error(`${p} ${macroEvaluateErr}`)\n    if (!macro.typeCheck) throw new Error(`${p} ${macroTypeCheckErr}`)\n    return macro\n  }\n}\n\nexport class VariableDeclaration {\n  constructor(name, type, description, value) {\n    this.name = name\n    this.type = type\n    this.description = description ?? null\n    this.constant = value !== undefined\n    this.value = value\n    objFreeze(this)\n  }\n}\n\nexport class FunctionDeclaration {\n  constructor({name, receiverType, returnType, handler, description, params, async}) {\n    if (typeof name !== 'string') throw new Error('name must be a string')\n    if (typeof handler !== 'function') throw new Error('handler must be a function')\n\n    this.name = name\n    this.async = isAsync(handler, async)\n    this.receiverType = receiverType ?? null\n    this.returnType = returnType\n    this.description = description ?? null\n    this.params = params\n    this.argTypes = params.map((p) => p.type)\n    this.macro = this.argTypes.includes(astType)\n\n    const receiverString = receiverType ? `${receiverType}.` : ''\n    this.signature = `${receiverString}${name}(${this.argTypes.join(', ')}): ${returnType}`\n    this.handler = this.macro ? wrapMacroExpander(this.signature, handler) : handler\n    this.partitionKey = `${receiverType ? 'rcall' : 'call'}:${name}:${params.length}`\n\n    this.hasPlaceholderType =\n      this.returnType.hasPlaceholderType ||\n      this.receiverType?.hasPlaceholderType ||\n      this.argTypes.some((t) => t.hasPlaceholderType) ||\n      false\n\n    objFreeze(this)\n  }\n\n  matchesArgs(argTypes) {\n    return argTypes.length === this.argTypes.length &&\n      this.argTypes.every((t, i) => t.matches(argTypes[i]))\n      ? this\n      : null\n  }\n}\n\nexport class OperatorDeclaration {\n  constructor({op, leftType, rightType, handler, returnType, async}) {\n    this.operator = op\n    this.leftType = leftType\n    this.rightType = rightType || null\n    this.handler = handler\n    this.async = isAsync(handler, async)\n    this.returnType = returnType\n\n    if (rightType) this.signature = `${leftType} ${op} ${rightType}: ${returnType}`\n    else this.signature = `${op}${leftType}: ${returnType}`\n\n    this.hasPlaceholderType =\n      this.leftType.hasPlaceholderType || this.rightType?.hasPlaceholderType || false\n\n    objFreeze(this)\n  }\n\n  equals(other) {\n    return (\n      this.operator === other.operator &&\n      this.leftType === other.leftType &&\n      this.rightType === other.rightType\n    )\n  }\n}\n\nfunction _createListType(valueType) {\n  return new TypeDeclaration({\n    kind: 'list',\n    name: `list<${valueType}>`,\n    type: 'list',\n    valueType\n  })\n}\n\nfunction _createPrimitiveType(name) {\n  return new TypeDeclaration({kind: 'primitive', name, type: name})\n}\n\nfunction _createMessageType(name) {\n  return new TypeDeclaration({kind: 'message', name, type: name})\n}\n\nfunction _createDynType(valueType) {\n  const name = valueType ? `dyn<${valueType}>` : 'dyn'\n  return new TypeDeclaration({kind: 'dyn', name, type: name, valueType})\n}\n\nfunction _createOptionalType(valueType) {\n  const name = `optional<${valueType}>`\n  return new TypeDeclaration({kind: 'optional', name, type: 'optional', valueType})\n}\n\nfunction _createMapType(keyType, valueType) {\n  return new TypeDeclaration({\n    kind: 'map',\n    name: `map<${keyType}, ${valueType}>`,\n    type: 'map',\n    keyType: keyType,\n    valueType: valueType\n  })\n}\n\nfunction _createPlaceholderType(name) {\n  return new TypeDeclaration({kind: 'param', name, type: name})\n}\n\n// Global immutable cache for built-in primitive types (shared across all registries)\nconst dynType = _createDynType()\nconst astType = _createPrimitiveType('ast')\nconst listType = _createListType(dynType)\nconst mapType = _createMapType(dynType, dynType)\nexport const celTypes = {\n  string: _createPrimitiveType('string'),\n  bool: _createPrimitiveType('bool'),\n  int: _createPrimitiveType('int'),\n  uint: _createPrimitiveType('uint'),\n  double: _createPrimitiveType('double'),\n  bytes: _createPrimitiveType('bytes'),\n  dyn: dynType,\n  null: _createPrimitiveType('null'),\n  type: _createPrimitiveType('type'),\n  optional: _createOptionalType(dynType),\n  list: listType,\n  'list<dyn>': listType,\n  map: mapType,\n  'map<dyn, dyn>': mapType\n}\n\nfor (const t of [celTypes.string, celTypes.double, celTypes.int]) {\n  const list = _createListType(t)\n  const map = _createMapType(celTypes.string, t)\n  celTypes[list.name] = list\n  celTypes[map.name] = map\n}\n\nObject.freeze(celTypes)\n\nclass Candidates {\n  returnType = null\n  async = false\n  macro = false\n  #matchCache = null\n  #checkCache = null\n  /** @type {Array<FunctionDeclaration>|Array<OperatorDeclaration>} */\n  declarations = []\n  constructor(registry) {\n    this.registry = registry\n  }\n\n  [Symbol.iterator]() {\n    return this.declarations[Symbol.iterator]()\n  }\n\n  add(decl) {\n    this.returnType =\n      (this.returnType || decl.returnType).unify(this.registry, decl.returnType) || dynType\n\n    if (decl.macro) this.macro = decl\n    if (decl.async && !this.async) this.async = true\n    this.declarations.push(decl)\n    this.#matchCache?.clear()\n    this.#checkCache?.clear()\n  }\n\n  findFunction(argTypes, receiverType = null) {\n    for (let i = 0; i < this.declarations.length; i++) {\n      const match = this.#matchesFunction(this.declarations[i], argTypes, receiverType)\n      if (match) return match\n    }\n    return null\n  }\n\n  findUnaryOverload(left) {\n    const cached = (this.#matchCache ??= new Map()).get(left)\n    if (cached !== undefined) return cached\n\n    let value = false\n    for (const decl of this.declarations) {\n      if (decl.leftType !== left) continue\n      value = decl\n      break\n    }\n\n    this.#matchCache.set(left, value)\n    return value\n  }\n\n  findBinaryOverload(left, right) {\n    if (left.kind === 'dyn' && left.valueType) right = right.wrappedType\n    else if (right.kind === 'dyn' && right.valueType) left = left.wrappedType\n    return (\n      (this.#matchCache ??= new Map()).get(left)?.get(right) ??\n      this.#cacheBinary(this.#matchCache, left, right, this.#findBinaryUncached(left, right))\n    )\n  }\n\n  checkBinaryOverload(left, right) {\n    return (\n      (this.#checkCache ??= new Map()).get(left)?.get(right) ??\n      this.#cacheBinary(this.#checkCache, left, right, this.#checkBinaryUncached(left, right))\n    )\n  }\n\n  #cacheBinary(c, l, r, v) {\n    return ((c.get(l) || c.set(l, new Map()).get(l)).set(r, v), v)\n  }\n\n  #findBinaryUncached(left, right) {\n    const ops = this.#findBinaryOverloads(left, right)\n    if (ops.length === 0) return false\n    if (ops.length === 1) return ops[0]\n    throw new Error(`Operator overload '${ops[0].signature}' overlaps with '${ops[1].signature}'.`)\n  }\n\n  #checkBinaryUncached(left, right) {\n    const ops = this.#findBinaryOverloads(left, right)\n    if (ops.length === 0) return false\n    let rt = ops[0].returnType\n    for (let i = 1; i < ops.length; i++) rt = rt.unify(this.registry, ops[i].returnType) || dynType\n    return rt\n  }\n\n  #findBinaryOverloads(leftType, rightType) {\n    const nonexactMatches = []\n    for (const decl of this.declarations) {\n      if (decl.leftType === leftType && decl.rightType === rightType) return [decl]\n      const secondary = this.#matchBinaryOverload(decl, leftType, rightType)\n      if (secondary) nonexactMatches.push(secondary)\n    }\n\n    if (nonexactMatches.length === 0) {\n      const op = this.declarations[0]?.operator\n      if ((op === '==' || op === '!=') && leftType.kind === 'dyn') {\n        return fallbackDynEqualityMatchers[op]\n      }\n    }\n\n    return nonexactMatches\n  }\n\n  #matchBinaryOverload(decl, actualLeft, actualRight) {\n    const bindings = decl.hasPlaceholderType ? new Map() : null\n    const leftType = this.#matchTypeWithPlaceholders(decl.leftType, actualLeft, bindings)\n    if (!leftType) return\n    const rightType = this.#matchTypeWithPlaceholders(decl.rightType, actualRight, bindings)\n    if (!rightType) return\n\n    if (\n      (decl.operator === '==' || decl.operator === '!=') &&\n      decl.leftType.kind === 'dyn' &&\n      decl.leftType.valueType &&\n      actualLeft.kind !== 'dyn' &&\n      actualRight.kind !== 'dyn'\n    )\n      return false\n\n    return decl.hasPlaceholderType\n      ? {\n          async: decl.async,\n          signature: decl.signature,\n          handler: decl.handler,\n          leftType,\n          rightType,\n          returnType: decl.returnType.templated(this.registry, bindings)\n        }\n      : decl\n  }\n\n  #matchesFunction(fn, argTypes, receiverType) {\n    if (fn.hasPlaceholderType) return this.#matchWithPlaceholders(fn, argTypes, receiverType)\n    if (receiverType && fn.receiverType && !receiverType.matches(fn.receiverType)) return\n    return fn.matchesArgs(argTypes)\n  }\n\n  #matchWithPlaceholders(fn, argTypes, receiverType) {\n    const bindings = new Map()\n    if (receiverType && fn.receiverType) {\n      if (!this.#matchTypeWithPlaceholders(fn.receiverType, receiverType, bindings)) {\n        return null\n      }\n    }\n\n    for (let i = 0; i < argTypes.length; i++) {\n      if (!this.#matchTypeWithPlaceholders(fn.argTypes[i], argTypes[i], bindings)) {\n        return null\n      }\n    }\n\n    return {\n      async: fn.async,\n      handler: fn.handler,\n      signature: fn.signature,\n      returnType: fn.returnType.templated(this.registry, bindings)\n    }\n  }\n\n  #matchTypeWithPlaceholders(declared, actual, bindings) {\n    if (!declared.hasPlaceholderType) return actual.matches(declared) ? actual : null\n\n    const treatAsDyn = actual.kind === 'dyn'\n    if (!this.#collectPlaceholderBindings(declared, actual, bindings, treatAsDyn)) return null\n    if (treatAsDyn) return actual\n    return actual.matches(declared.templated(this.registry, bindings)) ? actual : null\n  }\n\n  #collectPlaceholderBindings(dec, act, bind, fromDyn = false) {\n    if (!dec.hasPlaceholderType) return true\n    if (!act) return false\n\n    const asDyn = fromDyn || act.kind === 'dyn'\n    act = act.unwrappedType\n\n    switch (dec.kind) {\n      case 'param': {\n        const type = asDyn ? dynType : act\n        const existing = bind.get(dec.name)\n        if (!existing) return bind.set(dec.name, type) && true\n        return existing.kind === 'dyn' || type.kind === 'dyn' ? true : existing.matchesBoth(type)\n      }\n      case 'list': {\n        if (act.name === 'dyn') act = dec\n        if (act.kind !== 'list') return false\n        return this.#collectPlaceholderBindings(dec.valueType, act.valueType, bind, asDyn)\n      }\n      case 'map': {\n        if (act.name === 'dyn') act = dec\n        if (act.kind !== 'map') return false\n        return (\n          this.#collectPlaceholderBindings(dec.keyType, act.keyType, bind, asDyn) &&\n          this.#collectPlaceholderBindings(dec.valueType, act.valueType, bind, asDyn)\n        )\n      }\n      case 'optional': {\n        if (act.name === 'dyn') act = dec\n        if (act.kind !== 'optional') return false\n        return this.#collectPlaceholderBindings(dec.valueType, act.valueType, bind, asDyn)\n      }\n    }\n    return true\n  }\n}\n\n// Helper function for splitting map type parameters\nfunction splitByComma(str) {\n  const parts = []\n  let current = ''\n  let depth = 0\n\n  for (const char of str) {\n    if (char === '<') depth++\n    else if (char === '>') depth--\n    else if (char === ',' && depth === 0) {\n      parts.push(current.trim())\n      current = ''\n      continue\n    }\n    current += char\n  }\n\n  if (current) parts.push(current.trim())\n  return parts\n}\n\nconst objTypesDecls = [\n  [UnsignedInt, 'uint', TYPES.uint, celTypes.uint],\n  [Type, 'type', TYPES.type, celTypes.type],\n  [Optional, 'optional', optionalType, celTypes.optional],\n  [Uint8Array, 'bytes', TYPES.bytes, celTypes.bytes],\n  ...(typeof Buffer !== 'undefined' ? [[Buffer, 'bytes', TYPES.bytes, celTypes.bytes]] : [])\n].map(([ctor, name, typeType, type]) => Object.freeze({name, typeType, type, ctor}))\n\nconst objTypes = objTypesDecls.map((t) => [t.name, t])\nconst objTypesCtor = objTypesDecls.map((t) => [t.ctor, t])\n\nconst invalidVar = (postfix) => new Error(`Invalid variable declaration: ${postfix}`)\nconst invalidType = (postfix) => new Error(`Invalid type declaration: ${postfix}`)\n\nconst fallbackDynEqualityMatchers = {\n  '==': [{handler: (a, b) => a === b, returnType: celTypes.bool}],\n  '!=': [{handler: (a, b) => a !== b, returnType: celTypes.bool}]\n}\n\nexport class Registry {\n  #parent = null\n  #typeDeclarations\n\n  #ownsVariables = true\n  #operators = null\n  #functions = null\n  #operatorsByOp = null\n  #functionsByKey = null\n  #listTypes = null\n  #mapTypes = null\n  #optionalTypes = null\n  #others = null\n\n  #locked = false\n\n  constructor(opts = {}) {\n    this.enableOptionalTypes = opts.enableOptionalTypes ?? false\n    this.unlistedVariablesAreDyn = opts.unlistedVariablesAreDyn ?? false\n\n    const parent = opts.parent instanceof Registry ? opts.parent : null\n    if (parent) {\n      this.#parent = parent\n\n      let opParent = parent\n      while (opParent && !opParent.#operators) opParent = opParent.#parent\n\n      let fnParent = parent\n      while (fnParent && !fnParent.#functions) fnParent = fnParent.#parent\n\n      this.#operatorsByOp = parent.#operatorsByOp\n      this.#functionsByKey = parent.#functionsByKey\n      this.#others = {operators: opParent.#operators, functions: fnParent.#functions}\n\n      this.objectTypes = new Map(parent.objectTypes)\n      this.objectTypesByConstructor = new Map(parent.objectTypesByConstructor)\n      this.variables = parent.variables\n      this.#ownsVariables = false\n      this.#typeDeclarations = parent.#typeDeclarations\n      this.#listTypes = parent.#listTypes\n      this.#mapTypes = parent.#mapTypes\n      this.#optionalTypes = parent.#optionalTypes\n\n      if (\n        this.enableOptionalTypes !== parent.enableOptionalTypes ||\n        this.unlistedVariablesAreDyn !== parent.unlistedVariablesAreDyn\n      ) {\n        toggleOptionalTypes(this, this.enableOptionalTypes)\n      }\n    } else {\n      this.#operators = []\n      this.#functions = []\n      this.objectTypes = new Map(objTypes)\n      this.objectTypesByConstructor = new Map(objTypesCtor)\n      this.#typeDeclarations = new Map(objEntries(celTypes))\n      this.#listTypes = new Map()\n      this.#mapTypes = new Map()\n      this.#optionalTypes = new Map()\n      this.variables = new Map()\n      this.variables.dyn = this.unlistedVariablesAreDyn\n      for (const n in TYPES) this.registerConstant(n, 'type', TYPES[n])\n    }\n  }\n\n  #ensureOwnVariables() {\n    if (this.#ownsVariables) return\n    this.variables = new Map(this.variables)\n    this.variables.dyn = this.unlistedVariablesAreDyn\n    this.#ownsVariables = true\n  }\n\n  // Used by toggleOptionalTypes in optional.js to clear a variable before re-registering it\n  deleteVariable(name) {\n    this.#ensureOwnVariables()\n    this.variables.delete(name)\n  }\n\n  #pushOperator(decl) {\n    if (!this.#operators) this.#operatorsByOp = null\n    this.operatorCandidates(decl.operator).add(decl)\n    this.#operators.push(decl)\n  }\n\n  #pushFunction(decl) {\n    if (!this.#functions) this.#functionsByKey = null\n    this.#functionCandidates(decl.partitionKey).add(decl)\n    this.#functions.push(decl)\n  }\n\n  #ensureCandiate(c, key) {\n    return c.get(key) || c.set(key, new Candidates(this)).get(key)\n  }\n\n  #getOperators() {\n    if (this.#operators) return this.#operators\n    return (this.#operators = [...this.#others.operators])\n  }\n\n  #getFunctions() {\n    if (this.#functions) return this.#functions\n    return (this.#functions = [...this.#others.functions])\n  }\n\n  operatorCandidates(op) {\n    if (this.#operatorsByOp) return this.#ensureCandiate(this.#operatorsByOp, op)\n    const c = (this.#operatorsByOp = new Map())\n    for (const decl of this.#getOperators()) this.#ensureCandiate(c, decl.operator).add(decl)\n    return this.#ensureCandiate(c, op)\n  }\n\n  functionCandidates(rec, name, argLen) {\n    return this.#functionCandidates(`${rec ? 'rcall' : 'call'}:${name}:${argLen}`)\n  }\n\n  #functionCandidates(key) {\n    if (this.#functionsByKey) return this.#ensureCandiate(this.#functionsByKey, key)\n    const c = (this.#functionsByKey = new Map())\n    for (const decl of this.#getFunctions()) this.#ensureCandiate(c, decl.partitionKey).add(decl)\n    return this.#ensureCandiate(c, key)\n  }\n\n  registerVariable(name, type, opts) {\n    if (this.#locked) throw new Error('Cannot modify frozen registry')\n    let description = opts?.description\n    let value\n    if (\n      typeof name === 'string' &&\n      typeof type === 'object' &&\n      !(type instanceof TypeDeclaration)\n    ) {\n      description = type.description\n      value = type.value\n      if (type.schema) type = this.registerType({name: `$${name}`, schema: type.schema}).type\n      else type = type.type\n    } else if (typeof name === 'object') {\n      if (name.schema) type = this.registerType({name: `$${name.name}`, schema: name.schema}).type\n      else type = name.type\n      description = name.description\n      value = name.value\n      name = name.name\n    }\n\n    if (typeof name !== 'string' || !name) throw invalidVar(`name must be a string`)\n    if (RESERVED.has(name)) throw invalidVar(`'${name}' is a reserved name`)\n    if (this.variables.get(name) !== undefined) throw invalidVar(`'${name}' is already registered`)\n\n    if (typeof type === 'string') type = this.getType(type)\n    else if (!(type instanceof TypeDeclaration)) throw invalidVar(`type is required`)\n\n    this.#ensureOwnVariables()\n    this.variables.set(name, new VariableDeclaration(name, type, description, value))\n    return this\n  }\n\n  #registerSchemaAsType(name, schema) {\n    const fields = Object.create(null)\n    for (const key of objKeys(schema)) {\n      const def = schema[key]\n      if (typeof def === 'object' && def) {\n        fields[key] = this.registerType({name: `${name}.${key}`, schema: def}).type.name\n      } else if (typeof def === 'string') {\n        fields[key] = def\n      } else {\n        throw new Error(`Invalid field definition for '${name}.${key}'`)\n      }\n    }\n    return fields\n  }\n\n  registerConstant(name, type, value) {\n    if (typeof name === 'object') this.registerVariable(name)\n    else this.registerVariable({name, type, value})\n    return this\n  }\n\n  getType(typename) {\n    return this.#parseTypeString(typename, true)\n  }\n\n  getListType(type) {\n    return (\n      this.#listTypes.get(type) ||\n      this.#listTypes.set(type, this.#parseTypeString(`list<${type}>`, true)).get(type)\n    )\n  }\n\n  getMapType(a, b) {\n    return (\n      this.#mapTypes.get(a)?.get(b) ||\n      (this.#mapTypes.get(a) || this.#mapTypes.set(a, new Map()).get(a))\n        .set(b, this.#parseTypeString(`map<${a}, ${b}>`, true))\n        .get(b)\n    )\n  }\n\n  getOptionalType(type) {\n    return (\n      this.#optionalTypes.get(type) ||\n      this.#optionalTypes.set(type, this.#parseTypeString(`optional<${type}>`, true)).get(type)\n    )\n  }\n\n  assertType(typename, type, signature) {\n    try {\n      return this.#parseTypeString(typename, true)\n    } catch (e) {\n      e.message = `Invalid ${type} '${e.unknownType || typename}' in '${signature}'`\n      throw e\n    }\n  }\n\n  getFunctionType(typename) {\n    if (typename === 'ast') return astType\n    const t = this.#parseTypeString(typename, true)\n    if (t.kind === 'dyn' && t.valueType) throw new Error(`type '${t.name}' is not supported`)\n    return t\n  }\n\n  registerType(name, _d) {\n    if (this.#locked) throw new Error('Cannot modify frozen registry')\n    if (typeof name === 'object') ((_d = name), (name = _d.fullName || _d.name || _d.ctor?.name))\n    if (typeof name === 'string' && name[0] === '.') name = name.slice(1)\n    if (typeof name !== 'string' || name.length < 2 || RESERVED.has(name)) {\n      throw invalidType(`name '${name}' is not valid`)\n    }\n\n    if (this.objectTypes.has(name)) throw invalidType(`type '${name}' already registered`)\n\n    const type = this.#parseTypeString(name, false)\n    if (type.kind !== 'message') throw invalidType(`type '${name}' is not valid`)\n\n    const decl = {\n      name,\n      typeType: new Type(name),\n      type,\n      ctor: typeof _d === 'function' ? _d : _d?.ctor,\n      convert: typeof _d === 'function' ? undefined : _d?.convert,\n      fields:\n        typeof _d?.schema === 'object'\n          ? this.#normalizeFields(name, this.#registerSchemaAsType(name, _d.schema))\n          : this.#normalizeFields(name, typeof _d === 'function' ? undefined : _d?.fields)\n    }\n\n    if (typeof decl.ctor !== 'function') {\n      if (!decl.fields) throw invalidType(`type '${name}' requires a constructor or fields`)\n      Object.assign(decl, this.#createDefaultConvert(name, decl.fields))\n    }\n\n    this.objectTypes.set(name, Object.freeze(decl))\n    this.objectTypesByConstructor.set(decl.ctor, decl)\n    this.registerFunctionOverload(`type(${name}): type`, () => decl.typeType, {async: false})\n    return decl\n  }\n\n  /** @returns {TypeDeclaration} */\n  #parseTypeString(typeStr, requireKnownTypes = true) {\n    let match = this.#typeDeclarations.get(typeStr)\n    if (match) return match\n\n    if (typeof typeStr !== 'string' || !typeStr.length) {\n      throw new Error(`Invalid type: must be a string`)\n    }\n\n    match = typeStr.match(/^[A-Z]$/)\n    if (match) return this.#createDeclaration(_createPlaceholderType, typeStr, typeStr)\n\n    match = typeStr.match(/^(dyn|list|map|optional)<(.+)>$/)\n    if (!match) {\n      if (requireKnownTypes) {\n        const err = new Error(`Unknown type: ${typeStr}`)\n        err.unknownType = typeStr\n        throw err\n      }\n      return this.#createDeclaration(_createMessageType, typeStr, typeStr)\n    }\n\n    const kind = match[1]\n    const inner = match[2].trim()\n    switch (kind) {\n      case 'dyn': {\n        const type = this.#parseTypeString(inner, requireKnownTypes).wrappedType\n        this.#typeDeclarations.set(type.name, type)\n        return type\n      }\n      case 'list': {\n        const vType = this.#parseTypeString(inner, requireKnownTypes)\n        return this.#createDeclaration(_createListType, `list<${vType}>`, vType)\n      }\n      case 'map': {\n        const parts = splitByComma(inner)\n        if (parts.length !== 2) throw new Error(`Invalid map type: ${typeStr}`)\n        const kType = this.#parseTypeString(parts[0], requireKnownTypes)\n        const vType = this.#parseTypeString(parts[1], requireKnownTypes)\n        return this.#createDeclaration(_createMapType, `map<${kType}, ${vType}>`, kType, vType)\n      }\n      case 'optional': {\n        const vType = this.#parseTypeString(inner, requireKnownTypes)\n        return this.#createDeclaration(_createOptionalType, `optional<${vType}>`, vType)\n      }\n    }\n  }\n\n  #createDeclaration(creator, key, ...args) {\n    return (\n      this.#typeDeclarations.get(key) || this.#typeDeclarations.set(key, creator(...args)).get(key)\n    )\n  }\n\n  findMacro(name, hasReceiver, argLen) {\n    return this.functionCandidates(hasReceiver, name, argLen).macro\n  }\n\n  findUnaryOverload(op, left) {\n    return this.operatorCandidates(op).findUnaryOverload(left)\n  }\n\n  findBinaryOverload(op, left, right) {\n    return this.operatorCandidates(op).findBinaryOverload(left, right)\n  }\n\n  #toCelFieldType(field) {\n    if (typeof field === 'string') return {type: field}\n    if (field.id) return protobufjsFieldToCelType(field)\n    return field\n  }\n\n  #toCelFieldDeclaration(typename, fields, k, requireKnownTypes = false) {\n    try {\n      const field = this.#toCelFieldType(fields[k])\n      if (typeof field?.type !== 'string') throw new Error(`unsupported declaration`)\n      return this.#parseTypeString(field.type, requireKnownTypes)\n    } catch (e) {\n      e.message =\n        `Field '${k}' in type '${typename}' has unsupported declaration: ` +\n        `${JSON.stringify(fields[k])}`\n      throw e\n    }\n  }\n\n  #normalizeFields(typename, fields) {\n    if (!fields) return\n    const all = Object.create(null)\n    for (const k of objKeys(fields)) all[k] = this.#toCelFieldDeclaration(typename, fields, k)\n    return all\n  }\n\n  #createDefaultConvert(name, fields) {\n    const keys = objKeys(fields)\n\n    const conversions = Object.create(null)\n    for (const k of keys) {\n      const type = fields[k]\n      const decl = type.kind === 'message' && this.objectTypes.get(type.name)\n      if (decl === false) conversions[k] = false\n      else conversions[k] = decl.convert ? decl : false\n    }\n\n    const Ctor = {\n      [name]: class extends Map {\n        #raw\n        constructor(v) {\n          super()\n          this.#raw = v\n        }\n\n        [Symbol.iterator]() {\n          if (this.size !== keys.length) for (const k of keys) this.get(k)\n          return super[Symbol.iterator]()\n        }\n\n        get(field) {\n          let v = super.get(field)\n          if (v !== undefined || this.has(field)) return v\n\n          const dec = conversions[field]\n          if (dec === undefined) return\n\n          v = this.#raw instanceof Map ? this.#raw.get(field) : this.#raw?.[field]\n          if (dec && v && typeof v === 'object') {\n            switch (v.constructor) {\n              case undefined:\n              case Object:\n              case Map:\n                v = dec.convert(v)\n            }\n          }\n          return (super.set(field, v), v)\n        }\n      }\n    }[name]\n\n    return {\n      ctor: Ctor,\n      convert(v) {\n        if (!v) return\n        if (v.constructor === Ctor) return v\n        return new Ctor(v)\n      }\n    }\n  }\n\n  clone(opts) {\n    this.#locked = true\n    return new Registry({\n      parent: this,\n      unlistedVariablesAreDyn: opts.unlistedVariablesAreDyn,\n      enableOptionalTypes: opts.enableOptionalTypes\n    })\n  }\n\n  getDefinitions() {\n    const variables = []\n    const functions = []\n    for (const [, varDecl] of this.variables) {\n      if (!varDecl) continue\n      variables.push({\n        name: varDecl.name,\n        description: varDecl.description || null,\n        type: varDecl.type.name\n      })\n    }\n\n    for (const decl of this.#getFunctions()) {\n      functions.push({\n        signature: decl.signature,\n        name: decl.name,\n        description: decl.description,\n        receiverType: decl.receiverType ? decl.receiverType.name : null,\n        returnType: decl.returnType.name,\n        params: decl.params.map((p) => ({\n          name: p.name,\n          type: p.type.name,\n          description: p.description\n        }))\n      })\n    }\n\n    return {variables, functions}\n  }\n\n  #parseSignature(signature) {\n    if (typeof signature !== 'string') throw new Error('Invalid signature: must be a string')\n    const match = signature.match(/^(?:([a-zA-Z0-9.<>]+)\\.)?(\\w+)\\(([^)]*)\\):(.*)$/)\n    if (!match) throw new Error(`Invalid signature: ${signature}`)\n    const returnType = match[4].trim()\n    if (!returnType) throw new Error(`Invalid signature: ${signature}`)\n    return {\n      receiverType: match[1] || null,\n      name: match[2],\n      argTypes: splitByComma(match[3]),\n      returnType\n    }\n  }\n\n  /**\n   * @param {FunctionDeclaration} a\n   * @param {FunctionDeclaration} b\n   */\n  #functionSignatureOverlaps(a, b) {\n    if (a.name !== b.name) return false\n    if (a.argTypes.length !== b.argTypes.length) return false\n    if ((a.receiverType || b.receiverType) && (!a.receiverType || !b.receiverType)) return false\n\n    const isDifferentReceiver =\n      a.receiverType !== b.receiverType && a.receiverType !== dynType && b.receiverType !== dynType\n\n    return (\n      !isDifferentReceiver &&\n      (b.macro ||\n        a.macro ||\n        b.argTypes.every((t, i) => {\n          const o = a.argTypes[i]\n          return t === o || t === dynType || o === dynType\n        }))\n    )\n  }\n\n  /** @param {FunctionDeclaration} newDec */\n  #checkOverlappingSignatures(newDec) {\n    for (const decl of this.#functionCandidates(newDec.partitionKey)) {\n      if (!this.#functionSignatureOverlaps(decl, newDec)) continue\n      throw new Error(\n        `Function signature '${newDec.signature}' overlaps with existing overload '${decl.signature}'.`\n      )\n    }\n  }\n\n  #normalizeParam(i, aType, param) {\n    if (!param) return {type: this.getFunctionType(aType), name: `arg${i}`, description: null}\n\n    const type = param.type || aType\n    if (!type) throw new Error(`params[${i}].type is required`)\n    if (aType && type !== aType) throw new Error(`params[${i}].type not equal to signature type`)\n    return {\n      name: param.name || `arg${i}`,\n      type: this.getFunctionType(type),\n      description: param.description ?? null\n    }\n  }\n\n  registerFunctionOverload(s, handler, opts) {\n    if (this.#locked) throw new Error('Cannot modify frozen registry')\n    if (typeof s === 'object') opts = s\n    else if (typeof handler === 'object') opts = handler\n    else if (!opts) opts = {}\n\n    const sig = typeof s === 'string' ? s : (opts.signature ?? undefined)\n    const parsed = sig !== undefined ? this.#parseSignature(sig) : undefined\n    const name = parsed?.name || opts.name\n    const receiverType = parsed?.receiverType || opts.receiverType\n    const argTypes = parsed?.argTypes\n    const returnType = parsed?.returnType || opts.returnType\n    const params = opts.params\n    handler = typeof handler === 'function' ? handler : opts.handler\n\n    let dec\n    try {\n      if (!name) throw new Error(`signature or name are required`)\n      if (!returnType) throw new Error(`must have a returnType`)\n\n      if (params) {\n        if (argTypes && params.length !== argTypes.length) {\n          throw new Error(`mismatched length in params and args in signature`)\n        }\n      } else if (!argTypes) throw new Error(`signature or params are required`)\n\n      dec = new FunctionDeclaration({\n        name,\n        async: opts?.async,\n        receiverType: receiverType ? this.getType(receiverType) : null,\n        returnType: this.getType(returnType),\n        handler,\n        description: opts.description,\n        params: (argTypes || params).map((_, i) =>\n          this.#normalizeParam(i, argTypes?.[i], params?.[i])\n        )\n      })\n    } catch (e) {\n      if (typeof sig === 'string') e.message = `Invalid function declaration '${sig}': ${e.message}`\n      else if (name) e.message = `Invalid function declaration '${name}': ${e.message}`\n      else e.message = `Invalid function declaration: ${e.message}`\n      throw e\n    }\n\n    this.#checkOverlappingSignatures(dec)\n    this.#pushFunction(dec)\n  }\n\n  registerOperatorOverload(string, handler, opts) {\n    // Parse with optional return type: \"Vector + Vector: Vector\" or \"Vector + Vector\"\n    const unaryParts = string.match(/^([-!])([\\w.<>]+)(?::\\s*([\\w.<>]+))?$/)\n    if (unaryParts) {\n      const [, op, operandType, returnType] = unaryParts\n      return this.unaryOverload(op, operandType, handler, returnType, opts?.async)\n    }\n\n    const parts = string.match(\n      /^([\\w.<>]+) ([-+*%/]|==|!=|<|<=|>|>=|in) ([\\w.<>]+)(?::\\s*([\\w.<>]+))?$/\n    )\n    if (!parts) throw new Error(`Operator overload invalid: ${string}`)\n    const [, leftType, op, rightType, returnType] = parts\n    return this.binaryOverload(leftType, op, rightType, handler, returnType)\n  }\n\n  unaryOverload(op, typeStr, handler, returnTypeStr, async) {\n    if (this.#locked) throw new Error('Cannot modify frozen registry')\n    const leftType = this.assertType(typeStr, 'type', `${op}${typeStr}`)\n    const returnType = this.assertType(\n      returnTypeStr || typeStr,\n      'return type',\n      `${op}${typeStr}: ${returnTypeStr || typeStr}`\n    )\n\n    const d = new OperatorDeclaration({op: `${op}_`, leftType, returnType, handler, async})\n    this.#pushOperator(this.#assertOverload(d))\n  }\n\n  #hasOverload(d) {\n    for (const o of this.operatorCandidates(d.operator)) if (d.equals(o)) return true\n    return false\n  }\n\n  #assertOverload(decl) {\n    if (!this.#hasOverload(decl)) return decl\n    throw new Error(`Operator overload already registered: ${decl.signature}`)\n  }\n\n  binaryOverload(leftTypeStr, op, rightTypeStr, handler, returnTypeStr, async) {\n    if (this.#locked) throw new Error('Cannot modify frozen registry')\n    returnTypeStr ??= isRelational.has(op) ? 'bool' : leftTypeStr\n\n    const sig = `${leftTypeStr} ${op} ${rightTypeStr}: ${returnTypeStr}`\n    let leftType = this.assertType(leftTypeStr, 'left type', sig)\n    let rightType = this.assertType(rightTypeStr, 'right type', sig)\n    const returnType = this.assertType(returnTypeStr, 'return type', sig)\n\n    // Register both types as wrapped with dyn<> if one of them is wrapped\n    if (leftType.kind === 'dyn' && leftType.valueType) rightType = rightType.wrappedType\n    else if (rightType.kind === 'dyn' && rightType.valueType) leftType = leftType.wrappedType\n\n    if (isRelational.has(op) && returnType.type !== 'bool') {\n      throw new Error(`Comparison operator '${op}' must return 'bool', got '${returnType.type}'`)\n    }\n\n    const dec = new OperatorDeclaration({op, leftType, rightType, returnType, handler, async})\n    if (dec.hasPlaceholderType && !(rightType.hasPlaceholderType && leftType.hasPlaceholderType)) {\n      throw new Error(\n        `Operator overload with placeholders must use them in both left and right types: ${sig}`\n      )\n    }\n\n    this.#assertOverload(dec)\n    if (op === '==') {\n      const declarations = [\n        new OperatorDeclaration({\n          op: '!=',\n          leftType,\n          rightType,\n          handler(a, b, ast, ev) {\n            return !handler(a, b, ast, ev)\n          },\n          returnType,\n          async\n        })\n      ]\n\n      if (leftType !== rightType) {\n        declarations.push(\n          new OperatorDeclaration({\n            op: '==',\n            leftType: rightType,\n            rightType: leftType,\n            handler(a, b, ast, ev) {\n              return handler(b, a, ast, ev)\n            },\n            returnType,\n            async\n          }),\n          new OperatorDeclaration({\n            op: '!=',\n            leftType: rightType,\n            rightType: leftType,\n            handler(a, b, ast, ev) {\n              return !handler(b, a, ast, ev)\n            },\n            returnType,\n            async\n          })\n        )\n      }\n\n      for (const decl of declarations) this.#assertOverload(decl)\n      for (const decl of declarations) this.#pushOperator(decl)\n    }\n\n    this.#pushOperator(dec)\n  }\n}\n\nconst isRelational = new Set(['<', '<=', '>', '>=', '==', '!=', 'in'])\n\nexport function createRegistry(opts) {\n  return new Registry(opts)\n}\n\nexport class RootContext {\n  #vars\n  #contextObj\n  #contextMap\n  #convertCache\n  constructor(registry, context) {\n    this.#vars = registry.variables\n    if (context === undefined || context === null) return\n    if (typeof context !== 'object') {\n      throw evaluationError('invalid_context', 'Context must be an object')\n    }\n    if (context instanceof Map) this.#contextMap = context\n    else this.#contextObj = context\n  }\n\n  getValue(key) {\n    return (\n      this.#convertCache?.get(key) ||\n      (this.#contextObj ? this.#contextObj[key] : this.#contextMap?.get(key))\n    )\n  }\n\n  getVariable(name) {\n    return (\n      this.#vars.get(name) ??\n      (this.#vars.dyn && !RESERVED.has(name) ? new VariableDeclaration(name, dynType) : undefined)\n    )\n  }\n\n  getCheckedValue(ev, ast) {\n    const v = this.getValue(ast.args)\n    if (v === undefined) throw ev.createError('unknown_variable', `Unknown variable: ${ast.args}`, ast)\n    if (ast.checkedType.matchesValueType(v, ev)) return v\n\n    const type = ast.checkedType\n    const valueType = ev.debugType(v)\n    // Convert plain objects to typed instances when a convert function is registered\n    if (type.kind === 'message' && valueType.kind === 'map') {\n      const c = ev.objectTypes.get(type.name)?.convert?.(v)\n      if (c) return ((this.#convertCache ??= new Map()).set(ast.args, c), c)\n    }\n\n    throw ev.createError(\n      'variable_type_mismatch',\n      `Variable '${ast.args}' is not of type '${type}', got '${valueType}'`,\n      ast\n    )\n  }\n\n  forkWithVariable(iterVar, iterType) {\n    return new OverlayContext(this, iterVar, iterType)\n  }\n}\n\nclass OverlayContext {\n  #parent\n  accuType\n  accuValue\n  iterValue\n  constructor(parent, iterVar, iterType) {\n    this.#parent = parent\n    this.iterVar = iterVar\n    this.iterType = iterType\n  }\n\n  forkWithVariable(iterVar, iterType) {\n    return new OverlayContext(this, iterVar, iterType)\n  }\n\n  reuse(parent) {\n    if (!this.async) return ((this.#parent = parent), this)\n    const ctx = new OverlayContext(parent, this.iterVar, this.iterType)\n    ctx.accuType = this.accuType\n    return ctx\n  }\n\n  setIterValue(v, ev) {\n    if (this.iterType.matchesValueType(v, ev)) return ((this.iterValue = v), this)\n\n    const type = this.iterType\n    const valueType = ev.debugType(v)\n    // Convert plain objects to typed instances when a convert function is registered\n    if (type.kind === 'message' && valueType.kind === 'map') {\n      const c = ev.objectTypes.get(type.name)?.convert?.(v)\n      if (c) return ((this.iterValue = c), this)\n    }\n\n    throw ev.createError(\n      'variable_type_mismatch',\n      `Variable '${this.iterVar}' is not of type '${type}', got '${valueType}'`\n    )\n  }\n\n  setAccuType(type) {\n    return ((this.accuType = type), this)\n  }\n\n  setAccuValue(v) {\n    return ((this.accuValue = v), this)\n  }\n\n  getValue(key) {\n    return this.iterVar === key ? this.iterValue : this.#parent.getValue(key)\n  }\n\n  getCheckedValue(ev, ast) {\n    if (this.iterVar === ast.args) return this.iterValue\n    return this.#parent.getCheckedValue(ev, ast)\n  }\n\n  getVariable(name) {\n    if (this.iterVar === name) return new VariableDeclaration(name, this.iterType)\n    return this.#parent.getVariable(name)\n  }\n}\n\n/**\n * Extract CEL field declarations from a protobufjs message type.\n * Maps protobuf types to CEL types.\n * @param {protobuf.Type} messageType - The protobufjs message type\n * @returns {Object} Field declarations in CEL format {fieldName: 'celType'}\n */\nfunction protobufjsFieldToCelType(field) {\n  let fieldType\n  if (field.map) {\n    const keyType = protobufjsTypeToCelType(field.keyType, field.resolvedKeyType)\n    const valueType = protobufjsTypeToCelType(field.type, field.resolvedType)\n    fieldType = `map<${keyType}, ${valueType}>`\n  } else {\n    fieldType = protobufjsTypeToCelType(field.type, field.resolvedType)\n  }\n  return {type: field.repeated ? `list<${fieldType}>` : fieldType}\n}\n\n/**\n * Map protobuf type names to CEL type names.\n * @param {string} protoType - The protobuf type name\n * @param {protobuf.Type|null} resolvedType - The resolved type for message/enum fields\n * @returns {string} The CEL type name\n */\nfunction protobufjsTypeToCelType(protoType, resolvedType) {\n  switch (protoType) {\n    case 'string':\n      return 'string'\n    case 'bytes':\n      return 'bytes'\n    case 'bool':\n      return 'bool'\n    // protobufjs uses JavaScript numbers for all numeric types\n    case 'double':\n    case 'float':\n    case 'int32':\n    case 'int64':\n    case 'sint32':\n    case 'sint64':\n    case 'sfixed32':\n    case 'sfixed64':\n    case 'uint32':\n    case 'uint64':\n    case 'fixed32':\n    case 'fixed64':\n      return 'double'\n    default:\n      switch (resolvedType?.constructor.name) {\n        case 'Type':\n          return resolvedType.fullName.slice(1)\n        case 'Enum':\n          return 'int'\n      }\n\n      if (protoType?.includes('.')) return protoType\n\n      // Unknown type, treat as dyn\n      return 'dyn'\n  }\n}\n","import {celTypes} from './registry.js'\nimport {objKeys, isArray, hasOwn} from './globals.js'\nimport {attachErrorAst} from './errors.js'\nconst dynType = celTypes.dyn\n\nexport class Base {\n  dynType = celTypes.dyn\n  optionalType = celTypes.optional\n  stringType = celTypes.string\n  intType = celTypes.int\n  doubleType = celTypes.double\n  boolType = celTypes.bool\n  nullType = celTypes.null\n  listType = celTypes.list\n  mapType = celTypes.map\n\n  constructor(opts) {\n    this.opts = opts.opts\n    this.registry = opts.registry\n    this.objectTypes = this.registry.objectTypes\n    this.objectTypesByConstructor = this.registry.objectTypesByConstructor\n  }\n\n  /**\n   * Get a TypeDeclaration instance for a type name\n   * @param {string} typeName - The type name (e.g., 'string', 'int', 'dyn')\n   * @returns {TypeDeclaration} The type declaration instance\n   */\n  getType(typeName) {\n    return this.registry.getType(typeName)\n  }\n\n  debugType(v) {\n    switch (typeof v) {\n      case 'string':\n        return this.stringType\n      case 'bigint':\n        return this.intType\n      case 'number':\n        return this.doubleType\n      case 'boolean':\n        return this.boolType\n      case 'object':\n        if (v === null) return this.nullType\n        switch (v.constructor) {\n          case undefined:\n          case Object:\n          case Map:\n            return this.mapType\n          case Array:\n          case Set:\n            return this.listType\n          default:\n            return (\n              this.objectTypesByConstructor.get(v.constructor)?.type ||\n              unsupportedType(this, v.constructor?.name || typeof v)\n            )\n        }\n      default:\n        unsupportedType(this, typeof v)\n    }\n  }\n}\n\nfunction unsupportedType(self, type) {\n  throw self.createError('unsupported_type', `Unsupported type: ${type}`)\n}\n\nconst maybeAsyncArray = (a) => (Array.isArray(a) ? a.some((n) => n.maybeAsync) : false)\n\nfunction maybeAsync(l, r, h) {\n  if (r === true || (r && (r?.maybeAsync || maybeAsyncArray(r)))) return maybeAsyncBoth(h)\n  if (l === true || (l && (l?.maybeAsync || maybeAsyncArray(l)))) return maybeAsyncFirst(h)\n  return h\n}\n\nfunction maybeAsyncBoth(handler) {\n  return (handler.__asyncBoth ??= function handle(a, b, c, d) {\n    if (!(a instanceof Promise || b instanceof Promise)) return handler(a, b, c, d)\n    if (!(b instanceof Promise)) return a.then((_a) => handler(_a, b, c, d))\n    if (!(a instanceof Promise)) return b.then((_b) => handler(a, _b, c, d))\n    return Promise.all([a, b]).then((p) => handler(p[0], p[1], c, d))\n  })\n}\n\nfunction maybeAsyncFirst(handler) {\n  return (handler.__asyncFirst ??= function handle(a, b, c, d) {\n    if (a instanceof Promise) return a.then((_a) => handler(_a, b, c, d))\n    return handler(a, b, c, d)\n  })\n}\n\nfunction checkAccessNode(chk, ast, ctx) {\n  ast.right = ast.args[1]\n  const leftType = chk.check((ast.left = ast.args[0]), ctx)\n  if (ast.op === '[]') chk.check(ast.right, ctx)\n\n  ast.handle = maybeAsync(\n    ast.left,\n    ast.op === '[]' ? ast.right : false,\n    leftType !== dynType ? fieldAccessStatic : fieldAccess\n  )\n\n  if (leftType.kind !== 'optional') return chk.checkAccessOnType(ast, ctx, leftType)\n  return chk.registry.getOptionalType(chk.checkAccessOnType(ast, ctx, leftType.valueType, true))\n}\n\nfunction checkOptionalAccessNode(chk, ast, ctx) {\n  ast.right = ast.args[1]\n  const leftType = chk.check((ast.left = ast.args[0]), ctx)\n  if (ast.op === '[?]') chk.check(ast.right, ctx)\n\n  ast.handle = maybeAsync(ast.left, ast.op === '[?]' ? ast.right : false, oFieldAccess)\n\n  const actualType = leftType.kind === 'optional' ? leftType.valueType : leftType\n  return chk.registry.getOptionalType(chk.checkAccessOnType(ast, ctx, actualType, true))\n}\n\nconst HOMOGENEOUS_PREFIX = {\n  heterogeneous_list_element: 'List elements must have the same type,',\n  heterogeneous_map_key: 'Map key uses wrong type,',\n  heterogeneous_map_value: 'Map value uses wrong type,'\n}\n\nfunction checkElementHomogenous(chk, ctx, expected, el, code) {\n  const type = chk.check(el, ctx)\n  if (type === expected || expected.isEmpty()) return type\n  if (type.isEmpty()) return expected\n  throw chk.createError(\n    code,\n    `${HOMOGENEOUS_PREFIX[code]} expected type '${chk.formatType(expected)}' but found '${chk.formatType(type)}'`,\n    el\n  )\n}\n\nfunction checkElement(chk, ctx, expected, el) {\n  return expected.unify(chk.registry, chk.check(el, ctx)) || dynType\n}\n\nfunction ternaryConditionError(ev, value, node) {\n  const type = ev.debugRuntimeType(value)\n  return ev.createError(\n    'invalid_condition_type',\n    `${node.meta.label || 'Ternary condition must be bool'}, got '${type}'`,\n    node\n  )\n}\n\nfunction handleTernary(c, ev, ast, ctx) {\n  if (c === true) return ev.run(ast.left, ctx)\n  if (c === false) return ev.run(ast.right, ctx)\n  throw ternaryConditionError(ev, c, ast.condition)\n}\n\nfunction logicalOperandError(ev, value, node) {\n  const type = ev.debugRuntimeType(value)\n  return ev.createError(\n    'invalid_logical_operand',\n    `Logical operator requires bool operands, got '${type}'`,\n    node\n  )\n}\n\nfunction logicalValueOrErr(ev, v, node) {\n  if (v instanceof Error) return v\n  return logicalOperandError(ev, v, node)\n}\n\nfunction _logicalOp(exp, ev, ast, left, right) {\n  if (right === exp) return exp\n  if (right === !exp) {\n    if (left === right) return right\n    throw logicalValueOrErr(ev, left, ast.left)\n  }\n  if (right instanceof Promise) return right.then((r) => _logicalOpAsync(exp, ev, ast, left, r))\n  throw logicalOperandError(ev, right, ast.left)\n}\n\nfunction _logicalOpAsync(exp, ev, ast, left, right) {\n  if (right === exp) return exp\n  if (typeof right !== 'boolean') throw logicalOperandError(ev, right, ast.right)\n  if (typeof left !== 'boolean') throw logicalValueOrErr(ev, left, ast.left)\n  return !exp\n}\n\nfunction checkLogicalOp(chk, ast, ctx) {\n  const leftType = chk.check((ast.left = ast.args[0]), ctx)\n  const rightType = chk.check((ast.right = ast.args[1]), ctx)\n\n  if (!leftType.isDynOrBool()) {\n    throw chk.createError(\n      'invalid_logical_operand',\n      `Logical operator requires bool operands, got '${chk.formatType(leftType)}'`,\n      ast\n    )\n  }\n  if (!rightType.isDynOrBool()) {\n    throw chk.createError(\n      'invalid_logical_operand',\n      `Logical operator requires bool operands, got '${chk.formatType(rightType)}'`,\n      ast\n    )\n  }\n\n  return chk.boolType\n}\n\nfunction checkUnary(chk, ast, ctx) {\n  const op = ast.op\n  const right = chk.check(ast.args, ctx)\n  ast.candidates = chk.registry.operatorCandidates(op)\n\n  if (right.kind === 'dyn') {\n    ast.handle = maybeAsync(ast.args, false, handleUnary)\n    return ast.candidates.returnType\n  }\n\n  const overload = ast.candidates.findUnaryOverload(right)\n  if (!overload) {\n    throw chk.createError(\n      'no_such_overload',\n      `no such overload: ${op[0]}${chk.formatType(right)}`,\n      ast\n    )\n  }\n\n  ast.handle = maybeAsync(ast.args, false, overload.handler)\n  return overload.returnType\n}\n\nfunction handleUnary(left, ast, ev) {\n  const leftType = ev.debugRuntimeType(left, ast.args.checkedType)\n  const overload = ast.candidates.findUnaryOverload(leftType)\n  if (overload) return overload.handler(left)\n  throw ev.createError('no_such_overload', `no such overload: ${ast.op[0]}${leftType}`, ast)\n}\n\nfunction evaluateUnary(ev, ast, ctx) {\n  return ast.handle(ev.run(ast.args, ctx), ast, ev)\n}\n\nfunction checkBinary(chk, ast, ctx) {\n  const op = ast.op\n  const left = chk.check((ast.left = ast.args[0]), ctx)\n  const right = chk.check((ast.right = ast.args[1]), ctx)\n  ast.candidates = chk.registry.operatorCandidates(op)\n\n  const overload =\n    left.hasDynType || right.hasDynType ? undefined : ast.candidates.findBinaryOverload(left, right)\n\n  ast.handle = maybeAsync(ast.left, ast.right, overload?.handler || handleBinary)\n  if (overload) return overload.returnType\n\n  const type = ast.candidates.checkBinaryOverload(left, right)\n  if (!left.hasDynType) ast.leftStaticType = left\n  if (!right.hasDynType) ast.rightStaticType = right\n  if (type) return type\n\n  throw chk.createError(\n    'no_such_overload',\n    `no such overload: ${chk.formatType(left)} ${op} ${chk.formatType(right)}`,\n    ast\n  )\n}\n\nfunction evaluateBinary(ev, ast, ctx) {\n  return ast.handle(ev.run(ast.left, ctx), ev.run(ast.right, ctx), ast, ev)\n}\n\nfunction evaluateBinaryFirst(ev, ast, ctx) {\n  return ast.handle(ev.run(ast.left, ctx), ast.right, ast, ev)\n}\n\nfunction handleBinary(left, right, ast, ev) {\n  const leftType = ast.leftStaticType || ev.debugTypeDeep(left).wrappedType\n  const rightType = ast.rightStaticType || ev.debugTypeDeep(right).wrappedType\n  const overload = ast.candidates.findBinaryOverload(leftType, rightType)\n  if (overload) return overload.handler(left, right, ast, ev)\n  throw ev.createError(\n    'no_such_overload',\n    `no such overload: ${leftType} ${ast.op} ${rightType}`,\n    ast\n  )\n}\n\nfunction callFunctionHandler(handler, ev, args, ast) {\n  try {\n    const result = handler.apply(ev, args)\n    if (result instanceof Promise) {\n      return result.catch((error) => {\n        throw attachErrorAst(error, ast)\n      })\n    }\n    return result\n  } catch (error) {\n    throw attachErrorAst(error, ast)\n  }\n}\n\nfunction callFn(args, ast, ev) {\n  const argAst = ast.args[1]\n  const types = ast.argTypes\n  let i = argAst.length\n  while (i--) types[i] = ev.debugRuntimeType(args[i], argAst[i].checkedType)\n\n  const decl = ast.candidates.findFunction(types)\n  if (decl) return callFunctionHandler(decl.handler, ev, args, ast)\n  throw ev.createError(\n    'no_matching_overload',\n    `found no matching overload for '${ast.args[0]}(${types\n      .map((t) => t.unwrappedType)\n      .join(', ')})'`,\n    ast\n  )\n}\n\nfunction callRecFn(args, ev, ast) {\n  const [, receiverAst, argAst] = ast.args\n  const types = ast.argTypes\n  for (let i = 0; i < types.length; i++)\n    types[i] = ev.debugRuntimeType(args[i + 1], argAst[i].checkedType)\n\n  const receiverType = ev.debugRuntimeType(args[0], receiverAst.checkedType)\n  const decl = ast.candidates.findFunction(types, receiverType)\n  if (decl) return callFunctionHandler(decl.handler, ev, args, ast)\n\n  throw ev.createError(\n    'no_matching_overload',\n    `found no matching overload for '${receiverType.type}.${ast.args[0]}(${types\n      .map((t) => t.unwrappedType)\n      .join(', ')})'`,\n    ast\n  )\n}\n\nfunction resolveAstArray(ev, astArray, ctx, i = astArray.length) {\n  if (i === 0) return []\n\n  let async\n  const results = new Array(i)\n  while (i--) if ((results[i] = ev.run(astArray[i], ctx)) instanceof Promise) async ??= true\n  return async ? Promise.all(results) : results\n}\n\nfunction safeFromEntries(entries) {\n  const obj = {}\n  for (let i = 0; i < entries.length; i++) {\n    const [k, v] = entries[i]\n    if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue\n    obj[k] = v\n  }\n  return obj\n}\n\nfunction comprehensionElementType(chk, iterable, ctx) {\n  const iterType = chk.check(iterable, ctx)\n  if (iterType.kind === 'dyn') return iterType\n  if (iterType.kind === 'list') return iterType.valueType\n  if (iterType.kind === 'map') return iterType.keyType\n  throw chk.createError(\n    'invalid_comprehension_range',\n    `Expression of type '${chk.formatType(\n      iterType\n    )}' cannot be range of a comprehension (must be list, map, or dynamic).`,\n    iterable\n  )\n}\n\nfunction toIterable(ev, args, coll) {\n  if (coll instanceof Set) return [...coll]\n  if (coll instanceof Map) return [...coll.keys()]\n  if (coll && typeof coll === 'object') return objKeys(coll)\n  throw ev.createError(\n    'invalid_comprehension_range',\n    `Expression of type '${ev.debugType(\n      coll\n    )}' cannot be range of a comprehension (must be list, map, or dynamic).`,\n    args.iterable\n  )\n}\n\nfunction runQualifier(items, args, ev, ctx) {\n  if (!isArray(items)) items = toIterable(ev, args, items)\n  const accu = ev.run(args.init, (ctx = args.iterCtx.reuse(ctx)))\n  ctx.accuValue = accu\n  if (ctx === args.iterCtx) return iterateQuantifier(ev, ctx, args, items, accu, 0)\n  return continueQuantifier(ev, ctx, args, items, accu, 0)\n}\n\nfunction runComprehension(items, args, ev, ctx) {\n  if (!isArray(items)) items = toIterable(ev, args, items)\n  const accu = ev.run(args.init, (ctx = args.iterCtx.reuse(ctx)))\n  ctx.accuValue = accu\n  if (ctx === args.iterCtx) return iterateLoop(ev, ctx, args, items, accu, 0)\n  return continueLoop(ev, ctx, args, items, accu, 0)\n}\n\nfunction iterateLoop(ev, ctx, args, items, accu, i) {\n  const condition = args.condition\n  const step = args.step\n  const len = items.length\n  while (i < len) {\n    if (condition && !condition(accu)) break\n    accu = ev.run(step, ctx.setIterValue(items[i++], ev))\n    if (accu instanceof Promise) return continueLoop(ev, ctx, args, items, accu, i)\n  }\n  return args.result(accu)\n}\n\nasync function continueLoop(ev, ctx, args, items, accu, i) {\n  if (ctx === args.iterCtx) ctx.async = true\n  const condition = args.condition\n  const step = args.step\n  const len = items.length\n  accu = await accu\n  while (i < len) {\n    if (condition && !condition(accu)) return args.result(accu)\n    accu = ev.run(step, ctx.setIterValue(items[i++], ev))\n    if (accu instanceof Promise) accu = await accu\n  }\n  return args.result(accu)\n}\n\nfunction iterateQuantifier(ev, ctx, args, items, accu, i, error, stp) {\n  const condition = args.condition\n  const step = args.step\n  const len = items.length\n  while (i < len) {\n    if (!condition(accu)) return args.result(accu)\n    stp = ev.tryEval(step, ctx.setIterValue(items[i++], ev))\n    if (stp instanceof Promise) return continueQuantifier(ev, ctx, args, items, accu, i, error, stp)\n    if (stp instanceof Error && (error ??= stp)) continue\n    accu = stp\n  }\n\n  if (error && condition(accu)) throw error\n  return args.result(accu)\n}\n\nasync function continueQuantifier(ev, ctx, args, items, accu, i, error, stp) {\n  if (ctx === args.iterCtx) ctx.async = true\n  const condition = args.condition\n  const step = args.step\n  const len = items.length\n\n  stp = await stp\n  if (stp instanceof Error) error ??= stp\n  else accu = stp\n\n  while (i < len) {\n    if (!condition(accu)) return args.result(accu)\n    stp = ev.tryEval(step, ctx.setIterValue(items[i++], ev))\n    if (stp instanceof Promise) stp = await stp\n    if (stp instanceof Error && (error ??= stp)) continue\n    accu = stp\n  }\n  if (error && condition(accu)) throw error\n  return args.result(accu)\n}\n\nfunction oFieldAccess(left, right, ast, ev) {\n  return ev.optionalType.field(left, right, ast, ev)\n}\n\nfunction fieldAccessStatic(left, right, ast, ev) {\n  return ast.left.checkedType.field(left, right, ast, ev)\n}\n\nconst empty = Object.create(null)\nfunction fieldAccess(left, right, ast, ev) {\n  switch (left?.constructor) {\n    case undefined:\n    case Object: {\n      const v = hasOwn(left || empty, right) ? left[right] : undefined\n      if (v !== undefined) return (ev.debugType(v), v)\n      break\n    }\n    case Map: {\n      const v = left.get(right)\n      if (v !== undefined) return (ev.debugType(v), v)\n      break\n    }\n    case Array:\n    case Set:\n      return ev.listType.field(left, right, ast, ev)\n    default:\n      const t = ev.objectTypesByConstructor.get(left.constructor)\n      if (t) return t.type.field(left, right, ast, ev)\n      else if (typeof left === 'object') unsupportedType(ev, left.constructor.name)\n  }\n  throw ev.createError('no_such_key', `No such key: ${right}`, ast)\n}\n\nconst emptyList = () => []\nconst emptyMap = () => ({})\n\nexport const OPERATORS = {\n  value: {\n    check(chk, ast) {\n      return chk.debugType(ast.args)\n    },\n    evaluate(_ev, ast) {\n      return ast.args\n    }\n  },\n  id: {\n    check(chk, ast, ctx) {\n      const variable = ctx.getVariable(ast.args)\n      if (!variable) throw chk.createError('unknown_variable', `Unknown variable: ${ast.args}`, ast)\n      if (variable.constant) {\n        const alternate = ast.clone(OPERATORS.value, variable.value)\n        ast.setMeta('alternate', alternate)\n        return chk.check(alternate, ctx)\n      }\n      return variable.type\n    },\n    evaluate(ev, ast, ctx) {\n      return ctx.getCheckedValue(ev, ast)\n    }\n  },\n  '.': {\n    alias: 'fieldAccess',\n    check: checkAccessNode,\n    evaluate: evaluateBinaryFirst\n  },\n  '.?': {\n    alias: 'optionalFieldAccess',\n    check: checkOptionalAccessNode,\n    evaluate: evaluateBinaryFirst\n  },\n  '[]': {\n    alias: 'bracketAccess',\n    check: checkAccessNode,\n    evaluate: evaluateBinary\n  },\n  '[?]': {\n    alias: 'optionalBracketAccess',\n    check: checkOptionalAccessNode,\n    evaluate: evaluateBinary\n  },\n  call: {\n    check(chk, ast, ctx) {\n      const [functionName, args] = ast.args\n      const candidates = (ast.candidates = chk.registry.functionCandidates(\n        false,\n        functionName,\n        args.length\n      ))\n\n      const argTypes = (ast.argTypes = args.map((a) => chk.check(a, ctx)))\n      const decl = candidates.findFunction(argTypes)\n\n      if (!decl) {\n        throw chk.createError(\n          'no_matching_overload',\n          `found no matching overload for '${functionName}(${chk.formatTypeList(argTypes)})'`,\n          ast\n        )\n      }\n\n      const handle = argTypes.some((t) => t.hasDynType)\n        ? callFn\n        : (decl.handler.__handle ??= (l, _ast, e) => callFunctionHandler(decl.handler, e, l, _ast))\n\n      ast.handle = maybeAsync(args, false, handle)\n      return decl.returnType\n    },\n    evaluate(ev, ast, ctx) {\n      return ast.handle(resolveAstArray(ev, ast.args[1], ctx), ast, ev)\n    }\n  },\n  rcall: {\n    check(chk, ast, ctx) {\n      const [methodName, receiver, args] = ast.args\n      const receiverType = chk.check(receiver, ctx)\n      const candidates = (ast.candidates = chk.registry.functionCandidates(\n        true,\n        methodName,\n        args.length\n      ))\n\n      const argTypes = (ast.argTypes = args.map((a) => chk.check(a, ctx)))\n      ast.receiverWithArgs = [receiver, ...args]\n      ast.handle = maybeAsync(ast.receiverWithArgs, false, callRecFn)\n\n      if (receiverType.kind === 'dyn' && candidates.returnType) return candidates.returnType\n      const decl = candidates.findFunction(argTypes, receiverType)\n\n      if (!decl) {\n        throw chk.createError(\n          'no_matching_overload',\n          `found no matching overload for '${receiverType.type}.${methodName}(${chk.formatTypeList(\n            argTypes\n          )})'`,\n          ast\n        )\n      }\n\n      if (!receiverType.hasPlaceholderType && !argTypes.some((t) => t.hasDynType)) {\n        const fn = decl.handler\n        const handle = (fn.__handle ??= (a, ev, _ast) => callFunctionHandler(fn, ev, a, _ast))\n        ast.handle = maybeAsync(ast.receiverWithArgs, false, handle)\n      }\n\n      return decl.returnType\n    },\n    evaluate(ev, ast, ctx) {\n      return ast.handle(resolveAstArray(ev, ast.receiverWithArgs, ctx), ev, ast)\n    }\n  },\n  list: {\n    check(chk, ast, ctx) {\n      const arr = ast.args\n      const arrLen = arr.length\n      if (arrLen === 0) return ast.setMeta('evaluate', emptyList) && chk.getType('list<T>')\n\n      let valueType = chk.check(arr[0], ctx)\n      const check = chk.opts.homogeneousAggregateLiterals ? checkElementHomogenous : checkElement\n\n      for (let i = 1; i < arrLen; i++)\n        valueType = check(chk, ctx, valueType, arr[i], 'heterogeneous_list_element')\n      return chk.registry.getListType(valueType)\n    },\n    evaluate(ev, ast, ctx) {\n      return resolveAstArray(ev, ast.args, ctx)\n    }\n  },\n  map: {\n    check(chk, ast, ctx) {\n      const arr = ast.args\n      const arrLen = arr.length\n      if (arrLen === 0) return ast.setMeta('evaluate', emptyMap) && chk.getType('map<K, V>')\n\n      const check = chk.opts.homogeneousAggregateLiterals ? checkElementHomogenous : checkElement\n      let keyType = chk.check(arr[0][0], ctx)\n      let valueType = chk.check(arr[0][1], ctx)\n      for (let i = 1; i < arrLen; i++) {\n        const e = arr[i]\n        keyType = check(chk, ctx, keyType, e[0], 'heterogeneous_map_key')\n        valueType = check(chk, ctx, valueType, e[1], 'heterogeneous_map_value')\n      }\n      return chk.registry.getMapType(keyType, valueType)\n    },\n    evaluate(ev, ast, ctx) {\n      const astEntries = ast.args\n      const len = astEntries.length\n      const results = new Array(len)\n      let async\n      for (let i = 0; i < len; i++) {\n        const e = astEntries[i]\n        const k = ev.run(e[0], ctx)\n        const v = ev.run(e[1], ctx)\n        if (k instanceof Promise || v instanceof Promise) {\n          results[i] = Promise.all([k, v])\n          async ??= true\n        } else {\n          results[i] = [k, v]\n        }\n      }\n      if (async) return Promise.all(results).then(safeFromEntries)\n      return safeFromEntries(results)\n    }\n  },\n  comprehension: {\n    check(chk, ast, ctx) {\n      const args = ast.args\n      args.iterCtx = ctx\n        .forkWithVariable(args.iterVarName, comprehensionElementType(chk, args.iterable, ctx))\n        .setAccuType(chk.check(args.init, ctx))\n\n      const stepType = chk.check(args.step, args.iterCtx)\n      const handler = args.errorsAreFatal ? runComprehension : runQualifier\n      ast.handle = maybeAsync(args.iterable, false, handler)\n      if (args.kind === 'quantifier') return chk.boolType\n      return stepType\n    },\n    evaluate(ev, ast, ctx) {\n      return ast.handle(ev.run(ast.args.iterable, ctx), ast.args, ev, ctx)\n    }\n  },\n  accuValue: {\n    check(_chk, _ast, ctx) {\n      return ctx.accuType\n    },\n    evaluate(_ev, _ast, ctx) {\n      return ctx.accuValue\n    }\n  },\n  accuInc: {\n    check(_chk, _ast, ctx) {\n      return ctx.accuType\n    },\n    evaluate(_ev, _ast, ctx) {\n      return (ctx.accuValue += 1)\n    }\n  },\n  accuPush: {\n    check(chk, ast, ctx) {\n      const listType = ctx.accuType\n      const itemType = chk.check(ast.args, ctx)\n      if (!ast.args.maybeAsync) ast.setMeta('evaluate', OPERATORS.accuPush.evaluateSync)\n      if (listType.kind === 'list' && listType.valueType.kind !== 'param') return listType\n      return chk.registry.getListType(itemType)\n    },\n    evaluateSync(ev, ast, ctx) {\n      return (ctx.accuValue.push(ev.run(ast.args, ctx)), ctx.accuValue)\n    },\n    evaluate(ev, ast, ctx) {\n      const arr = ctx.accuValue\n      const el = ev.run(ast.args, ctx)\n      if (el instanceof Promise) return el.then((_e) => arr.push(_e) && arr)\n      arr.push(el)\n      return arr\n    }\n  },\n  '?:': {\n    alias: 'ternary',\n    check(chk, ast, ctx) {\n      const condast = (ast.condition = ast.args[0])\n      const leftast = (ast.left = ast.args[1])\n      const rightast = (ast.right = ast.args[2])\n      const condType = chk.check(condast, ctx)\n      if (!condType.isDynOrBool()) {\n        throw chk.createError(\n          'invalid_condition_type',\n          `${condast.meta.label || 'Ternary condition must be bool'}, got '${chk.formatType(condType)}'`,\n          condast\n        )\n      }\n\n      const leftType = chk.check(leftast, ctx)\n      const rightType = chk.check(rightast, ctx)\n      const unified = leftType.unify(chk.registry, rightType)\n\n      ast.handle = maybeAsync(condast, false, handleTernary)\n      if (unified) return unified\n\n      throw chk.createError(\n        'incompatible_ternary_branches',\n        `Ternary branches must have the same type, got '${chk.formatType(\n          leftType\n        )}' and '${chk.formatType(rightType)}'`,\n        ast\n      )\n    },\n    evaluate(ev, ast, ctx) {\n      return ast.handle(ev.run(ast.condition, ctx), ev, ast, ctx)\n    }\n  },\n  '||': {\n    check: checkLogicalOp,\n    evaluate(ev, ast, ctx) {\n      const l = ev.tryEval(ast.left, ctx)\n      if (l === true) return true\n      if (l === false) {\n        const right = ev.run(ast.right, ctx)\n        if (typeof right === 'boolean') return right\n        return _logicalOp(true, ev, ast, l, right)\n      }\n      if (l instanceof Promise)\n        return l.then((_l) =>\n          _l === true ? _l : _logicalOp(true, ev, ast, _l, ev.run(ast.right, ctx))\n        )\n      return _logicalOp(true, ev, ast, l, ev.run(ast.right, ctx))\n    }\n  },\n  '&&': {\n    check: checkLogicalOp,\n    evaluate(ev, ast, ctx) {\n      const l = ev.tryEval(ast.left, ctx)\n      if (l === false) return false\n      if (l === true) {\n        const right = ev.run(ast.right, ctx)\n        if (typeof right === 'boolean') return right\n        return _logicalOp(false, ev, ast, l, right)\n      }\n      if (l instanceof Promise)\n        return l.then((_l) =>\n          _l === false ? _l : _logicalOp(false, ev, ast, _l, ev.run(ast.right, ctx))\n        )\n      return _logicalOp(false, ev, ast, l, ev.run(ast.right, ctx))\n    }\n  },\n  '!_': {alias: 'unaryNot', check: checkUnary, evaluate: evaluateUnary},\n  '-_': {alias: 'unaryMinus', check: checkUnary, evaluate: evaluateUnary}\n}\n\nconst binaryOperators = ['!=', '==', 'in', '+', '-', '*', '/', '%', '<', '<=', '>', '>=']\nfor (const op of binaryOperators) OPERATORS[op] = {check: checkBinary, evaluate: evaluateBinary}\nfor (const op of objKeys(OPERATORS)) {\n  const obj = OPERATORS[op]\n  obj.name = op\n  if (obj.alias) OPERATORS[obj.alias] = obj\n}\n","import {evaluationError, parseError} from './errors.js'\nimport {OPERATORS as OPS} from './operators.js'\nconst identity = (x) => x\n\nfunction assertIdentifier(node, message) {\n  if (node.op === 'id') return node.args\n  throw parseError('invalid_macro_argument', message, node)\n}\n\nfunction createMapExpander(hasFilter) {\n  const functionDesc = hasFilter ? 'map(var, filter, transform)' : 'map(var, transform)'\n  const invalidMsg = `${functionDesc} invalid predicate iteration variable`\n  const label = `${functionDesc} filter predicate must return bool`\n\n  return ({args, receiver, ast: callAst}) => {\n    const [iterVar, predicate, transform] = hasFilter ? args : [args[0], null, args[1]]\n\n    let step = transform.clone(OPS.accuPush, transform)\n    if (predicate) {\n      const accuValue = predicate.clone(OPS.accuValue)\n      step = predicate.clone(OPS.ternary, [predicate.setMeta('label', label), step, accuValue])\n    }\n\n    return {\n      callAst: callAst.clone(OPS.comprehension, {\n        errorsAreFatal: true,\n        iterable: receiver,\n        iterVarName: assertIdentifier(iterVar, invalidMsg),\n        init: callAst.clone(OPS.list, []),\n        step,\n        result: identity\n      })\n    }\n  }\n}\n\nfunction createFilterExpander() {\n  const functionDesc = 'filter(var, predicate)'\n  const invalidMsg = `${functionDesc} invalid predicate iteration variable`\n  const label = `${functionDesc} predicate must return bool`\n\n  return ({args, receiver, ast: callAst}) => {\n    const iterVarName = assertIdentifier(args[0], invalidMsg)\n    const accuValue = callAst.clone(OPS.accuValue)\n    const predicate = args[1].setMeta('label', label)\n    const appendItem = callAst.clone(OPS.accuPush, callAst.clone(OPS.id, iterVarName))\n    const step = predicate.clone(OPS.ternary, [predicate, appendItem, accuValue])\n\n    return {\n      callAst: callAst.clone(OPS.comprehension, {\n        errorsAreFatal: true,\n        iterable: receiver,\n        iterVarName,\n        init: callAst.clone(OPS.list, []),\n        step,\n        result: identity\n      })\n    }\n  }\n}\n\nfunction createQuantifierExpander(opts) {\n  const invalidMsg = `${opts.name}(var, predicate) invalid predicate iteration variable`\n  const label = `${opts.name}(var, predicate) predicate must return bool`\n  return ({args, receiver, ast: callAst}) => {\n    const predicate = args[1].setMeta('label', label)\n    const transform = opts.transform({args, ast: callAst, predicate, opts})\n\n    return {\n      callAst: callAst.clone(OPS.comprehension, {\n        kind: 'quantifier',\n        errorsAreFatal: opts.errorsAreFatal || false,\n        iterable: receiver,\n        iterVarName: assertIdentifier(args[0], invalidMsg),\n        init: transform.init,\n        condition: transform.condition,\n        step: transform.step,\n        result: transform.result || identity\n      })\n    }\n  }\n}\n\nfunction createHasExpander() {\n  const invalidHasArgument = 'has() invalid argument'\n\n  function evaluate(ev, macro, ctx) {\n    const nodes = macro.macroHasProps\n    let i = nodes.length\n    let obj = ev.run(nodes[--i], ctx)\n    let inOptionalContext\n    while (i--) {\n      const node = nodes[i]\n      if (node.op === '.?') inOptionalContext ??= true\n      obj = ev.debugType(obj).fieldLazy(obj, node.args[1], node, ev)\n      if (obj !== undefined) continue\n      if (!(!inOptionalContext && i && node.op === '.')) break\n      throw evaluationError('no_such_key', `No such key: ${node.args[1]}`, node)\n    }\n    return obj !== undefined\n  }\n\n  function typeCheck(checker, macro, ctx) {\n    let node = macro.args[0]\n    if (node.op !== '.') throw checker.createError('invalid_macro_argument', invalidHasArgument, node)\n    if (!macro.macroHasProps) {\n      const props = []\n      while (node.op === '.' || node.op === '.?') node = props.push(node) && node.args[0]\n      if (node.op !== 'id') throw checker.createError('invalid_macro_argument', invalidHasArgument, node)\n      checker.check(node, ctx)\n      props.push(node)\n      macro.macroHasProps = props\n    }\n    return checker.getType('bool')\n  }\n\n  return function ({args}) {\n    return {args, evaluate, typeCheck, async: false}\n  }\n}\n\nexport function registerMacros(registry) {\n  const functionOverload = (sig, handler) => registry.registerFunctionOverload(sig, handler)\n\n  functionOverload('has(ast): bool', createHasExpander())\n\n  functionOverload(\n    'list.all(ast, ast): bool',\n    createQuantifierExpander({\n      name: 'all',\n      transform({ast: callAst, predicate, opts}) {\n        return {\n          init: callAst.clone(OPS.value, true),\n          condition: identity,\n          step: predicate.clone(OPS.ternary, [\n            predicate,\n            predicate.clone(OPS.value, true),\n            predicate.clone(OPS.value, false)\n          ])\n        }\n      }\n    })\n  )\n\n  functionOverload(\n    'list.exists(ast, ast): bool',\n    createQuantifierExpander({\n      name: 'exists',\n      condition(accu) {\n        return !accu\n      },\n      transform({ast: callAst, predicate, opts}) {\n        return {\n          init: callAst.clone(OPS.value, false),\n          condition: opts.condition,\n          step: predicate.clone(OPS.ternary, [\n            predicate,\n            predicate.clone(OPS.value, true),\n            predicate.clone(OPS.value, false)\n          ])\n        }\n      }\n    })\n  )\n\n  functionOverload(\n    'list.exists_one(ast, ast): bool',\n    createQuantifierExpander({\n      name: 'exists_one',\n      errorsAreFatal: true,\n      result(accu) {\n        return accu === 1\n      },\n      transform({ast: callAst, predicate, opts}) {\n        const accuValue = callAst.clone(OPS.accuValue)\n        return {\n          init: callAst.clone(OPS.value, 0),\n          step: predicate.clone(OPS.ternary, [predicate, callAst.clone(OPS.accuInc), accuValue]),\n          result: opts.result\n        }\n      }\n    })\n  )\n\n  functionOverload('list.map(ast, ast): list<dyn>', createMapExpander(false))\n  functionOverload('list.map(ast, ast, ast): list<dyn>', createMapExpander(true))\n  functionOverload('list.filter(ast, ast): list<dyn>', createFilterExpander())\n\n  class CelNamespace {}\n  const celNamespace = new CelNamespace()\n  registry.registerType('CelNamespace', CelNamespace)\n  registry.registerConstant('cel', 'CelNamespace', celNamespace)\n\n  function bindTypeCheck(checker, m, ctx) {\n    m.bindCtx = ctx.forkWithVariable(m.var, checker.check(m.val, ctx))\n    const type = checker.check(m.exp, m.bindCtx)\n    if (m.val.maybeAsync || m.exp.maybeAsync) return type\n    m.ast.setMeta('async', false)\n    m.evaluate = bindEvaluateSync\n    return type\n  }\n\n  function bindOptionalEvaluate(ev, exp, bindCtx, ctx, boundValue) {\n    const res = ev.run(exp, (ctx = bindCtx.reuse(ctx).setIterValue(boundValue, ev)))\n    if (res instanceof Promise && ctx === bindCtx) ctx.async = true\n    return res\n  }\n\n  function bindEvaluate(ev, {val, exp, bindCtx}, ctx) {\n    const v = ev.run(val, ctx)\n    if (v instanceof Promise) return v.then((_v) => bindOptionalEvaluate(ev, exp, bindCtx, ctx, _v))\n    return bindOptionalEvaluate(ev, exp, bindCtx, ctx, v)\n  }\n\n  function bindEvaluateSync(ev, {val, exp, bindCtx}, ctx) {\n    return ev.run(exp, bindCtx.reuse(ctx).setIterValue(ev.run(val, ctx), ev))\n  }\n\n  functionOverload('CelNamespace.bind(ast, dyn, ast): dyn', ({ast, args}) => {\n    return {\n      ast,\n      var: assertIdentifier(args[0], 'invalid variable argument'),\n      val: args[1],\n      exp: args[2],\n      bindCtx: undefined,\n      typeCheck: bindTypeCheck,\n      evaluate: bindEvaluate\n    }\n  })\n}\n","import {UnsignedInt, Duration} from './functions.js'\nimport {evaluationError} from './errors.js'\nimport {isArray, hasOwn, objKeys, MIN_UINT, MIN_INT, MAX_INT} from './globals.js'\n\nexport function registerOverloads(registry) {\n  const unaryOverload = (op, t, h, ret) => registry.unaryOverload(op, t, h, ret, false)\n  const binaryOverload = (l, op, r, h, ret) => registry.binaryOverload(l, op, r, h, ret, false)\n\n  function verifyInteger(v, ast) {\n    if (v <= MAX_INT && v >= MIN_INT) return v\n    throw evaluationError('numeric_overflow', `integer overflow: ${v}`, ast)\n  }\n\n  function throwDivisionByZero(ast) {\n    throw evaluationError('division_by_zero', 'division by zero', ast)\n  }\n\n  function throwModuloByZero(ast) {\n    throw evaluationError('modulo_by_zero', 'modulo by zero', ast)\n  }\n\n  unaryOverload('!', 'bool', (a) => !a)\n  unaryOverload('-', 'int', (a) => -a)\n  binaryOverload('dyn<int>', `==`, `double`, (a, b) => a == b) // eslint-disable-line eqeqeq\n  binaryOverload('dyn<int>', `==`, `uint`, (a, b) => a == b.valueOf()) // eslint-disable-line eqeqeq\n  binaryOverload('int', '*', 'int', (a, b, ast) => verifyInteger(a * b, ast))\n  binaryOverload('int', '+', 'int', (a, b, ast) => verifyInteger(a + b, ast))\n  binaryOverload('int', '-', 'int', (a, b, ast) => verifyInteger(a - b, ast))\n  binaryOverload('int', '/', 'int', (a, b, ast) => {\n    if (b === MIN_UINT) return throwDivisionByZero(ast)\n    return a / b\n  })\n  binaryOverload('int', '%', 'int', (a, b, ast) => {\n    if (b === MIN_UINT) return throwModuloByZero(ast)\n    return a % b\n  })\n\n  unaryOverload('-', 'double', (a) => -a)\n  binaryOverload('double', '*', 'double', (a, b) => a * b)\n  binaryOverload('double', '+', 'double', (a, b) => a + b)\n  binaryOverload('double', '-', 'double', (a, b) => a - b)\n  binaryOverload('double', '/', 'double', (a, b) => a / b)\n\n  binaryOverload('string', '+', 'string', (a, b) => a + b)\n  binaryOverload('list<V>', '+', 'list<V>', (a, b) => [...a, ...b])\n  binaryOverload('bytes', '+', 'bytes', (a, b) => {\n    if (!a.length) return b\n    if (!b.length) return a\n\n    const result = new Uint8Array(a.length + b.length)\n    result.set(a, 0)\n    result.set(b, a.length)\n    return result\n  })\n\n  const GPD = 'google.protobuf.Duration'\n  binaryOverload(GPD, '+', GPD, (a, b) => a.addDuration(b))\n  binaryOverload(GPD, '-', GPD, (a, b) => a.subtractDuration(b))\n  binaryOverload(GPD, '==', GPD, (a, b) => a.seconds === b.seconds && a.nanos === b.nanos)\n\n  const GPT = 'google.protobuf.Timestamp'\n  binaryOverload(GPT, '==', GPT, (a, b) => a.getTime() === b.getTime())\n  binaryOverload(GPT, '-', GPT, (a, b) => Duration.fromMilliseconds(a.getTime() - b.getTime()), GPD)\n  binaryOverload(GPT, '-', GPD, (a, b) => b.subtractTimestamp(a))\n  binaryOverload(GPT, '+', GPD, (a, b) => b.extendTimestamp(a))\n  binaryOverload(GPD, '+', GPT, (a, b) => a.extendTimestamp(b))\n\n  function listIncludes(value, list, ast, ev) {\n    if (list instanceof Set && list.has(value)) return true\n    for (const v of list) if (isEqual(value, v, ast, ev)) return true\n    return false\n  }\n\n  function mapIncludes(a, b) {\n    if (b instanceof Map) return b.get(a) !== undefined\n    return hasOwn(b, a) ? b[a] !== undefined : false\n  }\n\n  function listMembership(value, list, ast, ev) {\n    return listIncludes(value, list, ast, ev)\n  }\n\n  binaryOverload('V', 'in', 'list<V>', listMembership)\n  binaryOverload('K', 'in', 'map<K, V>', mapIncludes)\n\n  for (const t of ['type', 'null', 'bool', 'string', 'int', 'double']) {\n    binaryOverload(t, '==', t, (a, b) => a === b)\n  }\n\n  binaryOverload('bytes', `==`, 'bytes', (a, b) => {\n    if (a === b) return true\n\n    let i = a.length\n    if (i !== b.length) return false\n    while (i--) if (a[i] !== b[i]) return false\n    return true\n  })\n\n  binaryOverload('list<V>', `==`, 'list<V>', (a, b, ast, ev) => {\n    if (a === b) return true\n\n    if (isArray(a) && isArray(b)) {\n      const length = a.length\n      if (length !== b.length) return false\n      for (let i = 0; i < length; i++) {\n        if (!isEqual(a[i], b[i], ast, ev)) return false\n      }\n      return true\n    }\n\n    if (a instanceof Set && b instanceof Set) {\n      if (a.size !== b.size) return false\n      for (const value of a) if (!b.has(value)) return false\n      return true\n    }\n\n    const arr = a instanceof Set ? b : a\n    const set = a instanceof Set ? a : b\n    if (!isArray(arr)) return false\n    if (arr.length !== set?.size) return false\n    for (let i = 0; i < arr.length; i++) if (!set.has(arr[i])) return false\n    return true\n  })\n\n  binaryOverload('map<K, V>', `==`, 'map<K, V>', (a, b, ast, ev) => {\n    if (a === b) return true\n\n    if (a instanceof Map && b instanceof Map) {\n      if (a.size !== b.size) return false\n      for (const [key, value] of a)\n        if (!(b.has(key) && isEqual(value, b.get(key), ast, ev))) return false\n      return true\n    }\n\n    if (a instanceof Map || b instanceof Map) {\n      const obj = a instanceof Map ? b : a\n      const map = a instanceof Map ? a : b\n      const keysObj = objKeys(obj)\n      if (map.size !== keysObj.length) return false\n      for (const [key, value] of map) {\n        if (!(key in obj && isEqual(value, obj[key], ast, ev))) return false\n      }\n      return true\n    }\n\n    const keysA = objKeys(a)\n    const keysB = objKeys(b)\n    if (keysA.length !== keysB.length) return false\n\n    for (let i = 0; i < keysA.length; i++) {\n      const key = keysA[i]\n      if (!(key in b && isEqual(a[key], b[key], ast, ev))) return false\n    }\n    return true\n  })\n\n  binaryOverload('uint', '==', 'uint', (a, b) => a.valueOf() === b.valueOf())\n  binaryOverload('dyn<uint>', `==`, `double`, (a, b) => a.valueOf() == b) // eslint-disable-line eqeqeq\n\n  binaryOverload('uint', '+', 'uint', (a, b) => new UnsignedInt(a.valueOf() + b.valueOf()))\n  binaryOverload('uint', '-', 'uint', (a, b) => new UnsignedInt(a.valueOf() - b.valueOf()))\n  binaryOverload('uint', '*', 'uint', (a, b) => new UnsignedInt(a.valueOf() * b.valueOf()))\n  binaryOverload('uint', '/', 'uint', (a, b, ast) => {\n    if (b.valueOf() === MIN_UINT) return throwDivisionByZero(ast)\n    return new UnsignedInt(a.valueOf() / b.valueOf())\n  })\n  binaryOverload('uint', '%', 'uint', (a, b, ast) => {\n    if (b.valueOf() === MIN_UINT) return throwModuloByZero(ast)\n    return new UnsignedInt(a.valueOf() % b.valueOf())\n  })\n\n  for (const [left, right] of [\n    ['bool', 'bool'],\n    ['int', 'int'],\n    ['uint', 'uint'],\n    ['double', 'double'],\n    ['string', 'string'],\n    ['google.protobuf.Timestamp', 'google.protobuf.Timestamp'],\n    ['google.protobuf.Duration', 'google.protobuf.Duration'],\n    ['int', 'uint'],\n    ['int', 'double'],\n    ['double', 'int'],\n    ['double', 'uint'],\n    ['uint', 'int'],\n    ['uint', 'double']\n  ]) {\n    binaryOverload(left, '<', right, (a, b) => a < b)\n    binaryOverload(left, '<=', right, (a, b) => a <= b)\n    binaryOverload(left, '>', right, (a, b) => a > b)\n    binaryOverload(left, '>=', right, (a, b) => a >= b)\n  }\n}\n\nfunction isEqual(a, b, ast, ev) {\n  if (a === b) return true\n  switch (typeof a) {\n    case 'undefined':\n    case 'string':\n    case 'boolean':\n      return false\n    case 'bigint':\n      // eslint-disable-next-line eqeqeq\n      if (typeof b === 'number') return a == b\n      return false\n    case 'number':\n      // eslint-disable-next-line eqeqeq\n      if (typeof b === 'bigint') return a == b\n      return false\n    case 'object':\n      if (typeof b !== 'object') return false\n      const leftType = ev.debugType(a)\n      const rightType = ev.debugType(b)\n      if (leftType !== rightType) return false\n\n      const overload = ev.registry.findBinaryOverload('==', leftType, rightType)\n      if (!overload) return false\n      return overload.handler(a, b, ast, ev)\n  }\n  throw evaluationError('invalid_comparison_type', `Cannot compare values of type ${typeof a}`, ast)\n}\n","import {attachErrorAst, evaluationError, typeError} from './errors.js'\nimport {Base} from './operators.js'\nconst toDynTypeBinding = new Map().set('A', 'dyn').set('T', 'dyn').set('K', 'dyn').set('V', 'dyn')\n\n/**\n * TypeChecker performs static type analysis on CEL expressions\n * without executing them. It validates:\n * - Variable existence and types\n * - Function signatures and overloads\n * - Operator compatibility using the actual overload registry\n * - Property and index access validity\n */\nexport class TypeChecker extends Base {\n  constructor(opts, isEvaluating) {\n    super(opts)\n    this.createError = isEvaluating ? evaluationError : typeError\n  }\n\n  /**\n   * Check an expression and return its inferred type\n   * @param {Array|any} ast - The AST node to check\n   * @returns {Object} The inferred type declaration\n   * @throws {TypeError} If type checking fails\n   */\n  check(ast, ctx) {\n    try {\n      return (ast.checkedType ??= ast.check(this, ast, ctx))\n    } catch (error) {\n      throw attachErrorAst(error, ast)\n    }\n  }\n\n  checkAccessOnType(ast, ctx, leftType, allowMissingField = false) {\n    if (leftType === this.dynType) return leftType\n\n    const indexTypeName = (\n      ast.op === '[]' || ast.op === '[?]' ? this.check(ast.args[1], ctx) : this.stringType\n    ).type\n\n    if (leftType.kind === 'list') {\n      if (indexTypeName === 'int' || indexTypeName === 'dyn') return leftType.valueType\n      throw this.createError('invalid_index_type', `List index must be int, got '${indexTypeName}'`, ast)\n    }\n\n    if (leftType.kind === 'map') return leftType.valueType\n\n    const customType = this.objectTypes.get(leftType.name)\n    if (customType) {\n      if (!(indexTypeName === 'string' || indexTypeName === 'dyn')) {\n        throw this.createError(\n          'invalid_index_type',\n          `Cannot index type '${leftType.name}' with type '${indexTypeName}'`,\n          ast\n        )\n      }\n\n      if (customType.fields) {\n        let keyName\n        if (ast.op === '.' || ast.op === '.?') keyName = ast.args[1]\n        else if (ast.args[1].op === 'value') keyName = ast.args[1].args\n\n        if (typeof keyName === 'string') {\n          const fieldType = customType.fields[keyName]\n          if (fieldType) return fieldType\n          // For optional access, missing field returns dyn; for regular access, throw\n          if (allowMissingField) return this.dynType\n          throw this.createError('no_such_key', `No such key: ${keyName}`, ast)\n        }\n      }\n      return this.dynType\n    }\n\n    // No other types support indexing/property access\n    throw this.createError('cannot_index_type', `Cannot index type '${this.formatType(leftType)}'`, ast)\n  }\n\n  formatType(type) {\n    if (!type.hasPlaceholderType) return type.name\n    return type.templated(this.registry, toDynTypeBinding).name\n  }\n\n  formatTypeList(types) {\n    return types.map((t) => this.formatType(t)).join(', ')\n  }\n}\n","import {UnsignedInt} from './functions.js'\nimport {parseError} from './errors.js'\nimport {OPERATORS as OPS} from './operators.js'\nimport {RESERVED, isAsync} from './globals.js'\n\nconst TOKEN = {\n  EOF: 0,\n  NUMBER: 1,\n  STRING: 2,\n  BOOLEAN: 3,\n  NULL: 4,\n  IDENTIFIER: 5,\n  PLUS: 6,\n  MINUS: 7,\n  MULTIPLY: 8,\n  DIVIDE: 9,\n  MODULO: 10,\n  EQ: 11,\n  NE: 12,\n  LT: 13,\n  LE: 14,\n  GT: 15,\n  GE: 16,\n  AND: 17,\n  OR: 18,\n  NOT: 19,\n  IN: 20,\n  LPAREN: 21,\n  RPAREN: 22,\n  LBRACKET: 23,\n  RBRACKET: 24,\n  LBRACE: 25,\n  RBRACE: 26,\n  DOT: 27,\n  COMMA: 28,\n  COLON: 29,\n  QUESTION: 30,\n  BYTES: 31\n}\n\nconst OP_FOR_TOKEN = {\n  [TOKEN.EQ]: OPS['=='],\n  [TOKEN.PLUS]: OPS['+'],\n  [TOKEN.MINUS]: OPS['-'],\n  [TOKEN.MULTIPLY]: OPS['*'],\n  [TOKEN.DIVIDE]: OPS['/'],\n  [TOKEN.MODULO]: OPS['%'],\n  [TOKEN.LE]: OPS['<='],\n  [TOKEN.LT]: OPS['<'],\n  [TOKEN.GE]: OPS['>='],\n  [TOKEN.GT]: OPS['>'],\n  [TOKEN.NE]: OPS['!='],\n  [TOKEN.IN]: OPS['in']\n}\n\nconst TOKEN_BY_NUMBER = {}\nfor (const key in TOKEN) TOKEN_BY_NUMBER[TOKEN[key]] = key\n\nconst HEX_CODES = new Uint8Array(128)\nfor (const ch of '0123456789abcdefABCDEF') HEX_CODES[ch.charCodeAt(0)] = 1\n\nconst ESCAPE_ERRORS = {\n  bytes_unicode_escape: (e) => `\\\\${e} not allowed in bytes literals`,\n  invalid_unicode_escape: (e) => `Invalid Unicode escape: \\\\${e}`,\n  invalid_unicode_surrogate: (e) => `Invalid Unicode surrogate: \\\\${e}`,\n  invalid_hex_escape: (e) => `Invalid hex escape: \\\\${e}`,\n  invalid_octal_escape: () => 'Octal escape must be 3 digits',\n  octal_escape_out_of_range: (e) => `Octal escape out of range: \\\\${e}`,\n  invalid_escape_sequence: (e) => `Invalid escape sequence: \\\\${e}`\n}\n\nconst STRING_ESCAPES = {\n  '\\\\': '\\\\',\n  '?': '?',\n  '\"': '\"',\n  \"'\": \"'\",\n  '`': '`',\n  a: '\\x07',\n  b: '\\b',\n  f: '\\f',\n  n: '\\n',\n  r: '\\r',\n  t: '\\t',\n  v: '\\v'\n}\n\nexport class ASTNode {\n  #meta\n  #input\n  constructor(input, pos, start, end, op, args) {\n    this.#meta = {check: op.check, evaluate: op.evaluate}\n    this.#input = input\n    this.op = op.name\n    this.args = args\n    this.pos = pos\n    this.start = start\n    this.end = end\n  }\n\n  clone(op, args) {\n    return new ASTNode(this.#input, this.pos, this.start, this.end, op, args)\n  }\n\n  get meta() {\n    return this.#meta\n  }\n\n  get input() {\n    return this.#input\n  }\n\n  #computeIsAsync() {\n    const ast = this.#meta.alternate ?? this\n\n    // prettier-ignore\n    switch (ast.op) {\n      case 'value': case 'id': case 'accuValue': case 'accuInc':\n        return false\n      case 'accuPush':\n        return ast.args.maybeAsync\n      case '!_': case '-_':\n        if (ast.candidates?.async !== false) return true\n        return ast.args.maybeAsync\n      case '!=': case '==': case 'in': case '+': case '-': case '*':\n      case '/': case '%': case '<': case '<=': case '>': case '>=':\n        if (ast.candidates?.async !== false) return true\n        return ast.args.some((a) => a.maybeAsync)\n      case 'call': case 'rcall':\n        if (ast.candidates?.async !== false) return true\n        return (ast.receiverWithArgs || ast.args[1]).some((a) => a.maybeAsync)\n      case 'comprehension':\n        return ast.args.iterable.maybeAsync || ast.args.step.maybeAsync\n      case '.': case '.?':\n        return ast.args[0].maybeAsync\n      case '?:': case 'list':\n      case '[]': case '[?]':\n          return ast.args.some((a) => a.maybeAsync)\n      case '||': case '&&':\n        return ast.args.some((a) => a.maybeAsync)\n      case 'map':\n        return ast.args.some((a) => a[0].maybeAsync || a[1].maybeAsync)\n      default:\n        return true\n    }\n  }\n\n  /**\n   * Check whether we can optimize away async calling\n   * If no ast members includes a function, we can optimize the call\n   * for which we want to return true here.\n   * @returns {boolean}\n   */\n  get maybeAsync() {\n    return (this.#meta.async ??= this.#computeIsAsync())\n  }\n\n  check(chk, ast, ctx) {\n    const meta = this.#meta\n    if (meta.alternate) return chk.check(meta.alternate, ctx)\n    else if (meta.macro) return meta.macro.typeCheck(chk, meta.macro, ctx)\n    return meta.check(chk, ast, ctx)\n  }\n\n  evaluate(ev, ast, ctx) {\n    const meta = this.#meta\n    if (meta.alternate) this.evaluate = this.#evaluateAlternate\n    else if (meta.macro) this.evaluate = this.#evaluateMacro\n    else this.evaluate = meta.evaluate\n    return this.evaluate(ev, ast, ctx)\n  }\n\n  #evaluateAlternate(ev, ast, ctx) {\n    return (ast = this.#meta.alternate).evaluate(ev, ast, ctx)\n  }\n\n  #evaluateMacro(ev, ast, ctx) {\n    return (ast = this.#meta.macro).evaluate(ev, ast, ctx)\n  }\n\n  setMeta(key, value) {\n    return ((this.#meta[key] = value), this)\n  }\n\n  get range() {\n    return {start: this.start, end: this.end}\n  }\n\n  toOldStructure() {\n    const args = Array.isArray(this.args) ? this.args : [this.args]\n    return [this.op, ...args.map((a) => (a instanceof ASTNode ? a.toOldStructure() : a))]\n  }\n}\n\nclass Lexer {\n  input\n  pos\n  length\n\n  tokenPos\n  tokenType\n  tokenValue\n\n  reset(input) {\n    this.pos = 0\n    this.input = input\n    this.length = input.length\n    return input\n  }\n\n  token(pos, type, value) {\n    this.tokenPos = pos\n    this.tokenType = type\n    this.tokenValue = value\n    return this\n  }\n\n  // Read next token\n  nextToken() {\n    while (true) {\n      const {pos, input, length} = this\n      if (pos >= length) return this.token(pos, TOKEN.EOF)\n\n      const ch = input[pos]\n      switch (ch) {\n        // Whitespaces\n        case ' ':\n        case '\\t':\n        case '\\n':\n        case '\\r':\n          this.pos++\n          continue\n\n        // Operators\n        case '=':\n          if (input[pos + 1] !== '=') break\n          return this.token((this.pos += 2) - 2, TOKEN.EQ)\n        case '&':\n          if (input[pos + 1] !== '&') break\n          return this.token((this.pos += 2) - 2, TOKEN.AND)\n        case '|':\n          if (input[pos + 1] !== '|') break\n          return this.token((this.pos += 2) - 2, TOKEN.OR)\n        case '+':\n          return this.token(this.pos++, TOKEN.PLUS)\n        case '-':\n          return this.token(this.pos++, TOKEN.MINUS)\n        case '*':\n          return this.token(this.pos++, TOKEN.MULTIPLY)\n        case '/':\n          if (input[pos + 1] === '/') {\n            while (this.pos < length && this.input[this.pos] !== '\\n') this.pos++\n            continue\n          }\n          return this.token(this.pos++, TOKEN.DIVIDE)\n        case '%':\n          return this.token(this.pos++, TOKEN.MODULO)\n        case '<':\n          if (input[pos + 1] === '=') return this.token((this.pos += 2) - 2, TOKEN.LE)\n          return this.token(this.pos++, TOKEN.LT)\n        case '>':\n          if (input[pos + 1] === '=') return this.token((this.pos += 2) - 2, TOKEN.GE)\n          return this.token(this.pos++, TOKEN.GT)\n        case '!':\n          if (input[pos + 1] === '=') return this.token((this.pos += 2) - 2, TOKEN.NE)\n          return this.token(this.pos++, TOKEN.NOT)\n        case '(':\n          return this.token(this.pos++, TOKEN.LPAREN)\n        case ')':\n          return this.token(this.pos++, TOKEN.RPAREN)\n        case '[':\n          return this.token(this.pos++, TOKEN.LBRACKET)\n        case ']':\n          return this.token(this.pos++, TOKEN.RBRACKET)\n        case '{':\n          return this.token(this.pos++, TOKEN.LBRACE)\n        case '}':\n          return this.token(this.pos++, TOKEN.RBRACE)\n        case '.':\n          return this.token(this.pos++, TOKEN.DOT)\n        case ',':\n          return this.token(this.pos++, TOKEN.COMMA)\n        case ':':\n          return this.token(this.pos++, TOKEN.COLON)\n        case '?':\n          return this.token(this.pos++, TOKEN.QUESTION)\n        case `\"`:\n        case `'`:\n          return this.readString(ch)\n        // Check for string prefixes (b, B, r, R followed by quote)\n        case 'b':\n        case 'B':\n        case 'r':\n        case 'R': {\n          // This is a prefixed string, advance past the prefix and read string\n          const next = input[pos + 1]\n          if (next === '\"' || next === \"'\") return ++this.pos && this.readString(next, ch)\n          return this.readIdentifier()\n        }\n        default: {\n          const code = ch.charCodeAt(0)\n          if (code <= 57 && code >= 48) return this.readNumber()\n          if (this._isIdentifierCharCode(code)) return this.readIdentifier()\n        }\n      }\n\n      throw parseError('unexpected_character', `Unexpected character: ${ch}`, {\n        pos,\n        start: pos,\n        end: pos + 1,\n        input\n      })\n    }\n  }\n\n  // Characters: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_\n  _isIdentifierCharCode(c) {\n    if (c < 48 || c > 122) return false\n    return c >= 97 || (c >= 65 && c <= 90) || c <= 57 || c === 95\n  }\n\n  _parseAsDouble(start, end) {\n    const value = Number(this.input.substring(start, end))\n    if (Number.isFinite(value)) return this.token(start, TOKEN.NUMBER, value)\n    throw parseError('invalid_number', `Invalid number: ${value}`, {\n      pos: start,\n      start,\n      end,\n      input: this.input\n    })\n  }\n\n  _parseAsBigInt(start, end, isHex, unsigned) {\n    const string = this.input.substring(start, end)\n    if (unsigned === 'u' || unsigned === 'U') {\n      this.pos++\n      try {\n        return this.token(start, TOKEN.NUMBER, new UnsignedInt(string))\n      } catch (_err) {}\n    } else {\n      try {\n        return this.token(start, TOKEN.NUMBER, BigInt(string))\n      } catch (_err) {}\n    }\n\n    throw parseError(\n      isHex ? 'invalid_hex_integer' : 'invalid_integer',\n      isHex ? `Invalid hex integer: ${string}` : `Invalid integer: ${string}`,\n      {pos: start, start, end: this.pos, input: this.input}\n    )\n  }\n\n  _readDigits(input, length, pos, code) {\n    while (pos < length && (code = input.charCodeAt(pos)) && !(code > 57 || code < 48)) pos++\n    return pos\n  }\n\n  _readExponent(input, length, pos) {\n    let ch = pos < length && input[pos]\n    if (ch === 'e' || ch === 'E') {\n      ch = ++pos < length && input[pos]\n      if (ch === '-' || ch === '+') pos++\n      const start = pos\n      pos = this._readDigits(input, length, pos)\n      if (start === pos)\n        throw parseError('invalid_exponent', 'Invalid exponent', {\n          pos,\n          start: pos,\n          end: Math.min(pos + 1, input.length),\n          input\n        })\n    }\n    return pos\n  }\n\n  readNumber() {\n    const {input, length, pos: start} = this\n    let pos = start\n    if (input[pos] === '0' && (input[pos + 1] === 'x' || input[pos + 1] === 'X')) {\n      pos += 2\n      while (pos < length && HEX_CODES[input[pos].charCodeAt(0)]) pos++\n      return this._parseAsBigInt(start, (this.pos = pos), true, input[pos])\n    }\n\n    pos = this._readDigits(input, length, pos)\n    if (pos + 1 < length) {\n      let isDouble = false\n      let afterpos = input[pos] === '.' ? this._readDigits(input, length, pos + 1) : pos + 1\n      if (afterpos !== pos + 1) (isDouble = true) && (pos = afterpos)\n\n      afterpos = this._readExponent(input, length, pos)\n      if (afterpos !== pos) (isDouble = true) && (pos = afterpos)\n      if (isDouble) return this._parseAsDouble(start, (this.pos = pos))\n    }\n    return this._parseAsBigInt(start, (this.pos = pos), false, input[pos])\n  }\n\n  readString(del, prefix) {\n    const {input: i, pos: s} = this\n    if (i[s + 1] === del && i[s + 2] === del) return this.readTripleQuotedString(del, prefix)\n    return this.readSingleQuotedString(del, prefix)\n  }\n\n  _closeQuotedString(rawStart, rawValue, prefix, pos) {\n    switch (prefix) {\n      case 'b':\n      case 'B': {\n        const processed = this.processEscapes(rawStart, rawValue, true)\n        const bytes = new Uint8Array(processed.length)\n        for (let i = 0; i < processed.length; i++) bytes[i] = processed.charCodeAt(i) & 0xff\n        return this.token(pos - 1, TOKEN.BYTES, bytes)\n      }\n      case 'r':\n      case 'R': {\n        return this.token(pos - 1, TOKEN.STRING, rawValue)\n      }\n      default: {\n        const value = this.processEscapes(rawStart, rawValue, false)\n        return this.token(pos, TOKEN.STRING, value)\n      }\n    }\n  }\n\n  readSingleQuotedString(delimiter, prefix) {\n    const {input, length, pos: start} = this\n\n    let ch\n    let pos = this.pos + 1\n    while (pos < length && (ch = input[pos])) {\n      switch (ch) {\n        case delimiter:\n          const rawStart = start + 1\n          const rawValue = input.slice(rawStart, pos)\n          this.pos = ++pos\n          return this._closeQuotedString(rawStart, rawValue, prefix, start)\n        case '\\n':\n        case '\\r':\n          throw parseError('newline_in_string', 'Newlines not allowed in single-quoted strings', {\n            pos,\n            start: pos,\n            end: pos + 1,\n            input\n          })\n        case '\\\\':\n          pos++\n      }\n      pos++\n    }\n    throw parseError('unterminated_string', 'Unterminated string', {\n      pos: start,\n      start,\n      end: input.length,\n      input\n    })\n  }\n\n  readTripleQuotedString(delimiter, prefix) {\n    const {input, length, pos: start} = this\n\n    let ch\n    let pos = this.pos + 3\n    while (pos < length && (ch = input[pos])) {\n      switch (ch) {\n        case delimiter:\n          if (input[pos + 1] === delimiter && input[pos + 2] === delimiter) {\n            const rawStart = start + 3\n            const rawValue = input.slice(rawStart, pos)\n            this.pos = pos + 3\n            return this._closeQuotedString(rawStart, rawValue, prefix, start)\n          }\n          break\n        case '\\\\':\n          pos++\n      }\n      pos++\n    }\n    throw parseError('unterminated_triple_quoted_string', 'Unterminated triple-quoted string', {\n      pos: start,\n      start,\n      end: input.length,\n      input\n    })\n  }\n\n  #escapeErr(code, offset, len, i, chars, extra) {\n    const start = offset + i\n    return parseError(code, ESCAPE_ERRORS[code](extra), {\n      input: this.input,\n      pos: start,\n      start,\n      end: Math.min(start + chars, offset + len)\n    })\n  }\n\n  processEscapes(offset, str, isBytes) {\n    if (!str.includes('\\\\')) return str\n\n    const len = str.length\n    let result = ''\n    let i = 0\n    while (i < len) {\n      if (str[i] !== '\\\\' || i + 1 >= len) {\n        result += str[i++]\n        continue\n      }\n\n      const next = str[i + 1]\n      if (STRING_ESCAPES[next]) {\n        result += STRING_ESCAPES[next]\n        i += 2\n      } else if (next === 'u' || next === 'U') {\n        if (isBytes) throw this.#escapeErr('bytes_unicode_escape', offset, len, i, 2, next)\n\n        const hexLen = next === 'u' ? 4 : 8\n        const hex = str.substring(i + 2, i + 2 + hexLen)\n        const c = Number.parseInt(hex, 16)\n        if (hex.length !== hexLen || !/^[0-9a-fA-F]+$/.test(hex) || c > 0x10ffff)\n          throw this.#escapeErr('invalid_unicode_escape', offset, len, i, 2 + hexLen, next + hex)\n        if (c >= 0xd800 && c <= 0xdfff)\n          throw this.#escapeErr('invalid_unicode_surrogate', offset, len, i, 2 + hexLen, next + hex)\n        result += String.fromCodePoint(c)\n        i += 2 + hexLen\n      } else if (next === 'x' || next === 'X') {\n        const h = str.substring(i + 2, i + 4)\n        if (!/^[0-9a-fA-F]{2}$/.test(h))\n          throw this.#escapeErr('invalid_hex_escape', offset, len, i, 4, next + h)\n        result += String.fromCharCode(Number.parseInt(h, 16))\n        i += 4\n      } else if (next >= '0' && next <= '7') {\n        const o = str.substring(i + 1, i + 4)\n        if (!/^[0-7]{3}$/.test(o)) throw this.#escapeErr('invalid_octal_escape', offset, len, i, 4)\n        const value = Number.parseInt(o, 8)\n        if (value > 0xff) throw this.#escapeErr('octal_escape_out_of_range', offset, len, i, 4, o)\n        result += String.fromCharCode(value)\n        i += 4\n      } else {\n        throw this.#escapeErr('invalid_escape_sequence', offset, len, i, 2, next)\n      }\n    }\n\n    return result\n  }\n\n  readIdentifier() {\n    const {pos, input, length} = this\n    let p = pos\n    while (p < length && this._isIdentifierCharCode(input[p].charCodeAt(0))) p++\n    const value = input.substring(pos, (this.pos = p))\n    switch (value) {\n      case 'true':\n        return this.token(pos, TOKEN.BOOLEAN, true)\n      case 'false':\n        return this.token(pos, TOKEN.BOOLEAN, false)\n      case 'null':\n        return this.token(pos, TOKEN.NULL, null)\n      case 'in':\n        return this.token(pos, TOKEN.IN)\n      default:\n        return this.token(pos, TOKEN.IDENTIFIER, value)\n    }\n  }\n}\n\nconst globalLexer = new Lexer()\nexport class Parser {\n  lexer = globalLexer\n  input = null\n  maxDepthRemaining = null\n  astNodesRemaining = null\n\n  type = null\n  pos = null\n\n  constructor(limits, registry) {\n    this.limits = limits\n    this.registry = registry\n  }\n\n  #limitExceeded(limitKey, pos = this.pos) {\n    throw parseError('limit_exceeded', `Exceeded ${limitKey} (${this.limits[limitKey]})`, {\n      pos,\n      start: pos,\n      end: pos,\n      input: this.input\n    })\n  }\n\n  #node(start, end, op, args, pos = start) {\n    const node = new ASTNode(this.input, pos, start, end, op, args)\n    if (!this.astNodesRemaining--) this.#limitExceeded('maxAstNodes', pos)\n    return node\n  }\n\n  #infixNode(op, left, right) {\n    return this.#node(left.start, right.end, op, [left, right])\n  }\n\n  #ternaryNode(expression, consequent, alternate) {\n    return this.#node(expression.start, alternate.end, OPS.ternary, [\n      expression,\n      consequent,\n      alternate\n    ])\n  }\n\n  #unaryNode(pos, op, arg) {\n    return this.#node(pos, arg.end, op, arg)\n  }\n\n  #accessNode(op, left, right, end, pos = left.start) {\n    return this.#node(left.start, end, op, [left, right], pos)\n  }\n\n  #advanceToken(returnValue = this.pos) {\n    const l = this.lexer.nextToken()\n    this.pos = l.tokenPos\n    this.type = l.tokenType\n    return returnValue\n  }\n\n  // The value of the current token is accessed less regularly,\n  // so we use a getter to reduce assignment overhead\n  get value() {\n    return this.lexer.tokenValue\n  }\n\n  consume(expectedType) {\n    if (this.type === expectedType) return this.#advanceToken()\n    throw parseError(\n      'expected_token',\n      `Expected ${TOKEN_BY_NUMBER[expectedType]}, got ${TOKEN_BY_NUMBER[this.type]}`,\n      {pos: this.pos, start: this.pos, end: this.lexer.pos, input: this.input}\n    )\n  }\n\n  match(type) {\n    return this.type === type\n  }\n\n  // Parse entry point\n  parse(input) {\n    if (typeof input !== 'string') {\n      throw parseError('expression_must_be_string', 'Expression must be a string')\n    }\n    this.input = this.lexer.reset(input)\n    this.#advanceToken()\n    this.maxDepthRemaining = this.limits.maxDepth\n    this.astNodesRemaining = this.limits.maxAstNodes\n\n    const result = this.parseExpression()\n    if (this.match(TOKEN.EOF)) return result\n\n    throw parseError(\n      'unexpected_character',\n      `Unexpected character: '${this.input[this.lexer.pos - 1]}'`,\n      {\n        pos: this.pos,\n        start: this.pos,\n        end: this.lexer.pos,\n        input: this.input\n      }\n    )\n  }\n\n  #expandMacro(start, end, op, args) {\n    const methodName = args[0]\n    const receiver = op === OPS.rcall ? args[1] : null\n    const fnArgs = op === OPS.rcall ? args[2] : args[1]\n    const decl = this.registry.findMacro(methodName, !!receiver, fnArgs.length)\n    const ast = this.#node(start, end, op, args)\n    if (!decl) return ast\n    const macro = decl.handler({ast, args: fnArgs, receiver, methodName, parser: this})\n    if (macro.callAst) return ast.setMeta('alternate', macro.callAst)\n    return ast.setMeta('macro', macro).setMeta('async', isAsync(macro.evaluate, macro.async))\n  }\n\n  // Expression ::= LogicalOr ('?' Expression ':' Expression)?\n  parseExpression() {\n    if (!this.maxDepthRemaining--) this.#limitExceeded('maxDepth')\n    const expr = this.parseLogicalOr()\n    if (!this.match(TOKEN.QUESTION)) return ++this.maxDepthRemaining && expr\n\n    this.#advanceToken()\n    const consequent = this.parseExpression()\n    this.consume(TOKEN.COLON)\n    const alternate = this.parseExpression()\n    this.maxDepthRemaining++\n    return this.#ternaryNode(expr, consequent, alternate)\n  }\n\n  // LogicalOr ::= LogicalAnd ('||' LogicalAnd)*\n  parseLogicalOr() {\n    let expr = this.parseLogicalAnd()\n    while (this.match(TOKEN.OR)) {\n      this.#advanceToken()\n      expr = this.#infixNode(OPS['||'], expr, this.parseLogicalAnd())\n    }\n    return expr\n  }\n\n  // LogicalAnd ::= Equality ('&&' Equality)*\n  parseLogicalAnd() {\n    let expr = this.parseEquality()\n    while (this.match(TOKEN.AND)) {\n      this.#advanceToken()\n      expr = this.#infixNode(OPS['&&'], expr, this.parseEquality())\n    }\n    return expr\n  }\n\n  // Equality ::= Relational (('==' | '!=') Relational)*\n  parseEquality() {\n    let expr = this.parseRelational()\n    while (this.match(TOKEN.EQ) || this.match(TOKEN.NE)) {\n      const op = OP_FOR_TOKEN[this.type]\n      this.#advanceToken()\n      expr = this.#infixNode(op, expr, this.parseRelational())\n    }\n    return expr\n  }\n\n  // Relational ::= Additive (('<' | '<=' | '>' | '>=' | 'in') Additive)*\n  parseRelational() {\n    let expr = this.parseAdditive()\n    while (\n      this.match(TOKEN.LT) ||\n      this.match(TOKEN.LE) ||\n      this.match(TOKEN.GT) ||\n      this.match(TOKEN.GE) ||\n      this.match(TOKEN.IN)\n    ) {\n      const op = OP_FOR_TOKEN[this.type]\n      this.#advanceToken()\n      expr = this.#infixNode(op, expr, this.parseAdditive())\n    }\n    return expr\n  }\n\n  // Additive ::= Multiplicative (('+' | '-') Multiplicative)*\n  parseAdditive() {\n    let expr = this.parseMultiplicative()\n    while (this.match(TOKEN.PLUS) || this.match(TOKEN.MINUS)) {\n      const op = OP_FOR_TOKEN[this.type]\n      this.#advanceToken()\n      expr = this.#infixNode(op, expr, this.parseMultiplicative())\n    }\n    return expr\n  }\n\n  // Multiplicative ::= Unary (('*' | '/' | '%') Unary)*\n  parseMultiplicative() {\n    let expr = this.parseUnary()\n    while (this.match(TOKEN.MULTIPLY) || this.match(TOKEN.DIVIDE) || this.match(TOKEN.MODULO)) {\n      const op = OP_FOR_TOKEN[this.type]\n      this.#advanceToken()\n      expr = this.#infixNode(op, expr, this.parseUnary())\n    }\n    return expr\n  }\n\n  // Unary ::= ('!' | '-')* Postfix\n  parseUnary() {\n    if (this.type === TOKEN.NOT) {\n      return this.#unaryNode(this.#advanceToken(), OPS.unaryNot, this.parseUnary())\n    }\n    if (this.type === TOKEN.MINUS) {\n      return this.#unaryNode(this.#advanceToken(), OPS.unaryMinus, this.parseUnary())\n    }\n    return this.parsePostfix()\n  }\n\n  // Postfix ::= Primary (('.' IDENTIFIER ('(' ArgumentList ')')? | '[' Expression ']'))*\n  parsePostfix() {\n    let expr = this.parsePrimary()\n    const depth = this.maxDepthRemaining\n    while (true) {\n      if (this.match(TOKEN.DOT)) {\n        const dot = this.#advanceToken()\n        if (!this.maxDepthRemaining--) this.#limitExceeded('maxDepth', dot)\n\n        const op =\n          this.match(TOKEN.QUESTION) && this.registry.enableOptionalTypes && this.#advanceToken()\n            ? OPS.optionalFieldAccess\n            : OPS.fieldAccess\n\n        const propertyValue = this.value\n        const start = this.pos\n        const end = this.lexer.pos\n        this.consume(TOKEN.IDENTIFIER)\n        if (op === OPS.fieldAccess && this.match(TOKEN.LPAREN) && this.#advanceToken()) {\n          const args = this.parseArgumentList()\n          const closeEnd = this.lexer.pos\n          this.consume(TOKEN.RPAREN)\n          expr = this.#expandMacro(expr.start, closeEnd, OPS.rcall, [propertyValue, expr, args])\n        } else {\n          expr = this.#accessNode(op, expr, propertyValue, end, start)\n        }\n        continue\n      }\n\n      if (this.match(TOKEN.LBRACKET)) {\n        const bracket = this.#advanceToken()\n        if (!this.maxDepthRemaining--) this.#limitExceeded('maxDepth', bracket)\n\n        const op =\n          this.match(TOKEN.QUESTION) && this.registry.enableOptionalTypes && this.#advanceToken()\n            ? OPS.optionalBracketAccess\n            : OPS.bracketAccess\n\n        const index = this.parseExpression()\n        const closeEnd = this.lexer.pos\n        this.consume(TOKEN.RBRACKET)\n        expr = this.#accessNode(op, expr, index, closeEnd)\n        continue\n      }\n      break\n    }\n    this.maxDepthRemaining = depth\n    return expr\n  }\n\n  // Primary ::= NUMBER | STRING | BOOLEAN | NULL | IDENTIFIER | '(' Expression ')' | Array | Object\n  parsePrimary() {\n    switch (this.type) {\n      case TOKEN.NUMBER:\n      case TOKEN.STRING:\n      case TOKEN.BYTES:\n      case TOKEN.BOOLEAN:\n      case TOKEN.NULL:\n        return this.#consumeLiteral()\n      case TOKEN.IDENTIFIER:\n        return this.#parseIdentifierPrimary()\n      case TOKEN.LPAREN:\n        return this.#parseParenthesizedExpression()\n      case TOKEN.LBRACKET:\n        return this.parseList()\n      case TOKEN.LBRACE:\n        return this.parseMap()\n    }\n\n    throw parseError('unexpected_token', `Unexpected token: ${TOKEN_BY_NUMBER[this.type]}`, {\n      pos: this.pos,\n      start: this.pos,\n      end: this.lexer.pos,\n      input: this.input\n    })\n  }\n\n  #consumeLiteral() {\n    return this.#advanceToken(this.#node(this.pos, this.lexer.pos, OPS.value, this.value))\n  }\n\n  #parseIdentifierPrimary() {\n    const value = this.value\n    const end = this.lexer.pos\n    const start = this.consume(TOKEN.IDENTIFIER)\n    if (RESERVED.has(value)) {\n      throw parseError('reserved_identifier', `Reserved identifier: ${value}`, {\n        pos: start,\n        start,\n        end,\n        input: this.input\n      })\n    }\n\n    if (!this.match(TOKEN.LPAREN)) return this.#node(start, end, OPS.id, value)\n    this.#advanceToken()\n    const args = this.parseArgumentList()\n    const closeEnd = this.lexer.pos\n    this.consume(TOKEN.RPAREN)\n    return this.#expandMacro(start, closeEnd, OPS.call, [value, args])\n  }\n\n  #parseParenthesizedExpression() {\n    this.consume(TOKEN.LPAREN)\n    const expr = this.parseExpression()\n    this.consume(TOKEN.RPAREN)\n    return expr\n  }\n\n  parseList() {\n    const start = this.consume(TOKEN.LBRACKET)\n    const elements = []\n    let remainingElements = this.limits.maxListElements\n\n    if (!this.match(TOKEN.RBRACKET)) {\n      elements.push(this.parseExpression())\n      if (!remainingElements--) this.#limitExceeded('maxListElements', elements.at(-1).pos)\n      while (this.match(TOKEN.COMMA)) {\n        this.#advanceToken()\n        if (this.match(TOKEN.RBRACKET)) break\n        elements.push(this.parseExpression())\n        if (!remainingElements--) this.#limitExceeded('maxListElements', elements.at(-1).pos)\n      }\n    }\n\n    const closeEnd = this.lexer.pos\n    this.consume(TOKEN.RBRACKET)\n    return this.#node(start, closeEnd, OPS.list, elements)\n  }\n\n  parseMap() {\n    const start = this.consume(TOKEN.LBRACE)\n    const props = []\n    let remainingEntries = this.limits.maxMapEntries\n\n    if (!this.match(TOKEN.RBRACE)) {\n      props.push(this.parseProperty())\n      if (!remainingEntries--) this.#limitExceeded('maxMapEntries', props.at(-1)[0].pos)\n      while (this.match(TOKEN.COMMA)) {\n        this.#advanceToken()\n        if (this.match(TOKEN.RBRACE)) break\n        props.push(this.parseProperty())\n        if (!remainingEntries--) this.#limitExceeded('maxMapEntries', props.at(-1)[0].pos)\n      }\n    }\n\n    const closeEnd = this.lexer.pos\n    this.consume(TOKEN.RBRACE)\n    return this.#node(start, closeEnd, OPS.map, props)\n  }\n\n  parseProperty() {\n    return [this.parseExpression(), (this.consume(TOKEN.COLON), this.parseExpression())]\n  }\n\n  parseArgumentList() {\n    const args = []\n    let remainingArgs = this.limits.maxCallArguments\n\n    if (!this.match(TOKEN.RPAREN)) {\n      args.push(this.parseExpression())\n      if (!remainingArgs--) this.#limitExceeded('maxCallArguments', args.at(-1).pos)\n      while (this.match(TOKEN.COMMA)) {\n        this.#advanceToken()\n        if (this.match(TOKEN.RPAREN)) break\n        args.push(this.parseExpression())\n        if (!remainingArgs--) this.#limitExceeded('maxCallArguments', args.at(-1).pos)\n      }\n    }\n    return args\n  }\n}\n","import {objFreeze, objKeys} from './globals.js'\n\nconst DEFAULT_LIMITS = objFreeze({\n  maxAstNodes: 100000,\n  maxDepth: 250,\n  maxListElements: 1000,\n  maxMapEntries: 1000,\n  maxCallArguments: 32\n})\n\nconst LIMIT_KEYS = new Set(objKeys(DEFAULT_LIMITS))\nfunction createLimits(overrides, base = DEFAULT_LIMITS) {\n  const keys = overrides ? objKeys(overrides) : undefined\n  if (!keys?.length) return base\n\n  const merged = {...base}\n  for (const key of keys) {\n    if (!LIMIT_KEYS.has(key)) throw new TypeError(`Unknown limits option: ${key}`)\n    const value = overrides[key]\n    if (typeof value !== 'number') continue\n    merged[key] = value\n  }\n  return objFreeze(merged)\n}\n\nconst DEFAULT_OPTIONS = objFreeze({\n  unlistedVariablesAreDyn: false,\n  homogeneousAggregateLiterals: true,\n  enableOptionalTypes: false,\n  limits: DEFAULT_LIMITS\n})\n\nfunction bool(a, b, key) {\n  const value = a?.[key] ?? b?.[key]\n  if (typeof value !== 'boolean') throw new TypeError(`Invalid option: ${key}`)\n  return value\n}\n\nexport function createOptions(opts, base = DEFAULT_OPTIONS) {\n  if (!opts) return base\n  return objFreeze({\n    unlistedVariablesAreDyn: bool(opts, base, 'unlistedVariablesAreDyn'),\n    homogeneousAggregateLiterals: bool(opts, base, 'homogeneousAggregateLiterals'),\n    enableOptionalTypes: bool(opts, base, 'enableOptionalTypes'),\n    limits: createLimits(opts.limits, base.limits)\n  })\n}\n","import {createRegistry, RootContext} from './registry.js'\nimport {evaluationError} from './errors.js'\nimport {registerFunctions, Duration, UnsignedInt} from './functions.js'\nimport {registerMacros} from './macros.js'\nimport {registerOverloads} from './overloads.js'\nimport {TypeChecker} from './type-checker.js'\nimport {Parser} from './parser.js'\nimport {createOptions} from './options.js'\nimport {Base} from './operators.js'\n\nconst globalRegistry = createRegistry({enableOptionalTypes: false})\nregisterFunctions(globalRegistry)\nregisterOverloads(globalRegistry)\nregisterMacros(globalRegistry)\n\nclass Environment {\n  #registry\n  #evaluator\n  #typeChecker\n  #evalTypeChecker\n  #parser\n\n  constructor(opts, inherited) {\n    this.opts = createOptions(opts, inherited?.opts)\n    this.#registry = (\n      inherited instanceof Environment ? inherited.#registry : globalRegistry\n    ).clone(this.opts)\n\n    const childOpts = {registry: this.#registry, opts: this.opts}\n    this.#typeChecker = new TypeChecker(childOpts)\n    this.#evalTypeChecker = new TypeChecker(childOpts, true)\n    this.#evaluator = new Evaluator(childOpts)\n    this.#parser = new Parser(this.opts.limits, this.#registry)\n    Object.freeze(this)\n  }\n\n  clone(opts) {\n    return new Environment(opts, this)\n  }\n\n  registerFunction(signature, handler, opts) {\n    this.#registry.registerFunctionOverload(signature, handler, opts)\n    return this\n  }\n\n  registerOperator(string, handler, opts) {\n    this.#registry.registerOperatorOverload(string, handler, opts)\n    return this\n  }\n\n  registerType(typename, constructor) {\n    this.#registry.registerType(typename, constructor)\n    return this\n  }\n\n  registerVariable(name, type, opts) {\n    this.#registry.registerVariable(name, type, opts)\n    return this\n  }\n\n  registerConstant(name, type, value) {\n    this.#registry.registerConstant(name, type, value)\n    return this\n  }\n\n  hasVariable(name) {\n    return this.#registry.variables.has(name)\n  }\n\n  getDefinitions() {\n    return this.#registry.getDefinitions()\n  }\n\n  check(expression) {\n    try {\n      return this.#checkAST(this.#parser.parse(expression))\n    } catch (error) {\n      return {valid: false, error}\n    }\n  }\n\n  #checkAST(ast) {\n    try {\n      const typeDecl = this.#typeChecker.check(ast, new RootContext(this.#registry))\n      return {valid: true, type: this.#formatTypeForCheck(typeDecl)}\n    } catch (error) {\n      return {valid: false, error}\n    }\n  }\n\n  #formatTypeForCheck(typeDecl) {\n    if (typeDecl.name === `list<dyn>`) return 'list'\n    if (typeDecl.name === `map<dyn, dyn>`) return 'map'\n    return typeDecl.name\n  }\n\n  parse(expression) {\n    const ast = this.#parser.parse(expression)\n    const evaluateParsed = this.#evaluateAST.bind(this, ast)\n    evaluateParsed.check = this.#checkAST.bind(this, ast)\n    evaluateParsed.ast = ast\n    return evaluateParsed\n  }\n\n  evaluate(expression, context) {\n    return this.#evaluateAST(this.#parser.parse(expression), context)\n  }\n\n  #evaluateAST(ast, ctx) {\n    if (ast.checkedType) {\n      return ast.evaluate(this.#evaluator, ast, new RootContext(this.#registry, ctx))\n    } else {\n      this.#evalTypeChecker.check(ast, (ctx = new RootContext(this.#registry, ctx)))\n      return ast.evaluate(this.#evaluator, ast, ctx)\n    }\n  }\n}\n\nclass Evaluator extends Base {\n  constructor(opts) {\n    super(opts)\n    this.createError = evaluationError\n  }\n\n  #firstMapElement(coll) {\n    if (coll instanceof Map) return coll.entries().next().value\n    for (const key in coll) return [key, coll[key]]\n  }\n\n  debugRuntimeType(value, checkedType) {\n    return checkedType?.hasDynType === false ? checkedType : this.debugTypeDeep(value)\n  }\n\n  debugTypeDeep(value) {\n    const runtimeType = this.debugType(value)\n    switch (runtimeType.kind) {\n      case 'list': {\n        const first = value instanceof Array ? value[0] : value.values().next().value\n        if (first === undefined) return runtimeType\n        return this.registry.getListType(this.debugTypeDeep(first))\n      }\n      case 'map': {\n        const first = this.#firstMapElement(value)\n        if (!first) return runtimeType\n        return this.registry.getMapType(\n          runtimeType.keyType.hasDynType ? this.debugTypeDeep(first[0]) : runtimeType.keyType,\n          runtimeType.valueType.hasDynType ? this.debugTypeDeep(first[1]) : runtimeType.valueType\n        )\n      }\n      default:\n        return runtimeType\n    }\n  }\n\n  tryEval(ast, ctx) {\n    try {\n      const res = this.run(ast, ctx)\n      if (res instanceof Promise) return res.catch((err) => err)\n      return res\n    } catch (err) {\n      return err\n    }\n  }\n\n  run(ast, ctx) {\n    return ast.evaluate(this, ast, ctx)\n  }\n}\n\nconst globalEnvironment = new Environment({\n  unlistedVariablesAreDyn: true\n})\n\nexport function parse(expression) {\n  return globalEnvironment.parse(expression)\n}\n\nexport function evaluate(expression, context) {\n  return globalEnvironment.evaluate(expression, context)\n}\n\nexport function check(expression) {\n  return globalEnvironment.check(expression)\n}\n\nexport {Duration, UnsignedInt, Environment}\n\nexport default {\n  parse,\n  evaluate,\n  check,\n  Environment,\n  Duration,\n  UnsignedInt\n}\n","/**\n * Runtime counterpart of the type-level grammar. Authors write aggregates the way schema\n * expressions spell them (`ANY(inputs.lines.qty > 1)`, `SUM(inputs.lines.qty)`,\n * `COUNT(inputs.lines)`); the wire carries standard CEL so the console needs no custom macros:\n *\n *   COUNT(inputs.X)            → size(inputs.X)\n *   SUM|MIN|MAX(inputs.X.f)    → SUM|MIN|MAX(inputs.X.map(row, row.f))\n *   ANY|ALL(body)              → inputs.X.exists|all(row, body')   with inputs.X.f → row.f in body'\n *\n * Everything else passes through verbatim. The same structural rules as the type-level checker\n * are enforced (one iterator per quantifier, row paths only inside aggregates) so an expression\n * that bypassed TypeScript still fails at page render with a clear message.\n */\n\ntype Tok =\n  | { kind: \"id\"; text: string }\n  | { kind: \"str\"; text: string; raw: string }\n  | { kind: \"num\"; text: string }\n  | { kind: \"op\"; text: string };\n\nconst TWO_CHAR = [\"==\", \"!=\", \"<=\", \">=\", \"&&\", \"||\"];\nconst ONE_CHAR = \"<>!()[],.\";\n\nexport function tokenize(source: string): Tok[] {\n  const toks: Tok[] = [];\n  let i = 0;\n  while (i < source.length) {\n    const c = source[i];\n    if (/\\s/.test(c)) {\n      i++;\n      continue;\n    }\n    const two = source.slice(i, i + 2);\n    if (TWO_CHAR.includes(two)) {\n      toks.push({ kind: \"op\", text: two });\n      i += 2;\n      continue;\n    }\n    if (ONE_CHAR.includes(c)) {\n      toks.push({ kind: \"op\", text: c });\n      i++;\n      continue;\n    }\n    if (c === '\"' || c === \"'\") {\n      let j = i + 1;\n      while (j < source.length && source[j] !== c) j++;\n      if (j >= source.length)\n        throw new Error(`Unterminated string in visibility expression`);\n      toks.push({\n        kind: \"str\",\n        text: source.slice(i + 1, j),\n        raw: source.slice(i, j + 1),\n      });\n      i = j + 1;\n      continue;\n    }\n    const num = /^-?\\d+(\\.\\d+)?/.exec(source.slice(i));\n    if (num && (c !== \"-\" || /\\d/.test(source[i + 1] ?? \"\"))) {\n      toks.push({ kind: \"num\", text: num[0] });\n      i += num[0].length;\n      continue;\n    }\n    const id = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));\n    if (id) {\n      toks.push({ kind: \"id\", text: id[0] });\n      i += id[0].length;\n      continue;\n    }\n    throw new Error(`Unexpected character '${c}' in visibility expression`);\n  }\n  return toks;\n}\n\nexport const AGGREGATES = [\"COUNT\", \"ANY\", \"ALL\", \"SUM\", \"MIN\", \"MAX\"] as const;\ntype Aggregate = (typeof AGGREGATES)[number];\n\n/** Keel text functions and the CEL receiver methods they become on the wire. */\nexport const STRING_FNS: Record<string, string> = {\n  STARTSWITH: \"startsWith\",\n  ENDSWITH: \"endsWith\",\n  CONTAINS: \"contains\",\n  MATCHES: \"matches\",\n};\nconst methodToFn = (method: string): string | undefined =>\n  Object.keys(STRING_FNS).find((fn) => STRING_FNS[fn] === method);\n\nconst isOp = (t: Tok | undefined, text: string) =>\n  t?.kind === \"op\" && t.text === text;\nconst isId = (t: Tok | undefined, text?: string) =>\n  t?.kind === \"id\" && (text === undefined || t.text === text);\n\n/** A reference `inputs.<key>` or `inputs[\"<key>\"]`, optionally followed by a second key. */\ntype Ref = {\n  key: string;\n  field?: string;\n  end: number;\n  keyBracket: boolean;\n  fieldBracket: boolean;\n};\n\nfunction readKey(\n  toks: Tok[],\n  at: number\n): { key: string; bracket: boolean; end: number } | null {\n  if (isOp(toks[at], \".\") && isId(toks[at + 1])) {\n    return { key: toks[at + 1].text, bracket: false, end: at + 2 };\n  }\n  if (\n    isOp(toks[at], \"[\") &&\n    toks[at + 1]?.kind === \"str\" &&\n    isOp(toks[at + 2], \"]\")\n  ) {\n    return { key: toks[at + 1].text, bracket: true, end: at + 3 };\n  }\n  return null;\n}\n\nfunction readRef(toks: Tok[], at: number, iterators: Set<string>): Ref | null {\n  if (!isId(toks[at], \"inputs\")) return null;\n  const k = readKey(toks, at + 1);\n  if (!k) return null;\n  const ref: Ref = {\n    key: k.key,\n    end: k.end,\n    keyBracket: k.bracket,\n    fieldBracket: false,\n  };\n  if (iterators.has(k.key)) {\n    const f = readKey(toks, k.end);\n    if (f) {\n      ref.field = f.key;\n      ref.fieldBracket = f.bracket;\n      ref.end = f.end;\n    }\n  }\n  return ref;\n}\n\nconst quote = (s: string) => JSON.stringify(s);\nconst member = (base: string, key: string, bracket: boolean) =>\n  bracket || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)\n    ? `${base}[${quote(key)}]`\n    : `${base}.${key}`;\n\n// Index of the \")\" that closes the \"(\" at `open`.\nfunction closing(toks: Tok[], open: number): number {\n  let depth = 0;\n  for (let i = open; i < toks.length; i++) {\n    if (isOp(toks[i], \"(\")) depth++;\n    else if (isOp(toks[i], \")\") && --depth === 0) return i;\n  }\n  throw new Error(\"Expected ')' in visibility expression\");\n}\n\nfunction emit(t: Tok): string {\n  return t.kind === \"str\" ? quote(t.text) : t.text;\n}\n\n/**\n * Rewrites the tokens in [from, to) to CEL. `quantified` is the iterator whose row paths become\n * `row.<field>`; outside an ANY/ALL body it is null and row paths are an error.\n */\nfunction render(\n  toks: Tok[],\n  from: number,\n  to: number,\n  iterators: Set<string>,\n  quantified: string | null\n): string {\n  const out: string[] = [];\n  let i = from;\n  while (i < to) {\n    const t = toks[i];\n    // aggregate call\n    if (\n      t.kind === \"id\" &&\n      (AGGREGATES as readonly string[]).includes(t.text) &&\n      isOp(toks[i + 1], \"(\")\n    ) {\n      const fn = t.text as Aggregate;\n      const close = closing(toks, i + 1);\n      const bodyFrom = i + 2;\n      if (fn === \"COUNT\") {\n        const ref = readRef(toks, bodyFrom, iterators);\n        if (\n          !ref ||\n          ref.field !== undefined ||\n          !iterators.has(ref.key) ||\n          ref.end !== close\n        ) {\n          throw new Error(\n            \"COUNT() takes an iterator, e.g. COUNT(inputs.lines)\"\n          );\n        }\n        out.push(`size(${member(\"inputs\", ref.key, ref.keyBracket)})`);\n      } else if (fn === \"SUM\" || fn === \"MIN\" || fn === \"MAX\") {\n        const ref = readRef(toks, bodyFrom, iterators);\n        if (\n          !ref ||\n          !iterators.has(ref.key) ||\n          ref.field === undefined ||\n          ref.end !== close\n        ) {\n          throw new Error(\n            `${fn}() takes a row field, e.g. ${fn}(inputs.lines.qty)`\n          );\n        }\n        out.push(\n          `${fn}(${member(\"inputs\", ref.key, ref.keyBracket)}.map(row, ${member(\"row\", ref.field, ref.fieldBracket)}))`\n        );\n      } else {\n        const found = new Set<string>();\n        for (let j = bodyFrom; j < close; j++) {\n          const ref = readRef(toks, j, iterators);\n          if (ref && ref.field !== undefined) found.add(ref.key);\n        }\n        if (found.size === 0)\n          throw new Error(\n            `${fn}(...) must reference a row field such as inputs.lines.qty`\n          );\n        if (found.size > 1) {\n          throw new Error(\n            `${fn}(...) may only reference one iterator; found ${[...found].map((n) => `'${n}'`).join(\" | \")}`\n          );\n        }\n        const iter = [...found][0];\n        const body = render(toks, bodyFrom, close, iterators, iter);\n        out.push(\n          `${member(\"inputs\", iter, false)}.${fn === \"ANY\" ? \"exists\" : \"all\"}(row, ${body})`\n        );\n      }\n      i = close + 1;\n      continue;\n    }\n    // number list: cel-js list literals are homogeneous, so [1, 2.5] is written as [1.0, 2.5]\n    if (isOp(t, \"[\")) {\n      const close = toks.findIndex((x, j) => j > i && isOp(x, \"]\"));\n      const items = toks.slice(i + 1, close).filter((x) => !isOp(x, \",\"));\n      if (\n        close > i &&\n        items.length &&\n        items.every((x) => x.kind === \"num\") &&\n        items.some((x) => x.text.includes(\".\"))\n      ) {\n        out.push(\"[\");\n        for (let j = i + 1; j < close; j++) {\n          const x = toks[j];\n          out.push(\n            x.kind === \"num\" && !x.text.includes(\".\") ? `${x.text}.0` : emit(x)\n          );\n        }\n        out.push(\"]\");\n        i = close + 1;\n        continue;\n      }\n    }\n    // text function: STARTSWITH(inputs.code, \"D-\") → inputs.code.startsWith(\"D-\")\n    if (t.kind === \"id\" && t.text in STRING_FNS && isOp(toks[i + 1], \"(\")) {\n      const ref = readRef(toks, i + 2, iterators);\n      const lit = ref ? toks[ref.end + 1] : undefined;\n      if (\n        !ref ||\n        !isOp(toks[ref.end], \",\") ||\n        lit?.kind !== \"str\" ||\n        !isOp(toks[ref.end + 2], \")\")\n      ) {\n        throw new Error(\n          `${t.text}() takes a field and one quoted string, e.g. ${t.text}(inputs.code, \"abc\")`\n        );\n      }\n      out.push(\n        `${renderRef(ref, quantified)}.${STRING_FNS[t.text]}(${quote(lit.text)})`\n      );\n      i = ref.end + 3;\n      continue;\n    }\n    // input / iterator / row reference\n    const ref = readRef(toks, i, iterators);\n    if (ref) {\n      // a CEL-style method on a reference is not part of the author grammar\n      if (\n        isOp(toks[ref.end], \".\") &&\n        isId(toks[ref.end + 1]) &&\n        isOp(toks[ref.end + 2], \"(\")\n      ) {\n        const m = toks[ref.end + 1].text;\n        const fn = methodToFn(m);\n        throw new Error(\n          fn\n            ? `Methods are not supported; write ${fn}(inputs.${ref.field ?? ref.key}, \"...\") instead`\n            : `Unknown function '${m}'; text fields support STARTSWITH, ENDSWITH, CONTAINS and MATCHES`\n        );\n      }\n      out.push(renderRef(ref, quantified));\n      i = ref.end;\n      continue;\n    }\n    out.push(emit(t));\n    i++;\n  }\n  return joinTokens(out);\n}\n\n// A reference as CEL: `inputs.x`, or `row.f` for the quantified iterator's row field.\nfunction renderRef(ref: Ref, quantified: string | null): string {\n  if (ref.field !== undefined) {\n    if (quantified !== ref.key) {\n      throw new Error(\n        `inputs.${ref.key}.${ref.field} can only be used inside ANY, ALL, SUM, MIN or MAX`\n      );\n    }\n    return member(\"row\", ref.field, ref.fieldBracket);\n  }\n  return member(\"inputs\", ref.key, ref.keyBracket);\n}\n\n// Re-space the output the way an author would write it: no space around \".\", none inside brackets\n// or before a call's \"(\", one space around binary operators and after commas.\nfunction joinTokens(parts: string[]): string {\n  let s = \"\";\n  for (let i = 0; i < parts.length; i++) {\n    const p = parts[i];\n    const prev = parts[i - 1];\n    const callParen =\n      p === \"(\" &&\n      prev !== undefined &&\n      /[A-Za-z0-9_\\]\"]$/.test(prev) &&\n      prev !== \"in\";\n    const noSpace =\n      prev === undefined ||\n      p === \")\" ||\n      p === \"]\" ||\n      p === \",\" ||\n      p === \".\" ||\n      prev === \".\" ||\n      prev === \"(\" ||\n      prev === \"[\" ||\n      prev === \"!\" ||\n      callParen;\n    s += noSpace ? p : \" \" + p;\n  }\n  return s;\n}\n\n/**\n * Transpiles an author-facing visibility expression to the CEL string sent to the client.\n * `iterators` are the names of the iterators in the scope (empty for an iterator's own rules).\n */\nexport function transpile(\n  expression: string,\n  iterators: Iterable<string>\n): string {\n  const iters = new Set(iterators);\n  const toks = tokenize(expression);\n  return render(toks, 0, toks.length, iters, null);\n}\n","import type {\n  DisplayElementResponse,\n  ImplementationResponse,\n  InputElementResponse,\n  IteratorElementResponse,\n  UIElements,\n} from \".\";\nimport type { CelExpression } from \"./cel\";\nimport type { Rows, ScopeKind, scopeBrand } from \"./cel/types\";\n\nimport { Environment, EvaluationError } from \"@marcbachmann/cel-js\";\nimport { transpile } from \"./cel/transpile\";\n\n/* ********************\n * Wire format\n ******************* */\n\n/**\n * An element's `visible` property is a CEL expression over the inputs of the scope the element\n * lives in (the page, or the iterator row). The console re-evaluates it whenever the form changes;\n * the runtime evaluates it once on submit to skip validation of, and strip values from, hidden\n * elements. Inputs are referenced as `inputs.name` (or `inputs[\"name\"]`). Both sides evaluate with\n * @marcbachmann/cel-js against a context `{ inputs: {...} }` holding every input of the scope (null\n * when the form has no value), treating an evaluation error as \"hidden\".\n */\nexport type VisibilityExpression = string;\n\n/* ********************\n * Author-facing types\n ******************* */\n\ntype InputNames<T extends UIElements> = Extract<\n  T[number],\n  InputElementResponse<string, any, any>\n>[\"name\"];\n\n/** Everything a rule can target: inputs and iterators by name, display elements by `key`. */\nexport type VisibilityTargets<T extends UIElements> =\n  | InputNames<T>\n  | Extract<T[number], IteratorElementResponse<string, any, any>>[\"name\"]\n  | Extract<T[number], DisplayElementResponse<string>>[\"key\"];\n\ntype IteratorNames<T extends UIElements> = Extract<\n  T[number],\n  IteratorElementResponse<string, any, any>\n>[\"name\"];\n\n/**\n * The members of a scope as `{ name: valueType }`, the context a CEL string is checked against.\n * Inputs map to their value type; iterators map to a branded `Rows` of their row context so\n * aggregates can type their row fields. The scope brand says whether aggregates are allowed.\n */\nexport type CelCtx<T extends UIElements, Scope extends ScopeKind = \"page\"> = {\n  [K in InputNames<T>]: Extract<\n    T[number],\n    InputElementResponse<K, any, any>\n  >[\"valueType\"];\n} & {\n  [K in IteratorNames<T>]: Rows<IteratorRowCtx<T, K>>;\n} & { readonly [scopeBrand]: Scope };\n\n// The row context of iterator `K`: its content elements, in row scope.\ntype IteratorRowCtx<T extends UIElements, K extends string> =\n  Extract<\n    T[number],\n    IteratorElementResponse<K, any, any>\n  > extends IteratorElementResponse<K, infer E extends UIElements, any>\n    ? CelCtx<E, \"row\">\n    : never;\n\n/**\n * The `visibility` option of a page or iterator: one CEL expression per target element. `V` is\n * the inferred (const) type of the object written by the author, so each string literal can be\n * checked by the type-level CEL parser and replaced by its error message when invalid; the error\n * then lands on that property. \"Is set\" is spelled `inputs.x != null && inputs.x != \"\"` for text\n * fields and `inputs.x != null && size(inputs.x) > 0` for lists.\n */\nexport type VisibilityInput<\n  T extends UIElements,\n  V,\n  Scope extends ScopeKind = \"page\",\n> = {\n  [K in keyof V]: K extends VisibilityTargets<T>\n    ? V[K] extends string\n      ? CelExpression<V[K], CelCtx<T, Scope>>\n      : `Visibility rules are CEL strings, e.g. \"inputs.hasDiscount == true\"`\n    : `Unknown visibility target '${K & string}'`;\n};\n\n/* ********************\n * Implementation\n ******************* */\n\n/** The names of the inputs and iterators among a scope's elements, keyed by kind. */\nexport type ScopeMembers = { inputs: string[]; iterators: string[] };\n\nconst membersOf = (resolved: any[]): ScopeMembers => ({\n  inputs: resolved\n    .filter((e) => e?.__type === \"input\" && e.uiConfig?.name)\n    .map((e) => e.uiConfig.name as string),\n  iterators: resolved\n    .filter((e) => e?.__type === \"iterator\" && e.uiConfig?.name)\n    .map((e) => e.uiConfig.name as string),\n});\n\n// Every input of the scope is exposed under one `inputs` map variable, so input names can never\n// collide with CEL keywords, builtin type names or roots reserved for later (`ctx`). It is `dyn`\n// because form values are untyped JSON and CEL's own checker would otherwise reject\n// `inputs.x != null` on a typed field.\nconst environment = new Environment();\nenvironment.registerVariable(\"inputs\", \"dyn\");\n\n// Numeric aggregates over a row field, as produced by the transpiler (`SUM(inputs.lines.map(row,\n// row.qty))`). Nulls are skipped; an empty sum is 0 and an empty min/max is null, which makes any\n// comparison error and so hides the element. Declared `dyn` so `SUM(...) == 7` compares across\n// int and double like a variable does. The console registers the same three.\nconst numbers = (list: unknown[]): number[] =>\n  list.filter((v) => v !== null && v !== undefined).map(Number);\nenvironment.registerFunction(\"SUM(list): dyn\", (list: unknown[]) =>\n  numbers(list).reduce((a, b) => a + b, 0)\n);\nenvironment.registerFunction(\"MIN(list): dyn\", (list: unknown[]) => {\n  const n = numbers(list);\n  return n.length ? Math.min(...n) : null;\n});\nenvironment.registerFunction(\"MAX(list): dyn\", (list: unknown[]) => {\n  const n = numbers(list);\n  return n.length ? Math.max(...n) : null;\n});\n\n/**\n * Builds the evaluation context: every input of the scope (`null` when the form has no value) and\n * every iterator (`[]` when it has no rows), all under the `inputs` map.\n */\nconst contextFor = (\n  members: ScopeMembers,\n  data: Record<string, unknown> | null | undefined\n): { inputs: Record<string, unknown> } => {\n  const values: Record<string, unknown> = {};\n  for (const n of members.inputs) values[n] = data?.[n] ?? null;\n  for (const n of members.iterators) {\n    const rows = data?.[n];\n    values[n] = Array.isArray(rows) ? rows : [];\n  }\n  return { inputs: values };\n};\n\n/**\n * Writes each rule onto its target element's `uiConfig.visible`. Inputs and iterators are matched\n * by name, display elements by their `key`. Every expression is checked against the scope's inputs\n * so a bad one fails when the page renders rather than silently hiding the element; the type-level\n * checker should make that unreachable for literals written in flow code.\n */\nexport async function applyVisibility(\n  elements: ImplementationResponse<any, any>[],\n  rules: Record<string, VisibilityExpression | undefined> | undefined\n): Promise<void> {\n  if (!rules) return;\n  const resolved = (await Promise.all(elements)) as any[];\n  const members = membersOf(resolved);\n\n  for (const [target, rule] of Object.entries(rules)) {\n    if (rule === undefined) continue;\n    const element = resolved.find((e) =>\n      e?.__type ? e.uiConfig?.name === target : e?.key === target\n    );\n    if (!element) {\n      throw new Error(\n        `visibility rule targets \"${target}\" but no input, iterator or display element with that name or key exists`\n      );\n    }\n    let expression: string;\n    try {\n      expression = transpile(rule, members.iterators);\n    } catch (e) {\n      throw new Error(\n        `visibility rule for \"${target}\" is not a valid expression: ${e instanceof Error ? e.message : String(e)}`\n      );\n    }\n    const result = environment.check(expression);\n    if (!result.valid) {\n      throw new Error(\n        `visibility rule for \"${target}\" is not a valid expression: ${result.error?.message ?? expression}`\n      );\n    }\n    element.uiConfig.visible = expression;\n  }\n}\n\n/**\n * Evaluates a visibility expression against the form data of its scope. `inputs` are the names of\n * every input in the scope; absent ones are passed as null so a rule can test them. Mirrors the\n * console's evaluation: any evaluation error means the element is hidden.\n */\nexport function evaluateVisibility(\n  expression: VisibilityExpression,\n  members: ScopeMembers,\n  data: Record<string, unknown> | null | undefined\n): boolean {\n  try {\n    return environment.evaluate(expression, contextFor(members, data)) === true;\n  } catch (e) {\n    if (e instanceof EvaluationError) return false;\n    throw e;\n  }\n}\n\n/** Whether an element carrying `visible` should be shown for the given scope data. */\nexport function isVisible(\n  uiConfig: { visible?: VisibilityExpression } | undefined,\n  members: ScopeMembers,\n  data: Record<string, unknown> | null | undefined\n): boolean {\n  if (!uiConfig?.visible) return true;\n  return evaluateVisibility(uiConfig.visible, members, data);\n}\n\n/** The inputs and iterators among a scope's elements, for building an evaluation context. */\nexport const scopeMembers = async (\n  elements: ImplementationResponse<any, any>[]\n): Promise<ScopeMembers> => membersOf((await Promise.all(elements)) as any[]);\n","import { FlowConfig, ExtractStageKeys } from \"..\";\nimport {\n  BaseUiDisplayResponse,\n  ImplementationResponse,\n  InputElementImplementationResponse,\n  InputElementResponse,\n  IteratorElementImplementationResponse,\n  IteratorElementResponse,\n  UiElementApiResponse,\n  UiElementApiResponses,\n  UIElements,\n  ValidateFn,\n} from \".\";\nimport {\n  applyVisibility,\n  isVisible,\n  scopeMembers,\n  VisibilityInput,\n} from \"./visibility\";\n\ntype PageOptions<\n  C extends FlowConfig,\n  A extends PageActions[],\n  T extends UIElements,\n  V,\n> = {\n  stage?: ExtractStageKeys<C>;\n  title?: string;\n  description?: string;\n  content: T;\n  /**\n   * Show elements only while a CEL expression over the page's other inputs holds, e.g.\n   * `{ discountCode: \"inputs.hasDiscount == true\" }`. Keys are input and iterator names and display\n   * element `key`s. Expressions are checked against the page's inputs as you type. Hidden inputs\n   * are not validated and are absent from the result.\n   */\n  visibility?: VisibilityInput<T, V>;\n  validate?: ValidateFn<ExtractFormData<T>>;\n  actions?: A;\n  // When true, let the use go back a step if there is a previous step\n  allowBack?: boolean;\n  fullWidth?: boolean;\n};\n\nexport type UiPage<C extends FlowConfig> = <\n  T extends UIElements,\n  const A extends PageActions[] = [],\n  const V = {},\n>(\n  name: string,\n  options: PageOptions<C, A, T, V>\n) => Promise<\n  A[\"length\"] extends 0\n    ? ExtractFormData<T, keyof V>\n    : { data: ExtractFormData<T, keyof V>; action: ActionValue<A[number]> }\n>;\n\ntype PageActions = string | PageActionConfig;\ntype PageActionConfig = {\n  label: string;\n  value: string;\n  mode?: \"primary\" | \"secondary\" | \"destructive\";\n  /**\n   * Keyboard shortcut for this action.\n   *\n   * @example\n   * // Single key\n   * hotkey: \"1\"\n   * hotkey: \"enter\"\n   * hotkey: \"space\"\n   * hotkey: \"F1\"\n   *\n   *\n   * // With modifier:\n   * // shift, alt + mod (cmd on macOS, ctrl on Windows/Linux)\n   *\n   * hotkey: \"mod+s\"           // cmd+s on macOS, ctrl+s on Windows/Linux\n   * hotkey: \"mod+shift+enter\" // cmd+shift+enter on macOS, ctrl+shift+enter on Windows/Linux\n   *\n   * // With behavior control\n   * hotkey: {\n   *   key: \"mod+enter\",\n   *   behaviour: \"includeForms\"  // Trigger even when focused on form elements\n   * }\n   */\n  hotkey?: string | HotkeyConfig;\n};\n\ntype HotkeyConfig = {\n  key: string;\n  /** If the hotkey should be triggered when the user is on a form element or not\n   *\n   * @default \"excludeForms\"\n   */\n  behaviour?: \"includeForms\" | \"excludeForms\";\n};\n\nexport interface UiPageApiResponse extends Omit<\n  BaseUiDisplayResponse<\"ui.page\">,\n  \"visible\"\n> {\n  stage?: string;\n  title?: string;\n  description?: string;\n  actions?: PageActionConfig[];\n  content: UiElementApiResponses;\n  hasValidationErrors: boolean;\n  validationError?: string;\n  allowBack?: boolean;\n  fullWidth?: boolean;\n}\n\n// Walk a page's content and let each input element hydrate its slice of the\n// submitted data via its own `getData` hook. Iterator content recurses per row.\nexport async function applyElementGetData(\n  content: ImplementationResponse<any, any>[] | undefined,\n  data: any\n): Promise<any> {\n  if (!data || typeof data !== \"object\" || !Array.isArray(content)) return data;\n\n  for (const c of content) {\n    const resolved = (await c) as any;\n    if (!resolved || !(\"__type\" in resolved)) continue;\n\n    const name = resolved.uiConfig?.name;\n    if (!name || !(name in data)) continue;\n\n    if (resolved.__type === \"input\" && typeof resolved.getData === \"function\") {\n      data[name] = resolved.getData(data[name]);\n    } else if (resolved.__type === \"iterator\") {\n      const rows = data[name];\n      const inner = resolved.uiConfig?.content as\n        | ImplementationResponse<any, any>[]\n        | undefined;\n      if (Array.isArray(rows) && Array.isArray(inner)) {\n        for (let i = 0; i < rows.length; i++) {\n          rows[i] = await applyElementGetData(inner, rows[i]);\n        }\n      }\n    }\n  }\n  return data;\n}\n\n// Iterator-scoped element identifiers are encoded as `<iteratorName>[<index>]:<elementName>`.\n// Top-level elements just use their plain name. Encoding/decoding lives here so the rest of the\n// stack (HTTP handler, Go orchestrator, bun bridge) can treat the element as an opaque string.\nconst ITERATOR_SCOPED_ELEMENT = /^([^[]+)\\[(\\d+)\\]:(.+)$/;\n\nexport async function callbackFn<T extends UIElements>(\n  elements: T,\n  elementPath: string,\n  callbackName: string,\n  data: any\n): Promise<any> {\n  const scoped = ITERATOR_SCOPED_ELEMENT.exec(elementPath);\n  let searchScope: any[] = elements as any[];\n  let elementName = elementPath;\n  let iteratorName: string | null = null;\n\n  if (scoped) {\n    iteratorName = scoped[1];\n    elementName = scoped[3];\n    // Iterator content carries the full implementation responses with their attached\n    // callbacks at runtime, even though the type signature uses UiElementApiResponses.\n    const iter = (elements as any[]).find(\n      (el) =>\n        el?.uiConfig?.__type === \"ui.iterator\" &&\n        el.uiConfig.name === iteratorName\n    );\n    if (!iter) {\n      throw new Error(`Iterator with name ${iteratorName} not found`);\n    }\n    searchScope = iter.uiConfig.content as any[];\n  }\n\n  const element = searchScope.find(\n    (el) => el?.uiConfig && el.uiConfig.name === elementName\n  );\n\n  if (!element) {\n    const where = iteratorName ? ` in iterator ${iteratorName}` : \"\";\n    throw new Error(`Element with name ${elementName} not found${where}`);\n  }\n\n  const cb = (element as any)[callbackName];\n  if (typeof cb !== \"function\") {\n    throw new Error(\n      `Callback ${callbackName} not found on element ${elementName}`\n    );\n  }\n\n  return await cb(data);\n}\n\nexport async function page<\n  C extends FlowConfig,\n  A extends PageActions[],\n  T extends UIElements,\n  V,\n>(\n  options: PageOptions<C, A, T, V>,\n  data: any,\n  action: string | null\n): Promise<{ page: UiPageApiResponse; hasValidationErrors: boolean }> {\n  // Turn these back into the actual response types\n  const content = options.content as unknown as ImplementationResponse<\n    any,\n    any\n  >[];\n  let hasValidationErrors = false;\n  let validationError: string | undefined;\n\n  // Validate actions - all action validation errors are thrown as bad requests\n  if (options.actions && options.actions.length > 0) {\n    // Actions are defined on the page\n    // Normalize action - convert \"undefined\" string or undefined value to null\n    const normalizedAction =\n      action === \"undefined\" || action === undefined ? null : action;\n\n    // Only validate action when data is being submitted (data is not null)\n    if (data !== null) {\n      if (normalizedAction === null) {\n        // No action provided when actions are required during submission\n        const validValues = options.actions\n          .map((a) => {\n            if (typeof a === \"string\") return a;\n            return a && typeof a === \"object\" && \"value\" in a ? a.value : \"\";\n          })\n          .filter(Boolean);\n        throw new Error(\n          `action is required. Valid actions are: ${validValues.join(\", \")}`\n        );\n      }\n\n      // Action provided, check if it's valid\n      const isValidAction = options.actions.some((a) => {\n        if (typeof a === \"string\") return a === normalizedAction;\n        return (\n          a &&\n          typeof a === \"object\" &&\n          \"value\" in a &&\n          a.value === normalizedAction\n        );\n      });\n\n      if (!isValidAction) {\n        // Build list of valid action values\n        const validValues = options.actions\n          .map((a) => {\n            if (typeof a === \"string\") return a;\n            return a && typeof a === \"object\" && \"value\" in a ? a.value : \"\";\n          })\n          .filter(Boolean);\n\n        throw new Error(\n          `invalid action \"${normalizedAction}\". Valid actions are: ${validValues.join(\n            \", \"\n          )}`\n        );\n      }\n    }\n  } else if (\n    action !== null &&\n    action !== undefined &&\n    action !== \"undefined\"\n  ) {\n    // No actions defined but a real action value was provided - this is a bad request\n    throw new Error(\n      `invalid action \"${action}\". No actions are defined for this page`\n    );\n  }\n\n  await applyVisibility(content, options.visibility as any);\n\n  // Hidden elements are neither validated nor part of the submitted data. Strip them before\n  // anything reads `data` so page-level validation and the persisted value agree with the UI.\n  if (data && typeof data === \"object\") {\n    await stripHiddenValues(content, data);\n  }\n\n  const contentUiConfig = await Promise.all(\n    content.map(async (c) => {\n      const resolvedC = await c;\n\n      const elementData =\n        data && typeof data === \"object\" && resolvedC.uiConfig.name in data\n          ? data[resolvedC.uiConfig.name]\n          : undefined;\n\n      const { uiConfig, validationErrors } = await recursivelyProcessElement(\n        c,\n        elementData,\n        options.actions && options.actions.length > 0 ? action : null\n      );\n\n      if (validationErrors) hasValidationErrors = true;\n\n      return uiConfig;\n    })\n  );\n\n  // If there is page level validation, validate the data\n  if (data && options.validate) {\n    const validationResult =\n      options.actions && action !== null\n        ? await (options.validate as any)(data, action)\n        : await (options.validate as any)(data);\n    if (typeof validationResult === \"string\") {\n      hasValidationErrors = true;\n      validationError = validationResult;\n    }\n  }\n\n  return {\n    page: {\n      __type: \"ui.page\",\n      stage: options.stage,\n      title: options.title,\n      description: options.description,\n      content: contentUiConfig,\n      actions: options.actions?.map((a) => {\n        if (typeof a === \"string\") {\n          return { label: a, value: a, mode: \"primary\" };\n        } else if (typeof a === \"object\") {\n          a.mode = a.mode || \"primary\";\n        }\n        return a;\n      }),\n      hasValidationErrors,\n      validationError,\n      allowBack: options.allowBack,\n      fullWidth: options.fullWidth,\n    },\n    hasValidationErrors,\n  };\n}\n\n// Removes the values of elements whose `visible` condition fails for the given scope data.\n// Conditions are evaluated against the data as submitted, before any stripping, so the outcome\n// does not depend on element order.\nconst stripHiddenValues = async (\n  elements: ImplementationResponse<any, any>[],\n  data: Record<string, any>\n): Promise<void> => {\n  const snapshot = { ...data };\n  const members = await scopeMembers(elements);\n  for (const el of elements) {\n    const resolved = (await el) as any;\n    const name = resolved?.uiConfig?.name;\n    if (!name || isVisible(resolved.uiConfig, members, snapshot)) continue;\n    delete data[name];\n  }\n};\n\nconst recursivelyProcessElement = async (\n  c: ImplementationResponse<any, any>,\n  data: any,\n  action: string | null\n): Promise<{ uiConfig: UiElementApiResponse; validationErrors: boolean }> => {\n  const resolvedC = await c;\n  const elementType = \"__type\" in resolvedC ? resolvedC.__type : null;\n\n  switch (elementType) {\n    case \"input\":\n      return processInputElement(\n        resolvedC as InputElementImplementationResponse<any, any>,\n        data,\n        action\n      );\n    case \"iterator\":\n      return processIteratorElement(\n        resolvedC as IteratorElementImplementationResponse<any, any>,\n        data,\n        action\n      );\n    default:\n      return {\n        uiConfig: { ...resolvedC.uiConfig },\n        validationErrors: false,\n      };\n  }\n};\n\nconst processInputElement = async (\n  element: InputElementImplementationResponse<any, any>,\n  data: any,\n  action: string | null\n): Promise<{ uiConfig: UiElementApiResponse; validationErrors: boolean }> => {\n  const hasData = data !== undefined && data !== null;\n\n  if (!hasData || !element.validate) {\n    return {\n      uiConfig: { ...element.uiConfig },\n      validationErrors: false,\n    };\n  }\n\n  const validationError =\n    action !== null\n      ? await (element.validate as any)(data, action)\n      : await (element.validate as any)(data);\n  const hasValidationErrors = typeof validationError === \"string\";\n\n  return {\n    uiConfig: {\n      ...element.uiConfig,\n      validationError: hasValidationErrors ? validationError : undefined,\n    },\n    validationErrors: hasValidationErrors,\n  };\n};\n\nconst processIteratorElement = async (\n  element: any,\n  data: any,\n  action: string | null\n): Promise<{ uiConfig: UiElementApiResponse; validationErrors: boolean }> => {\n  const elements = element.uiConfig.content as ImplementationResponse<\n    any,\n    any\n  >[];\n  const dataArr = data as any[] | undefined;\n\n  // Row rules are scoped to the row's own inputs\n  await applyVisibility(elements, element.visibility);\n\n  // Process the UI config content\n  const ui: UiElementApiResponse[] = [];\n  for (const el of elements) {\n    const result = await recursivelyProcessElement(el, undefined, action);\n    ui.push(result.uiConfig);\n  }\n\n  // Check for validation errors if we have data\n  const validationErrors = await validateIteratorData(\n    elements,\n    dataArr,\n    action\n  );\n  let hasValidationErrors = validationErrors.length > 0;\n\n  let validationError: string | undefined = undefined;\n  if (dataArr && element.validate) {\n    const v =\n      action !== null\n        ? await (element.validate as any)(dataArr, action)\n        : await (element.validate as any)(dataArr);\n    if (typeof v === \"string\") {\n      hasValidationErrors = true;\n      validationError = v;\n    }\n  }\n\n  return {\n    uiConfig: {\n      ...element.uiConfig,\n      content: ui,\n      validationError: validationError,\n      contentValidationErrors: hasValidationErrors\n        ? validationErrors\n        : undefined,\n    },\n    validationErrors: hasValidationErrors,\n  };\n};\n\nconst validateIteratorData = async (\n  elements: ImplementationResponse<any, any>[],\n  dataArr: any[] | undefined,\n  action: string | null\n): Promise<Array<{ index: number; name: string; validationError: string }>> => {\n  const validationErrors: Array<{\n    index: number;\n    name: string;\n    validationError: string;\n  }> = [];\n\n  if (!dataArr || dataArr.length === 0) {\n    return validationErrors;\n  }\n\n  for (let i = 0; i < dataArr.length; i++) {\n    const rowData = dataArr[i];\n\n    if (rowData && typeof rowData === \"object\") {\n      await stripHiddenValues(elements, rowData);\n    }\n\n    for (const el of elements) {\n      const resolvedEl = await el;\n\n      if (\n        \"__type\" in resolvedEl &&\n        resolvedEl.__type === \"input\" &&\n        \"validate\" in resolvedEl &&\n        resolvedEl.validate &&\n        typeof resolvedEl.validate === \"function\"\n      ) {\n        const fieldName = resolvedEl.uiConfig.name;\n\n        if (rowData && typeof rowData === \"object\" && fieldName in rowData) {\n          const validationError =\n            action !== null\n              ? await (resolvedEl as any).validate(rowData[fieldName], action)\n              : await (resolvedEl as any).validate(rowData[fieldName]);\n\n          if (typeof validationError === \"string\") {\n            validationErrors.push({\n              index: i,\n              name: fieldName,\n              validationError: validationError,\n            });\n          }\n        }\n      }\n    }\n  }\n\n  return validationErrors;\n};\n\n/* ********************\n * Helper functions\n ******************* */\n\n// Extract the key from a custom action, supporting either a string or an object with a value property\ntype ActionValue<T> = T extends string\n  ? T\n  : T extends { value: infer V }\n    ? V\n    : never;\n\n// Extract the data from elements and return a key-value object based on the name of the element.\n// Elements named in `Hidden` (the targets of the scope's `visibility` rules) may be absent.\nexport type ExtractFormData<\n  T extends UIElements,\n  Hidden extends PropertyKey = never,\n> = {\n  [K in Extract<T[number], InputElementResponse<string, any>>[\"name\"]]:\n    | Extract<T[number], InputElementResponse<K, any>>[\"returnType\"]\n    | (K extends Hidden ? undefined : never);\n} & {\n  [K in Extract<T[number], IteratorElementResponse<string, any, any>>[\"name\"]]:\n    | Extract<T[number], IteratorElementResponse<K, any, any>>[\"contentData\"]\n    | (K extends Hidden ? undefined : never);\n};\n","// This is a special type that is thrown to disrupt the execution of a flow\nabstract class FlowDisrupt {\n  protected constructor() {}\n}\n\nexport class UIRenderDisrupt extends FlowDisrupt {\n  constructor(\n    public readonly stepId: string,\n    public readonly contents: any\n  ) {\n    super();\n  }\n}\n\nexport class StepErrorDisrupt extends FlowDisrupt {\n  constructor(public readonly message: string) {\n    super();\n  }\n}\n\nexport class StepCreatedDisrupt extends FlowDisrupt {\n  constructor(public readonly executeAfter?: Date) {\n    super();\n  }\n}\n\nexport class ExhuastedRetriesDisrupt extends FlowDisrupt {\n  constructor() {\n    super();\n  }\n}\n\nexport class CallbackDisrupt extends FlowDisrupt {\n  constructor(\n    public readonly response: any,\n    public readonly error: boolean\n  ) {\n    super();\n  }\n}\n\n// Thrown by ctx.flows.handoff / ctx.continue once the successor run has been\n// journaled (or found, on replay). Carries the successor's flow name and run\n// id so handleFlow.ts can report a handoffTo in its response instead of the\n// normal runCompleted/data shape. executeAfter, when set (a deferred\n// ctx.continue), tells the orchestrator to schedule the successor's first\n// execution rather than kicking it immediately.\nexport class HandoffDisrupt extends FlowDisrupt {\n  constructor(\n    public readonly flow: string,\n    public readonly runId: string,\n    public readonly executeAfter?: Date\n  ) {\n    super();\n  }\n}\n\n// Thrown by ctx.ui.page when the page a request is submitting has already been\n// recorded by another request (e.g. a double submit from the console). The\n// submission stops before executing anything else and leaves the run to the\n// request that recorded the page: handleFlow.ts reports a\n// StepAlreadySubmittedError, which the Go runtime returns as\n// ERR_STEP_ALREADY_SUBMITTED (409).\nexport class DuplicateSubmissionDisrupt extends FlowDisrupt {\n  constructor(public readonly stepId: string) {\n    super();\n  }\n}\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\ntype BannerMode = \"info\" | \"warning\" | \"error\" | \"success\";\n\nexport type UiElementBanner = DisplayElement<{\n  title: string;\n  description: string;\n  mode?: BannerMode;\n}>;\n\n// The shape of the response over the API\nexport interface UiElementBannerApiResponse extends BaseUiDisplayResponse<\"ui.display.banner\"> {\n  title: string;\n  description: string;\n  mode: BannerMode;\n}\n\nexport const banner: DisplayElementImplementation<\n  UiElementBanner,\n  UiElementBannerApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.banner\",\n      title: options?.title || \"\",\n      description: options?.description || \"\",\n      mode: options?.mode || \"info\",\n    } satisfies UiElementBannerApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\nexport type UiElementImage = DisplayElement<{\n  url: string;\n  alt?: string;\n  size?: \"thumbnail\" | \"small\" | \"medium\" | \"large\" | \"full\";\n  caption?: string;\n}>;\n\n// The shape of the response over the API\nexport interface UiElementImageApiResponse extends BaseUiDisplayResponse<\"ui.display.image\"> {\n  url: string;\n  alt?: string;\n  size?: \"thumbnail\" | \"small\" | \"medium\" | \"large\" | \"full\";\n  caption?: string;\n}\n\nexport const image: DisplayElementImplementation<\n  UiElementImage,\n  UiElementImageApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.image\",\n      url: options?.url || \"\",\n      alt: options?.alt,\n      size: options?.size,\n      caption: options?.caption,\n    } satisfies UiElementImageApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\nexport type UiElementCode = DisplayElement<{\n  code: string;\n  language?: string; // TODO: type the supported languages\n}>;\n\n// The shape of the response over the API\nexport interface UiElementCodeApiResponse extends BaseUiDisplayResponse<\"ui.display.code\"> {\n  code: string;\n  language?: string;\n}\n\nexport const code: DisplayElementImplementation<\n  UiElementCode,\n  UiElementCodeApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.code\",\n      code: options?.code || \"\",\n      language: options?.language,\n    } satisfies UiElementCodeApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementConfig,\n  DisplayElementResponse,\n} from \"../..\";\n\ntype ImageConfig = {\n  url: string;\n  alt?: string;\n  aspectRatio?: number;\n  fit?: \"cover\" | \"contain\";\n};\n\ntype GridItem = {\n  title?: string;\n  description?: string;\n  image?: ImageConfig;\n};\n\nexport type GridOptions<T> = {\n  data: T[];\n  render: (data: T) => GridItem;\n};\n\n// The types the user experiences\nexport type UiElementGrid = <T extends any, K extends string = never>(\n  options: GridOptions<T> & DisplayElementConfig<K>\n) => DisplayElementResponse<K>;\n\n// The shape of the response over the API\nexport interface UiElementGridApiResponse extends BaseUiDisplayResponse<\"ui.display.grid\"> {\n  data: GridItem[];\n}\n\n// The implementation\nexport const grid: DisplayElementImplementation<\n  UiElementGrid,\n  UiElementGridApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.grid\",\n      data: options.data.map((item: any) => {\n        const rendered = options.render(item);\n        return {\n          title: rendered.title,\n          description: rendered.description,\n          image: rendered.image,\n        } satisfies GridItem;\n      }),\n    } satisfies UiElementGridApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementConfig,\n  DisplayElementResponse,\n} from \"../..\";\nimport { ImageConfig } from \"../common\";\n\ntype ListItem = {\n  title?: string;\n  description?: string;\n  image?: ImageConfig;\n};\n\ntype ListOptions<T> = {\n  data: T[];\n  render: (data: T) => ListItem;\n};\n\n// The types the user experiences\nexport type UiElementList = <T extends any, K extends string = never>(\n  options: ListOptions<T> & DisplayElementConfig<K>\n) => DisplayElementResponse<K>;\n\n// The shape of the response over the API\nexport interface UiElementListApiResponse extends BaseUiDisplayResponse<\"ui.display.list\"> {\n  data: ListItem[];\n}\n\n// The implementation\nexport const list: DisplayElementImplementation<\n  UiElementList,\n  UiElementListApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.list\",\n      data: options.data.map((item: any) => {\n        const rendered = options.render(item);\n        return {\n          title: rendered.title,\n          description: rendered.description,\n          image: rendered.image,\n        } satisfies ListItem;\n      }),\n    } satisfies UiElementListApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\nexport type UiElementHeader = DisplayElement<{\n  /**\n   * The visual level of the header.\n   *\n   * @default 2\n   */\n  level?: 1 | 2 | 3;\n  /**\n   * The title of the header.\n   */\n  title?: string;\n  /**\n   * The description of the header.\n   */\n  description?: string;\n}>;\n\n// The shape of the response over the API\nexport interface UiElementHeaderApiResponse extends BaseUiDisplayResponse<\"ui.display.header\"> {\n  level: number;\n  title: string;\n  description: string;\n}\n\nexport const header: DisplayElementImplementation<\n  UiElementHeader,\n  UiElementHeaderApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.header\",\n      level: options?.level || 2,\n      title: options?.title || \"\",\n      description: options?.description || \"\",\n    } satisfies UiElementHeaderApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElement,\n  DisplayElementImplementation,\n} from \"../..\";\n\ntype KeyValueMode = \"list\" | \"grid\" | \"card\";\n\ntype KeyValueData = {\n  key: string;\n  value: string | number | Date | boolean; // TODO: support for an object with richer type info / linking\n};\n\n// The types the user experiences\nexport type UiElementKeyValue = DisplayElement<{\n  data: KeyValueData[];\n  mode?: KeyValueMode;\n}>;\n\n// The shape of the response over the API\nexport interface UiElementKeyValueApiResponse extends BaseUiDisplayResponse<\"ui.display.keyValue\"> {\n  data: KeyValueData[];\n  mode: KeyValueMode;\n}\n\n// The implementation\nexport const keyValue: DisplayElementImplementation<\n  UiElementKeyValue,\n  UiElementKeyValueApiResponse\n> = (options) => {\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.keyValue\",\n      data: options?.data || [],\n      mode: options?.mode || \"list\",\n    } satisfies UiElementKeyValueApiResponse,\n  };\n};\n","import {\n  BaseInputConfig,\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElementResponse,\n} from \"../..\";\nimport { processTableData, TableColumn, TableData } from \"../display/table\";\n\nexport type SelectMode = \"single\" | \"multi\";\n\n// Can't use the whole InputElement type and also use a local\n// bounded type parameter to infer the type of the value from the config options\n// So having to duplicate the types of the inputs\nexport type UiElementSelectTable = <\n  const T extends Record<string, any>,\n  N extends string,\n  const M extends SelectMode = \"multi\",\n  const O extends boolean = false,\n>(\n  name: N,\n  options: TableOptions<T, O, M>\n) => InputElementResponse<\n  N,\n  M extends \"single\" ? (O extends true ? T | undefined : T) : T[]\n>;\n\nexport type TableOptions<\n  T extends Record<string, any>,\n  O extends boolean,\n  M extends SelectMode,\n> = Omit<\n  BaseInputConfig<\n    M extends \"single\" ? (O extends true ? T | undefined : T) : T[],\n    O\n  >,\n  \"defaultValue\" | \"label\"\n> &\n  TableData<T> &\n  (\n    | {\n        mode?: M;\n      }\n    | {\n        mode: \"multi\";\n        max?: number;\n        min?: number;\n      }\n  );\n\n// The shape of the response over the API\nexport interface UiElementSelectTableApiResponse extends Omit<\n  BaseUiInputResponse<\"ui.select.table\", any>,\n  \"defaultValue\" | \"label\"\n> {\n  data: Record<string, any>[];\n  columns: TableColumn[];\n  mode: SelectMode;\n}\n\nexport const selectTable: InputElementImplementation<\n  any,\n  UiElementSelectTable,\n  UiElementSelectTableApiResponse\n> = (name, options) => {\n  const { data, columns } = processTableData(options.data, options.columns);\n\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.select.table\",\n      name,\n      data,\n      columns,\n      mode: options?.mode || \"multi\",\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n    } satisfies UiElementSelectTableApiResponse,\n    validate: options?.validate,\n    getData: (x: any) => x,\n  };\n};\n","import { sentenceCase } from \"change-case\";\nimport {\n  BaseInputConfig,\n  BaseUiInputResponse,\n  CallbackFn,\n  InputElementImplementation,\n  InputElementResponse,\n} from \"../..\";\nimport { processTableData } from \"../display/table\";\nimport {\n  ColumnFormat,\n  ColumnFormatApiResponse,\n  normaliseColumnFormat,\n} from \"../format\";\n\n// Can't use the whole InputElement type and also use a local\n// bounded type parameter to infer the type of the value from the config options\n// So having to duplicate the types of the inputs\nexport type UiElementInputDataGrid = <\n  N extends string,\n  T extends Record<string, any>,\n  const Cols extends Extract<keyof T, string>[],\n  C extends ColumnConfig<Cols>[] | undefined = undefined,\n>(\n  name: N,\n  options: DataGridOptions<T, C, Cols>\n) => InputElementResponse<\n  N,\n  C extends ColumnConfig<Cols>[]\n    ? {\n        // If the column has a type then we need to cast the value to the type of the column\n        // Otherwise we just use the type of the value\n        [K in C[number] as K[\"key\"]]: MapDataType<K[\"type\"], T[K[\"key\"]]>;\n      }[]\n    : T[]\n>;\n\ntype MapDataType<U, Fallback> = U extends \"text\"\n  ? string\n  : U extends \"number\"\n    ? number\n    : U extends \"boolean\"\n      ? boolean\n      : U extends \"id\"\n        ? string\n        : U extends \"select\"\n          ? string\n          : U extends \"lookup\"\n            ? string\n            : U extends \"hidden\"\n              ? Fallback\n              : Fallback;\n\n/** An option offered by a `select` or `lookup` column. `value` is what is stored in the cell. */\nexport type DataGridOption = {\n  value: string;\n  label: string;\n  description?: string;\n};\n\n/**\n * How a column's footer cell is populated. `sum` and `count` are aggregated in the browser from\n * the current rows; `computed` is supplied by the flow through an aggregate callback.\n */\ntype DataGridSummary = \"sum\" | \"count\" | \"computed\";\n\n/**\n * One totals entry. Strings render verbatim, numbers are formatted by the client. `label` is only\n * used by the grid's `summary` block; the column footer ignores it.\n */\nexport type DataGridTotal = { value: number | string; label?: string };\n\n/**\n * Totals returned by a grid's `totals` function, keyed by name. Keys matching a `summary: \"computed\"`\n * column fill that column's footer cell; any other keys (e.g. `vat`, `grandTotal`) are rendered only\n * by the grid's `summary` block. Key order is not preserved over the wire; use `summary.items` to\n * control display order.\n */\nexport type DataGridTotals = { [key: string]: DataGridTotal };\n\n/** One row of a grid's summary block. */\nexport type DataGridSummaryItem = {\n  /** The totals key whose live value this row shows. */\n  key?: string;\n  /** Row label. Defaults to the live total's label, then to `key`. */\n  label?: string;\n  /** Static value, or the value shown until the first live total arrives. Strings render verbatim. */\n  value?: number | string;\n  /** Marks a headline row (e.g. the grand total); the client renders it emphasised. */\n  important?: boolean;\n};\n\n/**\n * A read-only block rendered beneath the grid, fed by the grid's `totals` function. Keyed items\n * show that key's live total; label-only items are static. Without `items`, every total is shown\n * in alphabetical key order.\n */\nexport type DataGridSummaryBlock = {\n  title?: string;\n  /** Rows to render, in order. */\n  items?: DataGridSummaryItem[];\n};\n\n/** Configuration for a column of type `lookup`. */\nexport type DataGridLookupConfig = {\n  /**\n   * Resolves the options offered for the given search query. Invoked through the element's\n   * `onLookup` callback as the user types; `query` may be an empty string.\n   */\n  search: (args: {\n    query: string;\n  }) => DataGridOption[] | Promise<DataGridOption[]>;\n  /**\n   * Display labels for ids already present in `data`, keyed by id. Labels are not derived\n   * automatically, so build this from the same query that produced the rows.\n   */\n  labels?: Record<string, string>;\n  placeholder?: string;\n};\n\ntype ColumnConfig<Cols extends string[]> = {\n  key: Cols[number];\n  label?: string;\n  /** Inferred as `select` when `options` is set and `lookup` when `lookup` is set. */\n  type?: DataGridDataTypes;\n  editable?: boolean;\n  /** Seed value for rows the user adds. */\n  defaultValue?: string | number | boolean | null;\n  /** Static options for a `select` column. */\n  options?: DataGridOption[];\n  lookup?: DataGridLookupConfig;\n  /** Renders a totals footer for this column. */\n  summary?: DataGridSummary;\n  /** How the column's read-only cells are displayed, as in list-view datagrids (e.g. colourising numbers by sign). */\n  format?: ColumnFormat;\n};\n\n/**\n * Computes the grid's totals from its current rows (see `DataGridTotals`). Invoked through the\n * element's `onTotals` callback when the page opens and, debounced, after edits, so it should be\n * cheap and idempotent.\n */\ntype DataGridTotalsFn<T> = (\n  rows: T[]\n) => DataGridTotals | Promise<DataGridTotals>;\n\nexport type DataGridOptions<\n  T extends Record<string, any>,\n  C,\n  Cols extends string[] = Extract<keyof T, string>[],\n> = Omit<\n  BaseInputConfig<T[]>,\n  \"defaultValue\" | \"label\" | \"optional\" | \"disabled\"\n> & {\n  data: T[];\n  // The union keeps `ColumnConfig` as the contextual type for column callbacks (e.g. `lookup.search`)\n  // while `C` is still being inferred, so inline callbacks with untyped parameters don't collapse `C`.\n  columns?: C | ColumnConfig<Cols>[];\n  allowAddRows?: boolean;\n  allowDeleteRows?: boolean;\n  totals?: DataGridTotalsFn<T>;\n  /** Renders a summary block beneath the grid. Live (keyed) rows require `totals`. */\n  summary?: DataGridSummaryBlock;\n};\n\n// The shape of the response over the API\nexport interface UiElementInputDataGridApiResponse extends Omit<\n  BaseUiInputResponse<\"ui.input.dataGrid\", any>,\n  \"defaultValue\" | \"label\" | \"optional\" | \"disabled\"\n> {\n  data: any[];\n  columns: DataGridColumn[];\n  allowAddRows: boolean;\n  allowDeleteRows: boolean;\n  summary?: DataGridSummaryBlock;\n}\n\ntype DataGridDataTypes =\n  | \"text\"\n  | \"number\"\n  | \"boolean\"\n  | \"id\"\n  | \"hidden\"\n  | \"select\"\n  | \"lookup\";\n\nexport type DataGridColumn = {\n  key: string;\n  label: string;\n  index: number;\n  type: DataGridDataTypes;\n  editable: boolean;\n  defaultValue?: string | number | boolean | null;\n  options?: DataGridOption[];\n  lookup?: {\n    labels?: { [id: string]: string };\n    placeholder?: string;\n  };\n  summary?: DataGridSummary;\n  format?: ColumnFormatApiResponse;\n};\n\ntype DataGridLookupRequest = { column: string; query: string };\ntype DataGridLookupResponse = { options: DataGridOption[] };\ntype DataGridTotalsRequest = { rows: Record<string, unknown>[] };\ntype DataGridTotalsResponse = { totals: DataGridTotals };\n\n// Keeps the wire contract object-only: bare primitives are wrapped and entries are whitelisted to\n// `value`/`label`.\nconst normaliseTotals = (totals: Record<string, unknown>): DataGridTotals => {\n  const out: DataGridTotals = {};\n  for (const [key, entry] of Object.entries(totals)) {\n    if (typeof entry === \"number\" || typeof entry === \"string\") {\n      out[key] = { value: entry };\n      continue;\n    }\n    const candidate = entry as Partial<DataGridTotal> | null;\n    if (\n      candidate &&\n      typeof candidate === \"object\" &&\n      (typeof candidate.value === \"number\" ||\n        typeof candidate.value === \"string\")\n    ) {\n      out[key] = {\n        value: candidate.value,\n        ...(typeof candidate.label === \"string\" && { label: candidate.label }),\n      };\n      continue;\n    }\n    throw new Error(\n      `dataGrid totals entry \"${key}\" must be { value: number | string, label?: string }`\n    );\n  }\n  return out;\n};\n\nexport const dataGridInput: InputElementImplementation<\n  any,\n  UiElementInputDataGrid,\n  UiElementInputDataGridApiResponse\n> = (name, options) => {\n  const { data } = processTableData(\n    options.data,\n    options.columns?.map((c) => c.key)\n  );\n\n  const inferType = (key: string) => {\n    const inferredTypeRaw = typeof data[0][key];\n    const inferredTypeMap: Record<typeof inferredTypeRaw, DataGridDataTypes> = {\n      string: \"text\",\n      number: \"number\",\n      boolean: \"boolean\",\n      bigint: \"number\",\n      symbol: \"text\",\n      undefined: \"text\",\n      object: \"text\",\n      function: \"text\",\n    };\n    return inferredTypeMap[inferredTypeRaw] ?? \"text\";\n  };\n\n  const lookups = new Map<string, DataGridLookupConfig[\"search\"]>();\n\n  const columns: DataGridColumn[] = options.columns\n    ? options.columns.map((column, idx) => {\n        const type: DataGridDataTypes =\n          column.type ??\n          (column.options\n            ? \"select\"\n            : column.lookup\n              ? \"lookup\"\n              : inferType(column.key));\n\n        if (type === \"select\" && !column.options) {\n          throw new Error(\n            `dataGrid column \"${column.key}\" has type \"select\" but no options`\n          );\n        }\n        if (type === \"lookup\" && typeof column.lookup?.search !== \"function\") {\n          throw new Error(\n            `dataGrid column \"${column.key}\" has type \"lookup\" but no lookup.search function`\n          );\n        }\n        if (column.lookup) {\n          lookups.set(column.key, column.lookup.search);\n        }\n        if (\n          column.summary === \"computed\" &&\n          typeof options.totals !== \"function\"\n        ) {\n          throw new Error(\n            `dataGrid column \"${column.key}\" has summary \"computed\" but no totals function`\n          );\n        }\n\n        return {\n          key: column.key,\n          label: column.label || column.key,\n          index: idx,\n          type,\n          editable: column.editable ?? type !== \"id\",\n          ...(column.defaultValue !== undefined && {\n            defaultValue: column.defaultValue,\n          }),\n          ...(column.options && { options: column.options }),\n          ...(column.lookup && {\n            lookup: {\n              ...(column.lookup.labels && { labels: column.lookup.labels }),\n              ...(column.lookup.placeholder && {\n                placeholder: column.lookup.placeholder,\n              }),\n            },\n          }),\n          ...(column.summary && { summary: column.summary }),\n          ...(column.format !== undefined && {\n            format: normaliseColumnFormat(\n              column.format,\n              `dataGrid column \"${column.key}\"`\n            ),\n          }),\n        };\n      })\n    : Object.keys(data[0]).map((key, idx) => {\n        return {\n          index: idx,\n          key,\n          label: sentenceCase(key),\n          type: inferType(key),\n          editable: true,\n        };\n      });\n\n  const summary = options.summary;\n  if (summary !== undefined) {\n    if (summary === null || typeof summary !== \"object\") {\n      throw new Error(\"dataGrid summary must be an object\");\n    }\n    const items = summary.items;\n    for (const item of items ?? []) {\n      if (item.label === undefined && item.key === undefined) {\n        throw new Error(\"dataGrid summary items require a label or a key\");\n      }\n      if (item.important !== undefined && typeof item.important !== \"boolean\") {\n        throw new Error(\n          `dataGrid summary item \"${item.label ?? item.key}\" has a non-boolean important flag`\n        );\n      }\n    }\n    const needsTotals =\n      !items ||\n      items.length === 0 ||\n      items.some((item) => item.key !== undefined);\n    if (needsTotals && typeof options.totals !== \"function\") {\n      throw new Error(\n        \"dataGrid summary shows live totals but the grid has no totals function\"\n      );\n    }\n  }\n\n  const onLookup: CallbackFn<\n    DataGridLookupRequest,\n    DataGridLookupResponse\n  > = async (input) => {\n    const column = input?.column;\n    if (typeof column !== \"string\") {\n      throw new Error(\"onLookup requires a column\");\n    }\n    const search = lookups.get(column);\n    if (!search) {\n      throw new Error(`Column ${column} does not have a lookup`);\n    }\n    const results = await search({ query: input.query ?? \"\" });\n    return { options: results ?? [] };\n  };\n\n  const onTotals: CallbackFn<\n    DataGridTotalsRequest,\n    DataGridTotalsResponse\n  > = async (input) => {\n    if (typeof options.totals !== \"function\") {\n      throw new Error(\"dataGrid does not have a totals function\");\n    }\n    const rows = Array.isArray(input?.rows) ? input.rows : [];\n    const totals = (await options.totals(rows as any)) ?? {};\n    return { totals: normaliseTotals(totals as Record<string, unknown>) };\n  };\n\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.dataGrid\",\n      name,\n      data,\n      columns,\n      helpText: options?.helpText,\n      allowAddRows: options?.allowAddRows ?? false,\n      allowDeleteRows: options?.allowDeleteRows ?? false,\n      ...(summary && {\n        summary: {\n          ...(summary.title && { title: summary.title }),\n          ...(summary.items &&\n            summary.items.length > 0 && { items: summary.items }),\n        },\n      }),\n    } satisfies UiElementInputDataGridApiResponse,\n    validate: options?.validate, // TODO have some built in validation that checks the types of the response\n    getData: (x: any) => x,\n    onLookup,\n    onTotals,\n  };\n};\n","// Column formats are authored in flow-SDK vocabulary and sent as the JSON form of the tools\n// `FormatConfig` proto (tools/proto/tools.proto), so the console renders flow columns with the same\n// cell decoration as list-view datagrids.\n\nconst NUMBER_STYLES = {\n  decimal: \"DECIMAL\",\n  raw: \"RAW\",\n  percent: \"PERCENTAGE\",\n  currency: \"CURRENCY\",\n  unit: \"UNIT\",\n} as const;\n\nconst SIGN_DISPLAYS = {\n  auto: \"AUTO\",\n  exceptZero: \"EXCEPT_ZERO\",\n  always: \"ALWAYS\",\n  never: \"NEVER\",\n} as const;\n\n/**\n * How numbers are coloured, chosen by `mode`. `sign` colours non-zero numbers by their sign; zero is\n * never coloured.\n */\nexport type ColumnNumberColor =\n  | { mode: \"sign\"; positive: \"green\"; negative: \"red\" }\n  | { mode: \"sign\"; positive: \"red\"; negative: \"green\" };\n\nexport type ColumnNumberFormat = {\n  /** As `Intl.NumberFormat`'s `style`, plus `raw` for the unformatted number. Defaults to `decimal`. */\n  style?: keyof typeof NUMBER_STYLES;\n  /** ISO 4217 code, used by the `currency` style. */\n  currency?: string;\n  /** Unit identifier used by the `unit` style, e.g. `kilogram` or `meter-per-second`. */\n  unit?: string;\n  /** As `Intl.NumberFormat`'s `signDisplay`. */\n  signDisplay?: keyof typeof SIGN_DISPLAYS;\n  color?: ColumnNumberColor;\n  /** Hidden by default; revealed on hover. */\n  sensitive?: boolean;\n  /** Locale code; detected from the browser when omitted. */\n  locale?: string;\n  prefix?: string;\n  suffix?: string;\n};\n\nexport type ColumnTextFormat = {\n  prefix?: string;\n  suffix?: string;\n  color?: string;\n  /** Hidden by default; revealed on hover. */\n  sensitive?: boolean;\n};\n\n/** How a single value is displayed: `label` replaces the value's text. */\nexport type ColumnValueFormat = {\n  label?: string;\n  color?: string;\n};\n\nexport type ColumnBooleanFormat = {\n  true?: ColumnValueFormat;\n  false?: ColumnValueFormat;\n};\n\ntype FormatKind = {\n  number: ColumnNumberFormat;\n  text: ColumnTextFormat;\n  boolean: ColumnBooleanFormat;\n  /** Formats keyed by cell value, e.g. `{ late: { label: \"Late\", color: \"red\" } }`. */\n  values: Record<string, ColumnValueFormat>;\n};\n\n/** How a column's cells are displayed. Set exactly one of `number`, `text`, `boolean` or `values`. */\nexport type ColumnFormat = {\n  [K in keyof FormatKind]: { [P in K]: FormatKind[K] } & {\n    [P in Exclude<keyof FormatKind, K>]?: never;\n  };\n}[keyof FormatKind];\n\n// The shape of a column's format over the API\nexport type ColumnFormatApiResponse = {\n  type: \"NUMBER\" | \"STRING\" | \"BOOL\" | \"ENUM\";\n  numberConfig?: {\n    mode?: (typeof NUMBER_STYLES)[keyof typeof NUMBER_STYLES];\n    currencyCode?: string;\n    unitCode?: string;\n    sensitive?: boolean;\n    locale?: string;\n    prefix?: string;\n    suffix?: string;\n    colourise?: \"NORMAL\" | \"INVERTED\";\n    signDisplay?: (typeof SIGN_DISPLAYS)[keyof typeof SIGN_DISPLAYS];\n  };\n  stringConfig?: {\n    prefix?: string;\n    suffix?: string;\n    sensitive?: boolean;\n    textColour?: string;\n  };\n  boolConfig?: {\n    positiveColour?: string;\n    positiveValue?: string;\n    negativeColour?: string;\n    negativeValue?: string;\n  };\n  enumConfig?: {\n    values: { value: string; displayValue?: string; colour?: string }[];\n  };\n};\n\nconst FORMAT_KINDS: (keyof FormatKind)[] = [\n  \"number\",\n  \"text\",\n  \"boolean\",\n  \"values\",\n];\n\n/**\n * Validates an author-supplied column format and converts it to its wire shape. Unknown keys are\n * dropped. `context` prefixes error messages.\n */\nexport const normaliseColumnFormat = (\n  format: ColumnFormat,\n  context: string\n): ColumnFormatApiResponse => {\n  if (!isObject(format)) {\n    throw new Error(`${context} format must be an object`);\n  }\n  const set = FORMAT_KINDS.filter((k) => format[k] != null);\n  if (set.length !== 1) {\n    throw new Error(\n      `${context} format must set exactly one of number, text, boolean or values`\n    );\n  }\n  const kind = set[0];\n  const config: unknown = format[kind];\n  if (!isObject(config)) {\n    throw new Error(`${context} format ${kind} must be an object`);\n  }\n\n  switch (kind) {\n    case \"number\":\n      return {\n        type: \"NUMBER\",\n        numberConfig: {\n          ...pickMapped(config, \"style\", \"mode\", NUMBER_STYLES, context),\n          ...pick(config, \"currency\", \"currencyCode\", \"string\", context),\n          ...pick(config, \"unit\", \"unitCode\", \"string\", context),\n          ...pick(config, \"sensitive\", \"sensitive\", \"boolean\", context),\n          ...pick(config, \"locale\", \"locale\", \"string\", context),\n          ...pick(config, \"prefix\", \"prefix\", \"string\", context),\n          ...pick(config, \"suffix\", \"suffix\", \"string\", context),\n          ...colourise(config.color, context),\n          ...pickMapped(\n            config,\n            \"signDisplay\",\n            \"signDisplay\",\n            SIGN_DISPLAYS,\n            context\n          ),\n        },\n      };\n    case \"text\":\n      return {\n        type: \"STRING\",\n        stringConfig: {\n          ...pick(config, \"prefix\", \"prefix\", \"string\", context),\n          ...pick(config, \"suffix\", \"suffix\", \"string\", context),\n          ...pick(config, \"sensitive\", \"sensitive\", \"boolean\", context),\n          ...pick(config, \"color\", \"textColour\", \"string\", context),\n        },\n      };\n    case \"boolean\": {\n      const t = valueFormat(config.true, `${context} format boolean.true`);\n      const f = valueFormat(config.false, `${context} format boolean.false`);\n      return {\n        type: \"BOOL\",\n        boolConfig: {\n          ...(t.label !== undefined && { positiveValue: t.label }),\n          ...(t.color !== undefined && { positiveColour: t.color }),\n          ...(f.label !== undefined && { negativeValue: f.label }),\n          ...(f.color !== undefined && { negativeColour: f.color }),\n        },\n      };\n    }\n    case \"values\":\n      return {\n        type: \"ENUM\",\n        enumConfig: {\n          values: Object.entries(config).map(([value, entry]) => {\n            const v = valueFormat(entry, `${context} format values.${value}`);\n            return {\n              value,\n              ...(v.label !== undefined && { displayValue: v.label }),\n              ...(v.color !== undefined && { colour: v.color }),\n            };\n          }),\n        },\n      };\n  }\n};\n\nconst isObject = (value: unknown): value is Record<string, any> =>\n  typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst pick = (\n  config: Record<string, unknown>,\n  key: string,\n  wireKey: string,\n  type: \"string\" | \"boolean\",\n  context: string\n) => {\n  const value = config[key];\n  if (value === undefined) return {};\n  if (typeof value !== type) {\n    throw new Error(`${context} format ${key} must be a ${type}`);\n  }\n  return { [wireKey]: value };\n};\n\nconst pickMapped = (\n  config: Record<string, unknown>,\n  key: string,\n  wireKey: string,\n  mapping: Record<string, string>,\n  context: string\n) => {\n  const value = config[key];\n  if (value === undefined) return {};\n  if (\n    typeof value !== \"string\" ||\n    !Object.prototype.hasOwnProperty.call(mapping, value)\n  ) {\n    throw new Error(\n      `${context} format ${key} must be one of ${Object.keys(mapping).join(\", \")}`\n    );\n  }\n  return { [wireKey]: mapping[value] };\n};\n\nconst colourise = (color: unknown, context: string) => {\n  if (color === undefined) return {};\n  if (!isObject(color) || color.mode !== \"sign\") {\n    throw new Error(`${context} format color.mode must be one of sign`);\n  }\n  const { positive, negative } = color;\n  if (positive === \"green\" && negative === \"red\") {\n    return { colourise: \"NORMAL\" as const };\n  }\n  if (positive === \"red\" && negative === \"green\") {\n    return { colourise: \"INVERTED\" as const };\n  }\n  throw new Error(\n    `${context} format color with mode \"sign\" must have positive: \"green\", negative: \"red\" or positive: \"red\", negative: \"green\"`\n  );\n};\n\nconst valueFormat = (entry: unknown, context: string): ColumnValueFormat => {\n  if (entry === undefined) return {};\n  if (!isObject(entry)) {\n    throw new Error(`${context} must be an object`);\n  }\n  for (const key of [\"label\", \"color\"] as const) {\n    if (entry[key] !== undefined && typeof entry[key] !== \"string\") {\n      throw new Error(`${context}.${key} must be a string`);\n    }\n  }\n  return { label: entry.label, color: entry.color };\n};\n","import {\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElement,\n} from \"../..\";\n\ntype ElementDataType = string;\n\n/**\n * Defines what type of datepicker should we use.\n * @default \"dateTime\"\n */\ntype DatePickerMode =\n  /** Pick both a date and a time */\n  | \"dateTime\"\n  /** Pick only a date */\n  | \"date\";\n\nexport type UiElementInputDatePicker = InputElement<\n  ElementDataType,\n  {\n    mode?: DatePickerMode;\n    /** Allows selecting only dates/datetimes past this given date. */\n    min?: string;\n    /** Allows selecting only dates/datetimes before this given date. */\n    max?: string;\n  }\n>;\n\n// The shape of the response over the API\nexport interface UiElementInputDatePickerApiResponse extends BaseUiInputResponse<\n  \"ui.input.datePicker\",\n  ElementDataType\n> {\n  mode?: DatePickerMode;\n  min?: string;\n  max?: string;\n}\n\nexport const datePickerInput: InputElementImplementation<\n  ElementDataType,\n  UiElementInputDatePicker,\n  UiElementInputDatePickerApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.datePicker\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n      defaultValue: options?.defaultValue,\n      mode: options?.mode,\n      min: options?.min,\n      max: options?.max,\n    } satisfies UiElementInputDatePickerApiResponse,\n    validate: options?.validate,\n    onLeave: options?.onLeave,\n    getData: (x: ElementDataType) => x,\n  };\n};\n","import {\n  BaseUiInputResponse,\n  InputElementImplementation,\n  InputElement,\n  CallbackFn,\n} from \"../..\";\n\nimport { File, FileDbRecord } from \"../../../../File\";\n\ntype ElementDataType = Partial<FileDbRecord>;\n\nexport type UiElementInputFile = InputElement<ElementDataType, {}, File>;\n\n/**\n * key: string;\n * filename: string;\n * contentType: string;\n */\ntype PresignedUrlCallbackInput = Partial<FileDbRecord>;\ntype PresignedUrlCallbackResponse = {\n  key: string;\n  url: string;\n};\n\n// The shape of the response over the API\nexport interface UiElementInputFileApiResponse extends BaseUiInputResponse<\n  \"ui.input.file\",\n  ElementDataType\n> {}\n\nexport const fileInput: InputElementImplementation<\n  ElementDataType,\n  UiElementInputFile,\n  UiElementInputFileApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.file\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n    } satisfies UiElementInputFileApiResponse,\n    validate: options?.validate,\n    getData: (x: ElementDataType) => x,\n    getPresignedUploadURL: (async (input: PresignedUrlCallbackInput) => {\n      const file = new File(input);\n      const url = await file.getPresignedUploadUrl();\n      return {\n        url: url.toString(),\n        key: file.key,\n      };\n    }) as CallbackFn<PresignedUrlCallbackInput, PresignedUrlCallbackResponse>,\n  };\n};\n","import {\n  BaseInputConfig,\n  BaseUiInputResponse,\n  CallbackFn,\n  InputElementImplementation,\n  InputElementImplementationResponse,\n  InputElementResponse,\n  ValidateFn,\n} from \"../..\";\n\nimport { File, FileDbRecord } from \"../../../../File\";\n\n/**\n * Data posted by the client for a single image capture entry.\n * `file` carries the upload metadata (the bytes go via the presigned URL).\n */\nexport type ImageCaptureValue = {\n  file: Partial<FileDbRecord>;\n  caption?: string;\n};\n\n/**\n * Hydrated entry handed to the flow function: `file` becomes a real File\n * instance (via transformRichDataTypes).\n */\nexport type ImageCaptureResult = {\n  file: File;\n  caption?: string;\n};\n\nexport type ImageCaptureMode = \"single\" | \"multi\";\nexport type ImageCaptureCaptionMode = \"disabled\" | \"optional\" | \"required\";\n\ntype ImageCaptureValueFor<M> = M extends \"multi\"\n  ? ImageCaptureValue[]\n  : ImageCaptureValue;\ntype ImageCaptureResultFor<M> = M extends \"multi\"\n  ? ImageCaptureResult[]\n  : ImageCaptureResult;\n\ntype SharedOptions = {\n  /** Controls whether captions are disabled, optional, or required. Defaults to \"optional\". */\n  caption?: ImageCaptureCaptionMode;\n};\n\ntype ImageCaptureOptions<M extends ImageCaptureMode> = SharedOptions & {\n  /** The mode of the image capture input. Defaults to \"single\". */\n  mode?: M;\n} & (M extends \"multi\"\n    ? {\n        /** Maximum number of photos the user can capture. */\n        max?: number;\n        /** Minimum number of photos the user must capture. */\n        min?: number;\n      }\n    : {});\n\nexport type UiElementInputImageCapture = <\n  N extends string,\n  const M extends ImageCaptureMode = \"single\",\n>(\n  name: N,\n  options?: BaseInputConfig<ImageCaptureValueFor<M>> & ImageCaptureOptions<M>\n) => InputElementResponse<N, ImageCaptureValueFor<M>, ImageCaptureResultFor<M>>;\n\ntype PresignedUrlCallbackInput = Partial<FileDbRecord>;\ntype PresignedUrlCallbackResponse = {\n  key: string;\n  url: string;\n};\n\nexport interface UiElementInputImageCaptureApiResponse extends BaseUiInputResponse<\n  \"ui.input.imageCapture\",\n  ImageCaptureValue | ImageCaptureValue[]\n> {\n  mode: ImageCaptureMode;\n  caption: ImageCaptureCaptionMode;\n  /** Multi mode only: maximum number of photos. */\n  max?: number;\n  /** Multi mode only: minimum number of photos. */\n  min?: number;\n}\n\nconst isMultiOptions = (\n  opts: any\n): opts is ImageCaptureOptions<\"multi\"> & {\n  max?: number;\n  min?: number;\n} => opts && opts.mode === \"multi\";\n\nfunction validateEntry(\n  entry: ImageCaptureValue | undefined,\n  caption: ImageCaptureCaptionMode,\n  context: string\n): string | true {\n  if (!entry?.file?.key) {\n    return `${context}: an image is required`;\n  }\n  if (caption === \"required\" && !entry.caption?.trim()) {\n    return `${context}: a caption is required`;\n  }\n  return true;\n}\n\nexport const imageCapture: InputElementImplementation<\n  ImageCaptureValue | ImageCaptureValue[],\n  UiElementInputImageCapture,\n  UiElementInputImageCaptureApiResponse\n> = (name, options) => {\n  const caption = options?.caption ?? \"optional\";\n  const mode: ImageCaptureMode = options?.mode ?? \"single\";\n  const multi = isMultiOptions(options);\n  const max = multi ? options?.max : undefined;\n  const min = multi ? options?.min : undefined;\n\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.imageCapture\",\n      name,\n      label: options?.label || name,\n      optional: options?.optional || false,\n      disabled: options?.disabled || false,\n      helpText: options?.helpText,\n      mode,\n      caption,\n      ...(multi ? { max, min } : {}),\n    } satisfies UiElementInputImageCaptureApiResponse,\n    validate: async (data, action) => {\n      const optional = options?.optional ?? false;\n\n      if (mode === \"multi\") {\n        const list = (data as ImageCaptureValue[] | undefined) ?? [];\n        if (list.length === 0) {\n          // min/max/per-item checks only constrain non-empty submissions;\n          // an optional input with no photos is a valid state.\n          if (!optional) return \"At least one image is required\";\n        } else {\n          if (min !== undefined && list.length < min) {\n            return `At least ${min} image${min === 1 ? \"\" : \"s\"} required`;\n          }\n          if (max !== undefined && list.length > max) {\n            return `At most ${max} image${max === 1 ? \"\" : \"s\"} allowed`;\n          }\n          for (let i = 0; i < list.length; i++) {\n            const result = validateEntry(list[i], caption, `Image ${i + 1}`);\n            if (result !== true) return result;\n          }\n        }\n      } else {\n        const entry = data as ImageCaptureValue | undefined;\n        const hasFile = !!entry?.file?.key;\n        if (!optional && !hasFile) {\n          return \"An image is required\";\n        }\n        if (hasFile) {\n          const result = validateEntry(entry, caption, \"Image\");\n          if (result !== true) return result;\n        }\n      }\n\n      return (\n        (options?.validate as ValidateFn<typeof data> | undefined)?.(\n          data,\n          action\n        ) ?? true\n      );\n    },\n    getData: (x) => x,\n    getPresignedUploadURL: (async (input: PresignedUrlCallbackInput) => {\n      const file = new File(input);\n      const url = await file.getPresignedUploadUrl();\n      return {\n        url: url.toString(),\n        key: file.key,\n      };\n    }) as CallbackFn<PresignedUrlCallbackInput, PresignedUrlCallbackResponse>,\n  } satisfies InputElementImplementationResponse<\n    UiElementInputImageCaptureApiResponse,\n    ImageCaptureValue | ImageCaptureValue[]\n  > & {\n    getPresignedUploadURL: CallbackFn<\n      PresignedUrlCallbackInput,\n      PresignedUrlCallbackResponse\n    >;\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  ImplementationResponse,\n  IteratorElementImplementation,\n  IteratorElementResponse,\n  UiElementApiResponses,\n  UIElements,\n  ValidateFn,\n} from \"..\";\nimport { ExtractFormData } from \"../page\";\nimport { VisibilityInput } from \"../visibility\";\n\nexport type UiElementIterator = <\n  N extends string,\n  T extends UIElements,\n  const V = {},\n>(\n  name: N,\n  options: {\n    content: T;\n    /** Visibility rules for the row's elements, evaluated against the same row's inputs. */\n    visibility?: VisibilityInput<T, V, \"row\">;\n    validate?: ValidateFn<ExtractFormData<T>[]>;\n    max?: number;\n    min?: number;\n  }\n) => IteratorElementResponse<N, T, ExtractFormData<T, keyof V>[]>;\n\n// The shape of the response over the API\nexport interface UiElementIteratorApiResponse extends BaseUiDisplayResponse<\"ui.iterator\"> {\n  name: string;\n  content: UiElementApiResponses;\n  max?: number;\n  min?: number;\n  validationError?: string;\n  contentValidationErrors?: Array<{\n    index: number;\n    name: string;\n    validationError: string;\n  }>;\n}\n\nexport const iterator: IteratorElementImplementation<\n  any,\n  UiElementIterator,\n  UiElementIteratorApiResponse\n> = (name, options) => {\n  return {\n    __type: \"iterator\",\n    // Applied to the row elements by the page when it processes this iterator\n    visibility: options.visibility,\n    uiConfig: {\n      __type: \"ui.iterator\",\n      name,\n      content: options.content as unknown as UiElementApiResponses,\n      max: options.max,\n      min: options.min,\n    } satisfies UiElementIteratorApiResponse,\n    validate: options?.validate,\n    getData: (x: any) => x,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementWithRequiredConfig,\n} from \"../..\";\nimport { Hardware, NullableHardware } from \"../../../index\";\n\nexport type UiElementPrint<H extends NullableHardware> =\n  DisplayElementWithRequiredConfig<{\n    jobs: PrintData<H>[] | PrintData<H>;\n    title?: string;\n    description?: string;\n    /** If true, the jobs will be automatically printed. */\n    autoPrint?: boolean;\n    /** If true, the step will continue after the jobs are complete (pending validation). */\n    autoContinue?: boolean;\n    /** Control whether users can reprint jobs\n     * @default true\n     */\n    allowReprint?: boolean;\n  }>;\n\ntype PrintData<H extends NullableHardware> = {\n  /** The name of the print job. */\n  name?: string;\n  /** The printer to use for the print job. Printers are defined in keelconfig.yaml. */\n  printer?: H extends Hardware ? H[\"printers\"][number][\"name\"] : never;\n} & (PrintDataZpl | PrintDataRawPdf);\n\ntype PrintDataZpl = {\n  type: \"zpl\";\n} & (\n  | {\n      data: string | string[];\n      url?: never;\n    }\n  | {\n      data?: never;\n      url: string;\n    }\n);\n\ntype PrintDataRawPdf = {\n  type: \"rawPdf\";\n  url: string;\n  data?: never;\n  /** The DPI of the PDF\n   * @default 300\n   */\n  dpi?: number;\n  /** The width of the page in dots.\n   * e.g. 4\" at 300 dpi is 1200 dots.\n   * @default 1200\n   */\n  pageWidth?: number;\n  /** The height of the page in dots.\n   * e.g. 6\" at 300 dpi is 1800 dots.\n   * @default 1800\n   */\n  pageHeight?: number;\n};\n\n// The shape of the response over the API\nexport interface UiElementPrintApiResponse extends BaseUiDisplayResponse<\"ui.interactive.print\"> {\n  title?: string;\n  description?: string;\n  data: {\n    type: \"zpl\" | \"rawPdf\";\n    name?: string;\n    data?: string[];\n    url?: string;\n    printer?: string;\n    dpi?: number;\n    pageWidth?: number;\n    pageHeight?: number;\n  }[];\n  autoPrint: boolean;\n  autoContinue: boolean;\n  allowReprint: boolean;\n}\n\nexport const print: DisplayElementImplementation<\n  UiElementPrint<NullableHardware>,\n  UiElementPrintApiResponse\n> = async (options) => {\n  const dataConfig = Array.isArray(options.jobs)\n    ? options.jobs\n    : [options.jobs];\n\n  const dataPromises = dataConfig.map(async (d) => {\n    // if (\"file\" in d && d.file) {\n    //   return {\n    //     type: \"url\" as const,\n    //     url: (await d.file.getPresignedUrl()).toString(),\n    //   };\n    // }\n\n    return {\n      type: d.type,\n      name: d.name,\n      data:\n        \"data\" in d && d.data\n          ? Array.isArray(d.data)\n            ? d.data\n            : [d.data]\n          : undefined,\n      printer: d.printer,\n      url: \"url\" in d && d.url ? d.url : undefined,\n      ...(d.type === \"rawPdf\"\n        ? {\n            dpi: d.dpi,\n            pageWidth: d.pageWidth,\n            pageHeight: d.pageHeight,\n          }\n        : {}),\n    } satisfies UiElementPrintApiResponse[\"data\"][number];\n  });\n\n  const data = (await Promise.all(dataPromises)).filter(\n    (x): x is NonNullable<typeof x> => x !== null\n  );\n\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.interactive.print\",\n      title: options.title,\n      description: options.description,\n      data,\n      autoPrint: options.autoPrint ?? false,\n      autoContinue: options.autoContinue ?? false,\n      allowReprint: options.allowReprint ?? true,\n    } satisfies UiElementPrintApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  BaseUiMinimalInputResponse,\n  DisplayElementImplementation,\n  InputElementImplementation,\n  InputElementResponse,\n  ValidateFn,\n} from \"../..\";\nimport { ImageConfig } from \"../common\";\n\nexport type UiElementPickList = <\n  N extends string,\n  T extends Record<string, any>,\n  const M extends PickListInputModes = { scanner: true; manual: true },\n>(\n  name: N,\n  options: PickListOptions<M, T>\n) => InputElementResponse<\n  N,\n  {\n    items: PickListResponseItem[];\n  }\n>;\n\ntype PickListResponseItem = {\n  id: string;\n  quantity: number;\n  targetQuantity: number;\n  scannedBarcodes?: string[];\n};\n\ntype PickListItem = {\n  id: string;\n  targetQuantity: number;\n  title?: string;\n  description?: string;\n  image?: ImageConfig;\n  barcodes?: string[];\n};\n\n/**\n * Defines how duplicate scans should be handled.\n * @default \"increaseQuantity\"\n */\ntype ScanDuplicateMode =\n  /** Increase quantity when duplicates are scanned */\n  | \"increaseQuantity\"\n  /** Reject duplicate scans with an error message */\n  | \"rejectDuplicates\";\n\n/**\n * Defines how picking items should be handled. By default, all modes are enabled.\n */\ntype PickListInputModes = {\n  /** Picking items can be done by scanning barcodes */\n  scanner: boolean;\n  /** Picking items can be done by using the add/remove buttons */\n  manual: boolean;\n};\n\ntype PickListOptions<M extends PickListInputModes, T> = {\n  data: T[];\n  render: (data: T) => PickListItem;\n  supportedInputs?: M;\n  validate?: ValidateFn<{ items: PickListResponseItem[] }>;\n  duplicateHandling?: ScanDuplicateMode | undefined;\n  /** If true, the step will continue after all items reach the target quantity (pending validation)\n   * Only applied for scanner inputs.\n   */\n  autoContinue?: boolean;\n};\n\n// The shape of the response over the API\nexport interface UiElementPickListApiResponse extends BaseUiMinimalInputResponse<\"ui.interactive.pickList\"> {\n  data: PickListItem[];\n  supportedInputs: PickListInputModes;\n  duplicateHandling: ScanDuplicateMode | undefined;\n  autoContinue: boolean;\n}\n\nexport const pickList: InputElementImplementation<\n  { items: PickListResponseItem[] },\n  UiElementPickList,\n  UiElementPickListApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.interactive.pickList\",\n      name,\n      supportedInputs: options.supportedInputs || {\n        scanner: true,\n        manual: true,\n      },\n      duplicateHandling: options.duplicateHandling,\n      autoContinue: options.autoContinue ?? false,\n      data: options.data.map((item: any) => {\n        const rendered = options.render(item);\n        return {\n          id: rendered.id,\n          targetQuantity: rendered.targetQuantity,\n          title: rendered.title,\n          description: rendered.description,\n          image: rendered.image ?? undefined,\n          barcodes: rendered.barcodes ?? undefined,\n        } satisfies PickListItem;\n      }),\n    } satisfies UiElementPickListApiResponse,\n    validate: async (data, action) => {\n      // Ensure the response is an object with an items array\n      if (!(\"items\" in data)) {\n        return \"Missing items in response\";\n      }\n\n      if (!Array.isArray(data.items)) {\n        return \"Items must be an array\";\n      }\n\n      if (\n        data.items.some(\n          (item: any) =>\n            typeof item !== \"object\" ||\n            typeof item.id !== \"string\" ||\n            typeof item.quantity !== \"number\" ||\n            typeof item.targetQuantity !== \"number\" ||\n            (item.scannedBarcodes && !Array.isArray(item.scannedBarcodes))\n        )\n      ) {\n        return \"Invalid data\";\n      }\n\n      return options?.validate?.(data, action) ?? true;\n    },\n    getData: (x: any) => x,\n  };\n};\n","export class NonRetriableError extends Error {\n  constructor(message?: string) {\n    super(message);\n  }\n}\n","import {\n  BaseUiMinimalInputResponse,\n  InputElementImplementation,\n  InputElementResponse,\n  ValidateFn,\n} from \"../..\";\n\nexport type UiElementScan = <\n  N extends string,\n  const M extends scanMode = \"single\",\n  const D extends ScanDuplicateMode = \"none\",\n  R = string | null,\n>(\n  name: N,\n  options?: ScanOptions<M, D, R>\n) => InputElementResponse<\n  N,\n  M extends \"single\" ? string : ScanResponseItem<D>[]\n>;\n\ntype ScanResponseItem<D> = D extends \"trackQuantity\"\n  ? {\n      value: string;\n      quantity: number;\n    }\n  : string;\n\n/**\n * Defines how duplicate scans should be handled.\n * @default \"none\"\n */\ntype ScanDuplicateMode =\n  /** No duplicate handling - all scans are accepted as separate entries */\n  | \"none\"\n  /** Track quantity when duplicates are scanned */\n  | \"trackQuantity\"\n  /** Reject duplicate scans with an error message */\n  | \"rejectDuplicates\";\n\ntype scanMode = \"single\" | \"multi\";\n\ntype ScanOptions<M, D, R = string | null> = {\n  /** The title of the input block\n   * @default \"Scan {unit plural | 'items'}\"\n   */\n  title?: string;\n  description?: string;\n  /** The singular unit of the item being scanned. E.g. \"box\", \"bottle\", \"product\" etc */\n  unit?: string;\n  /** The mode of the scan input\n   * @default \"single\"\n   */\n  mode: M | scanMode;\n\n  validate?: ValidateFn<ScanResponseItem<D>>;\n  /** Converts a scanned value into the value this element should return.\n   * Use it to turn a raw barcode into the data your flow actually wants —\n   * e.g. a product name, an internal ID, or a full record. Defaults to\n   * `string | null`; return a richer JSON-serializable shape to let\n   * TypeScript infer it.\n   */\n  lookup?: (value: string) => R | Promise<R>;\n} & (M extends \"multi\"\n  ? {\n      max?: number;\n      min?: number;\n      duplicateHandling?: D | ScanDuplicateMode;\n    }\n  : {\n      /** If true, the step will continue after a scan (pending validation).\n       * @default false\n       */\n      autoContinue?: boolean;\n    });\n\n// The shape of the response over the API\nexport interface UiElementInputScanApiResponse extends BaseUiMinimalInputResponse<\"ui.input.scan\"> {\n  mode: \"single\" | \"multi\";\n  title?: string;\n  description?: string;\n  unit?: string;\n  max?: number;\n  min?: number;\n  duplicateHandling: ScanDuplicateMode;\n  autoContinue: boolean;\n}\n\nconst isMultiMode = (opts: any): opts is ScanOptions<\"multi\", any> =>\n  opts && opts.mode === \"multi\";\nconst isSingleMode = (opts: any): opts is ScanOptions<\"single\", any> =>\n  opts && opts.mode === \"single\";\n\nexport const scan: InputElementImplementation<\n  any,\n  UiElementScan,\n  UiElementInputScanApiResponse\n> = (name, options) => {\n  return {\n    __type: \"input\",\n    uiConfig: {\n      __type: \"ui.input.scan\",\n      name,\n      title: options?.title ?? undefined,\n      description: options?.description ?? undefined,\n      unit: options?.unit ?? undefined,\n      mode: options?.mode ?? \"single\",\n      duplicateHandling: \"none\",\n      autoContinue: false,\n      ...(isMultiMode(options)\n        ? {\n            max: options.max ?? undefined,\n            min: options.min ?? undefined,\n            duplicateHandling: options.duplicateHandling ?? \"none\",\n          }\n        : {}),\n      ...(isSingleMode(options)\n        ? {\n            autoContinue: options.autoContinue,\n          }\n        : {}),\n    } satisfies UiElementInputScanApiResponse,\n    validate: async (data, action) => {\n      return options?.validate?.(data, action) ?? true;\n    },\n    getData: (x: any) => x,\n    lookup: options?.lookup,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementWithRequiredConfig,\n} from \"../..\";\nimport { File, FileDbRecord } from \"../../../../File\";\n\nexport type UiElementFile = DisplayElementWithRequiredConfig<{\n  title?: string;\n  file: File;\n}>;\n\n// The shape of the response over the API\nexport interface UiElementFileApiResponse extends BaseUiDisplayResponse<\"ui.display.file\"> {\n  title: string;\n  file?: FileDbRecord & { url: string };\n}\n\nexport const file: DisplayElementImplementation<\n  UiElementFile,\n  UiElementFileApiResponse\n> = async (options) => {\n  const title = options.title || options.file.filename;\n  const url = await options.file.getPresignedUrl();\n  const metadata = await options.file.toJSON();\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.file\",\n      title,\n      file: metadata\n        ? {\n            url: url?.toString() || \"\",\n            ...metadata,\n          }\n        : undefined,\n    } satisfies UiElementFileApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementWithRequiredConfig,\n} from \"../..\";\n\n/** One row of a summary block. */\nexport type SummaryItem = {\n  label: string;\n  /** Strings render verbatim, numbers are formatted by the client. */\n  value: number | string;\n  /** Marks a headline row (e.g. the grand total); the client renders it emphasised. */\n  important?: boolean;\n};\n\n// The types the user experiences\nexport type UiElementSummary = DisplayElementWithRequiredConfig<{\n  title?: string;\n  /** Rows to render, in order. */\n  items: SummaryItem[];\n}>;\n\n// The shape of the response over the API\nexport interface UiElementSummaryApiResponse extends BaseUiDisplayResponse<\"ui.display.summary\"> {\n  title?: string;\n  items: SummaryItem[];\n}\n\n/**\n * A read-only block of label/value rows whose content is fixed by the flow at render time. For a\n * block that follows a grid's live totals, use the `summary` option of `ui.inputs.dataGrid`.\n */\nexport const summary: DisplayElementImplementation<\n  UiElementSummary,\n  UiElementSummaryApiResponse\n> = (options) => {\n  const items = options?.items;\n\n  if (!Array.isArray(items) || items.length === 0) {\n    throw new Error(\"ui.display.summary requires at least one item\");\n  }\n  for (const item of items) {\n    if (typeof item.label !== \"string\" || item.label === \"\") {\n      throw new Error(\"ui.display.summary items require a label\");\n    }\n    if (typeof item.value !== \"number\" && typeof item.value !== \"string\") {\n      throw new Error(\n        `ui.display.summary item \"${item.label}\" must have a number or string value`\n      );\n    }\n    if (item.important !== undefined && typeof item.important !== \"boolean\") {\n      throw new Error(\n        `ui.display.summary item \"${item.label}\" has a non-boolean important flag`\n      );\n    }\n  }\n\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.summary\",\n      ...(options.title && { title: options.title }),\n      items,\n    } satisfies UiElementSummaryApiResponse,\n  };\n};\n","import {\n  BaseUiDisplayResponse,\n  DisplayElementImplementation,\n  DisplayElementConfig,\n  DisplayElementResponse,\n} from \"../..\";\n\n/** The axis granularity the timeline opens at. Unset falls back to weeks on the client. */\nexport type TimelineGranularity = \"hours\" | \"days\" | \"weeks\" | \"months\";\n\n/** Items sharing a row key render as bars on a single row (e.g. the phases of one initiative). */\nexport type TimelineRow = {\n  key: string;\n  /** The row label; `title` then labels each bar. */\n  title?: string;\n};\n\n/** What `render` returns for one record. Dates may be `Date` objects or ISO 8601 strings. */\nexport type TimelineItemInput = {\n  /** The bar label, and the row label when there is no `row`. */\n  title: string;\n  start: Date | string;\n  /** Without an end the item is a point event one period wide. */\n  end?: Date | string;\n  /** A category label; the client assigns one colour per distinct value. */\n  color?: string;\n  /** 0–100, rendered as the bar's fill. */\n  progress?: number;\n  /** Items nest under a collapsible section per distinct value. */\n  group?: string;\n  row?: TimelineRow;\n};\n\n/** The item as sent over the API: dates are ISO 8601 strings. */\nexport type TimelineItem = Omit<TimelineItemInput, \"start\" | \"end\"> & {\n  start: string;\n  end?: string;\n};\n\nexport type TimelineOptions<T> = {\n  data: T[];\n  render: (data: T) => TimelineItemInput;\n  defaultGranularity?: TimelineGranularity;\n};\n\n// The types the user experiences\nexport type UiElementTimeline = <T extends any, K extends string = never>(\n  options: TimelineOptions<T> & DisplayElementConfig<K>\n) => DisplayElementResponse<K>;\n\n// The shape of the response over the API\nexport interface UiElementTimelineApiResponse extends BaseUiDisplayResponse<\"ui.display.timeline\"> {\n  data: TimelineItem[];\n  defaultGranularity?: TimelineGranularity;\n}\n\nconst granularities: TimelineGranularity[] = [\n  \"hours\",\n  \"days\",\n  \"weeks\",\n  \"months\",\n];\n\n/**\n * A Gantt-like timeline: one bar per rendered item on a scrolling time axis. The wire shape mirrors\n * the console's timeline display layout for list tools, resolved per record.\n */\nexport const timeline: DisplayElementImplementation<\n  UiElementTimeline,\n  UiElementTimelineApiResponse\n> = (options) => {\n  if (!Array.isArray(options?.data)) {\n    throw new Error(\"ui.display.timeline requires a data array\");\n  }\n  if (typeof options.render !== \"function\") {\n    throw new Error(\"ui.display.timeline requires a render function\");\n  }\n  const granularity = options.defaultGranularity;\n  if (granularity !== undefined && !granularities.includes(granularity)) {\n    throw new Error(\n      `ui.display.timeline defaultGranularity must be one of ${granularities.join(\", \")}`\n    );\n  }\n\n  const data = options.data.map((record, index) =>\n    toTimelineItem(options.render(record), index)\n  );\n\n  return {\n    key: options?.key,\n    uiConfig: {\n      __type: \"ui.display.timeline\",\n      data,\n      ...(granularity && { defaultGranularity: granularity }),\n    } satisfies UiElementTimelineApiResponse,\n  };\n};\n\nconst toTimelineItem = (\n  rendered: TimelineItemInput,\n  index: number\n): TimelineItem => {\n  const label = `ui.display.timeline item ${index}`;\n\n  if (typeof rendered?.title !== \"string\" || rendered.title === \"\") {\n    throw new Error(`${label} requires a title`);\n  }\n  const name = `${label} \"${rendered.title}\"`;\n\n  const item: TimelineItem = {\n    title: rendered.title,\n    start: toIsoDate(rendered.start, `${name} start`),\n  };\n  if (rendered.end !== undefined) {\n    item.end = toIsoDate(rendered.end, `${name} end`);\n  }\n  if (rendered.color !== undefined) {\n    if (typeof rendered.color !== \"string\") {\n      throw new Error(`${name} has a non-string color`);\n    }\n    item.color = rendered.color;\n  }\n  if (rendered.progress !== undefined) {\n    const p = rendered.progress;\n    if (typeof p !== \"number\" || !Number.isFinite(p) || p < 0 || p > 100) {\n      throw new Error(`${name} progress must be a number between 0 and 100`);\n    }\n    item.progress = p;\n  }\n  if (rendered.group !== undefined) {\n    if (typeof rendered.group !== \"string\") {\n      throw new Error(`${name} has a non-string group`);\n    }\n    item.group = rendered.group;\n  }\n  if (rendered.row !== undefined) {\n    if (typeof rendered.row?.key !== \"string\" || rendered.row.key === \"\") {\n      throw new Error(`${name} row requires a key`);\n    }\n    if (\n      rendered.row.title !== undefined &&\n      typeof rendered.row.title !== \"string\"\n    ) {\n      throw new Error(`${name} row has a non-string title`);\n    }\n    item.row = {\n      key: rendered.row.key,\n      ...(rendered.row.title !== undefined && { title: rendered.row.title }),\n    };\n  }\n\n  return item;\n};\n\n// Date objects become ISO strings; strings must parse as a date and are kept verbatim\nconst toIsoDate = (value: Date | string | undefined, what: string): string => {\n  if (value instanceof Date) {\n    if (isNaN(value.getTime())) {\n      throw new Error(`${what} is an invalid date`);\n    }\n    return value.toISOString();\n  }\n  if (typeof value !== \"string\" || isNaN(Date.parse(value))) {\n    throw new Error(`${what} must be a Date or an ISO 8601 string`);\n  }\n  return value;\n};\n","import { Kysely } from \"kysely\";\nimport { log } from \"../logger\";\n\n/**\n * How a client should present the current/total counter alongside the\n * progress bar: the raw count (\"50 of 100\"), a derived percentage (\"50%\"),\n * or no label at all (bar only). Absent means the client picks its default.\n */\nexport type ProgressCounterMode = \"count\" | \"percent\" | \"none\";\n\n/**\n * Snapshot of a step's progress as stored on keel.flow_step.progress and\n * returned by the flows API. The key set is closed so the Console always knows\n * how to render it; user-defined values live under `data`.\n */\nexport type StepProgress = {\n  /** Human-readable description of what the step is doing right now. */\n  message?: string;\n  /** How many units of work have completed. */\n  current?: number;\n  /** Total units of work, if known. Percent is derived client-side. */\n  total?: number;\n  /** What current/total count, e.g. \"rows\", \"files\", \"bytes\". */\n  unit?: string;\n  /** How the counter should be displayed. */\n  counter?: ProgressCounterMode;\n  /** Bounded, append-only activity feed (newest last). */\n  logs?: string[];\n  /** Escape hatch for arbitrary user-defined progress data. */\n  data?: Record<string, unknown>;\n  /** ISO timestamp of the last accepted update. Stamped by the runtime, not user code. */\n  updatedAt: string;\n};\n\n/** The fields user code may set directly; the rest of StepProgress is runtime-managed. */\nexport type ProgressPatch = {\n  message?: string;\n  current?: number;\n  total?: number;\n  unit?: string;\n  counter?: ProgressCounterMode;\n  data?: Record<string, unknown>;\n};\n\n/** The progress API exposed to step functions via their args. */\nexport type ProgressHandle = {\n  /** Merge the given fields into the step's progress snapshot. */\n  set(patch: ProgressPatch): void;\n  /** Increase `current` by n (default 1). */\n  increment(n?: number): void;\n  /** Append a line to the step's activity log. The log is bounded; oldest entries are dropped first. */\n  log(message: string): void;\n};\n\n// Minimum time between progress writes for one step. The first update writes\n// immediately (a UI flipping from dead spinner to real information matters\n// most); later updates coalesce so a tight loop costs at most ~1 write/sec.\nconst THROTTLE_MS = 1000;\n\n// Hard cap on the serialized envelope. Progress is a live display snapshot,\n// not a data channel; anything bigger belongs in the step's return value.\nconst MAX_PROGRESS_BYTES = 10_000;\n\n// Ring-buffer size for the activity log.\nconst MAX_LOG_ENTRIES = 50;\n\n/**\n * Writes a step's progress snapshot to keel.flow_step, throttled and\n * best-effort: progress must never fail or slow a step, so database errors are\n * logged and swallowed, and invalid updates are dropped.\n *\n * Writes go through the flow invocation's own (non-transactional) connection,\n * which is what makes mid-step progress visible to pollers immediately. If\n * steps ever become transactional this needs its own connection instead.\n */\nexport class ProgressWriter {\n  private readonly stepId: string;\n  private readonly db: Kysely<any>;\n  private readonly throttleMs: number;\n\n  private snapshot: StepProgress | null = null;\n  private dirty = false;\n  private stopped = false;\n  private timer: NodeJS.Timeout | null = null;\n  private lastWriteAt: number | null = null;\n  // Serializes writes so a slow write can't overlap (and race) the next one.\n  private writeChain: Promise<void> = Promise.resolve();\n\n  /** The user-facing API, passed to the step function. */\n  readonly handle: ProgressHandle;\n\n  constructor(options: {\n    stepId: string;\n    db: Kysely<any>;\n    throttleMs?: number;\n  }) {\n    this.stepId = options.stepId;\n    this.db = options.db;\n    this.throttleMs = options.throttleMs ?? THROTTLE_MS;\n\n    this.handle = {\n      set: (patch) => {\n        this.apply((next) => Object.assign(next, patch));\n      },\n      increment: (n = 1) => {\n        this.apply((next) => {\n          next.current = (next.current ?? 0) + n;\n        });\n      },\n      log: (message) => {\n        this.apply((next) => {\n          next.logs = [...(next.logs ?? []), message].slice(-MAX_LOG_ENTRIES);\n        });\n      },\n    };\n  }\n\n  /**\n   * Apply a mutation to a copy of the snapshot, validate it, and schedule a\n   * write. Invalid results (non-serializable, or too large to trim) are\n   * dropped whole, leaving the previous snapshot intact.\n   */\n  private apply(mutate: (next: StepProgress) => void): void {\n    if (this.stopped) {\n      return;\n    }\n\n    const next: StepProgress = this.snapshot\n      ? { ...this.snapshot, logs: this.snapshot.logs?.slice() }\n      : { updatedAt: \"\" };\n    mutate(next);\n    next.updatedAt = new Date().toISOString();\n\n    let serialized: string;\n    try {\n      serialized = JSON.stringify(next);\n    } catch (error) {\n      log.warn(\"flow progress update dropped: not serializable\", {\n        step_id: this.stepId,\n        error,\n      });\n      return;\n    }\n\n    // Over budget: sacrifice the oldest log lines first — they're the only\n    // unbounded-by-usage part of the envelope. If that isn't enough, the\n    // update itself is oversized and is dropped whole.\n    while (\n      Buffer.byteLength(serialized, \"utf8\") > MAX_PROGRESS_BYTES &&\n      (next.logs?.length ?? 0) > 1\n    ) {\n      next.logs!.shift();\n      serialized = JSON.stringify(next);\n    }\n    if (Buffer.byteLength(serialized, \"utf8\") > MAX_PROGRESS_BYTES) {\n      log.warn(\"flow progress update dropped: payload exceeds limit\", {\n        step_id: this.stepId,\n        limit_bytes: MAX_PROGRESS_BYTES,\n      });\n      return;\n    }\n\n    // Parse back so the stored snapshot is a clean clone the caller can't\n    // mutate after the fact.\n    this.snapshot = JSON.parse(serialized);\n    this.dirty = true;\n    this.scheduleWrite();\n  }\n\n  /**\n   * Leading-edge throttle: write immediately if we're outside the throttle\n   * window (including the very first update), otherwise schedule a trailing\n   * write for when the window closes.\n   */\n  private scheduleWrite(): void {\n    if (this.timer !== null) {\n      return;\n    }\n\n    const elapsed =\n      this.lastWriteAt === null ? Infinity : Date.now() - this.lastWriteAt;\n    if (elapsed >= this.throttleMs) {\n      this.enqueueWrite();\n      return;\n    }\n\n    this.timer = setTimeout(() => {\n      this.timer = null;\n      this.enqueueWrite();\n    }, this.throttleMs - elapsed);\n  }\n\n  private enqueueWrite(): Promise<void> {\n    if (!this.dirty || this.snapshot === null) {\n      return this.writeChain;\n    }\n\n    const payload = JSON.stringify(this.snapshot);\n    this.dirty = false;\n    // Stamped at enqueue time so a slow write doesn't shrink the window for\n    // the next one.\n    this.lastWriteAt = Date.now();\n\n    this.writeChain = this.writeChain.then(() => this.performWrite(payload));\n    return this.writeChain;\n  }\n\n  private async performWrite(payload: string): Promise<void> {\n    try {\n      await this.db\n        .updateTable(\"keel.flow_step\")\n        .set({ progress: payload })\n        .where(\"id\", \"=\", this.stepId)\n        .execute();\n    } catch (error) {\n      log.error(\"failed to write flow progress\", {\n        step_id: this.stepId,\n        error,\n      });\n    }\n  }\n\n  /** Write any pending snapshot now and wait for all in-flight writes. */\n  async flush(): Promise<void> {\n    if (this.timer !== null) {\n      clearTimeout(this.timer);\n      this.timer = null;\n    }\n    await this.writeChain;\n    if (this.dirty) {\n      await this.enqueueWrite();\n    }\n  }\n\n  /**\n   * Flush and retire the writer. Called when the step reaches a terminal\n   * state; later handle calls (e.g. from un-awaited promises the step leaked)\n   * are ignored rather than writing to a completed step's row.\n   */\n  async stop(): Promise<void> {\n    this.stopped = true;\n    await this.flush();\n  }\n}\n","/** A JSON-serializable file attached to a user message. `data` is base64 so\n * requests remain library-neutral and can be recorded by scripted engines. */\nexport interface AgentFile {\n  data: string;\n  mediaType: string;\n  filename: string;\n}\n\n/** A JSON-serializable message in an agent conversation. Library-neutral —\n * engine adapters map this to their provider's shape. */\nexport type AgentMessage =\n  | { role: \"user\"; content: string; files?: AgentFile[] }\n  | { role: \"assistant\"; content: string; toolCalls?: ToolCallRequest[] }\n  | { role: \"tool\"; toolCallId: string; toolName: string; result: string };\n\nexport interface ToolCallRequest {\n  id: string;\n  name: string;\n  arguments: Record<string, unknown>;\n}\n\n/** A tool as presented to the model. `parameters` is a JSON Schema object. */\nexport interface ToolSpec {\n  name: string;\n  description: string;\n  parameters: Record<string, unknown>;\n}\n\nexport interface TurnRequest {\n  model: string;\n  system?: string;\n  messages: AgentMessage[];\n  tools?: ToolSpec[];\n  /** Force the model to call a specific tool (used for structured output). */\n  toolChoice?: \"auto\" | { name: string };\n  /** The flow step this call belongs to (e.g. \"classify\" or\n   * \"OrderTriage#1/turn-2/llm\"). Attribution metadata only — engines that\n   * talk to the platform AI proxy forward it as the x-keel-flow-step header;\n   * other engines ignore it. */\n  stepName?: string;\n}\n\nexport interface TurnUsage {\n  inputTokens: number;\n  outputTokens: number;\n}\n\nexport interface TurnResult {\n  /** Empty string when the model only returned tool calls. */\n  text: string;\n  toolCalls: ToolCallRequest[];\n  usage: TurnUsage;\n  stopReason: \"end_turn\" | \"tool_calls\";\n}\n\n/** The turn primitive: ONE model call, no looping, no tool execution.\n * The flows replay engine owns the loop; adapters must never auto-execute tools. */\nexport interface TurnEngine {\n  turn(req: TurnRequest): Promise<TurnResult>;\n}\n\n/** Internal: how an injected engine rides on the flow context. */\nexport const ENGINE = Symbol.for(\"keel.agents.engine\");\n\ntype ScriptEntry = TurnResult | ((req: TurnRequest) => TurnResult);\n\n/** Deterministic fake engine for tests. Returns scripted results in order. */\nexport class ScriptedEngine implements TurnEngine {\n  private _requests: TurnRequest[] = [];\n  private index = 0;\n\n  constructor(private readonly script: ScriptEntry[]) {}\n\n  get requests(): readonly TurnRequest[] {\n    return this._requests;\n  }\n\n  async turn(req: TurnRequest): Promise<TurnResult> {\n    this._requests.push(req);\n    if (this.index >= this.script.length) {\n      throw new Error(\n        `ScriptedEngine: no scripted result for turn ${this.index + 1}`\n      );\n    }\n    const entry = this.script[this.index++];\n    return typeof entry === \"function\" ? entry(req) : entry;\n  }\n}\n\nlet callCounter = 0;\n\n/** Helpers for building scripted turns concisely in tests. */\nexport const scriptedTurn = {\n  text(text: string): TurnResult {\n    return {\n      text,\n      toolCalls: [],\n      usage: { inputTokens: 0, outputTokens: 0 },\n      stopReason: \"end_turn\",\n    };\n  },\n  /** Auto-generated ids increment per process — pass an explicit `id` when asserting on ids in tests. */\n  toolCall(\n    name: string,\n    args: Record<string, unknown>,\n    id?: string\n  ): TurnResult {\n    return {\n      text: \"\",\n      toolCalls: [\n        { id: id ?? `call_${name}_${++callCounter}`, name, arguments: args },\n      ],\n      usage: { inputTokens: 0, outputTokens: 0 },\n      stopReason: \"tool_calls\",\n    };\n  },\n};\n","import { readFileSync } from \"node:fs\";\nimport { ENGINE, type TurnEngine, ScriptedEngine } from \"./engine\";\nimport {\n  DECISION_ENGINE,\n  type DecisionEngine,\n  ScriptedDecisionEngine,\n} from \"./decision\";\nimport { TypeSafeDecisionEngine } from \"./typesafeDecisionEngine\";\nimport {\n  EXTRACTION_ENGINE,\n  type ExtractionEngine,\n  ScriptedExtractionEngine,\n} from \"./extraction\";\nimport { CloudflareExtractionEngine } from \"./cloudflareExtractionEngine\";\nimport { AiSdkEngine, sanitizeHeaderValue } from \"./aiSdkEngine\";\nimport { getServiceToken } from \"../auth/serviceTokenStore\";\n\n// Cache for the file-scripted engines. Keyed by path so tests that change the\n// env var path get a fresh engine rather than the previous file's turns.\nlet _fileScriptedEngine: { path: string; engine: ScriptedEngine } | undefined;\nlet _fileScriptedDecisionEngine:\n  | { path: string; engine: ScriptedDecisionEngine }\n  | undefined;\nlet _fileScriptedExtractionEngine:\n  | { path: string; engine: ScriptedExtractionEngine }\n  | undefined;\n\n/**\n * Resolve the turn engine for a flow invocation. Prefers an injected engine\n * (tests), then a file-scripted engine via FAKE_LLM_SCRIPT, then a live\n * Anthropic engine built from the ANTHROPIC_API_KEY secret, then the platform\n * AI gateway (the flows AI proxy). The customer's own key deliberately wins\n * over the gateway: existing users keep paying Anthropic directly until they\n * delete the secret — nobody silently migrates onto Keel billing.\n */\nexport function resolveEngine(\n  injected: TurnEngine | undefined,\n  secrets: unknown,\n  aiGateway?: { baseUrl: string },\n  runId?: string,\n  flowName?: string\n): TurnEngine {\n  if (injected) return injected;\n  const scriptPath = process.env.FAKE_LLM_SCRIPT;\n  if (scriptPath) {\n    if (!_fileScriptedEngine || _fileScriptedEngine.path !== scriptPath) {\n      const script = JSON.parse(readFileSync(scriptPath, \"utf8\"));\n      _fileScriptedEngine = {\n        path: scriptPath,\n        engine: new ScriptedEngine(script),\n      };\n    }\n    return _fileScriptedEngine.engine;\n  }\n  const key = (secrets as Record<string, string> | undefined)?.[\n    \"ANTHROPIC_API_KEY\"\n  ];\n  if (key) {\n    // OAuth access tokens (sk-ant-oat...) authenticate via Bearer; standard\n    // API keys (sk-ant-api...) via x-api-key.\n    if (key.startsWith(\"sk-ant-oat\")) {\n      return new AiSdkEngine({ authToken: key });\n    }\n    return new AiSdkEngine({ apiKey: key });\n  }\n  // Platform AI gateway (the flows AI proxy); falls through to the error\n  // below when the environment isn't fully provisioned.\n  const proxy = gatewayProxy(aiGateway, runId, flowName);\n  if (proxy) {\n    // The provider segment is hard-coded to anthropic for now; it will be\n    // derived from the model prefix when multi-provider lands (Phase 1.5).\n    // The AI SDK provider appends /messages to this base URL.\n    return new AiSdkEngine({\n      baseURL: `${proxy.root}/flows/ai-proxy/anthropic/v1`,\n      proxyToken: proxy.token,\n      headers: proxy.headers,\n    });\n  }\n  throw new Error(\n    \"No LLM engine available — set the ANTHROPIC_API_KEY secret, run on the hosted Keel platform (which provides an AI gateway), or inject an engine in tests\"\n  );\n}\n\n/**\n * The platform AI proxy connection for this invocation, or undefined when the\n * environment isn't provisioned for it. Needs BOTH the gateway base URL\n * (delivered in the invoke meta) and the runtime-minted ai-proxy service token.\n *\n * aiGateway.baseUrl is the proxy worker's ROOT URL — callers append the route\n * path so the platform config stays a provider-agnostic root. Attribution\n * headers are for the gateway path ONLY — direct-to-provider calls with a\n * customer key must not gain custom headers. Values are sanitized because flow\n * names are schema-author-controlled.\n */\nfunction gatewayProxy(\n  aiGateway: { baseUrl: string } | undefined,\n  runId: string | undefined,\n  flowName: string | undefined\n):\n  | { root: string; token: string; headers: Record<string, string> | undefined }\n  | undefined {\n  if (!aiGateway?.baseUrl) return undefined;\n  const token = getServiceToken(\"ai-proxy\");\n  if (!token) return undefined;\n  let root = aiGateway.baseUrl;\n  while (root.endsWith(\"/\")) {\n    root = root.slice(0, -1);\n  }\n  const headers: Record<string, string> = {};\n  const runIdValue = runId ? sanitizeHeaderValue(runId) : \"\";\n  if (runIdValue) headers[\"x-keel-flow-run-id\"] = runIdValue;\n  const flowNameValue = flowName ? sanitizeHeaderValue(flowName) : \"\";\n  if (flowNameValue) headers[\"x-keel-flow-name\"] = flowNameValue;\n  return {\n    root,\n    token,\n    headers: Object.keys(headers).length > 0 ? headers : undefined,\n  };\n}\n\n/**\n * Read the engine that the flow context wired onto itself via the ENGINE\n * symbol. This is how agent + LLM steps reach the engine without the engine\n * being part of the public flow context type.\n */\nexport function resolveEngineForContext(context: unknown): TurnEngine {\n  const get = (context as any)?.[ENGINE];\n  if (typeof get !== \"function\") {\n    throw new Error(\"An LLM engine is only available within a flow context\");\n  }\n  return get();\n}\n\n/**\n * Resolve the decision engine for a flow invocation: an injected engine\n * (tests), then a file-scripted engine via FAKE_DECIDE_SCRIPT, then the\n * platform AI gateway. There is no customer-key path: Jev is only reachable\n * through the platform's Cloudflare AI Gateway.\n */\nexport function resolveDecisionEngine(\n  injected: DecisionEngine | undefined,\n  aiGateway?: { baseUrl: string },\n  runId?: string,\n  flowName?: string\n): DecisionEngine {\n  if (injected) return injected;\n  const scriptPath = process.env.FAKE_DECIDE_SCRIPT;\n  if (scriptPath) {\n    if (\n      !_fileScriptedDecisionEngine ||\n      _fileScriptedDecisionEngine.path !== scriptPath\n    ) {\n      const script = JSON.parse(readFileSync(scriptPath, \"utf8\"));\n      _fileScriptedDecisionEngine = {\n        path: scriptPath,\n        engine: new ScriptedDecisionEngine(script),\n      };\n    }\n    return _fileScriptedDecisionEngine.engine;\n  }\n  const proxy = gatewayProxy(aiGateway, runId, flowName);\n  if (proxy) {\n    // The engine POSTs to <baseURL>/systemone.\n    return new TypeSafeDecisionEngine({\n      baseURL: `${proxy.root}/flows/ai-proxy/typesafe/v1`,\n      proxyToken: proxy.token,\n      headers: proxy.headers,\n    });\n  }\n  throw new Error(\n    \"No decision engine available — decide steps run on the hosted Keel platform (which provides an AI gateway), or inject a decision engine in tests\"\n  );\n}\n\n/** Read the decision engine the flow context wired onto itself via the\n * DECISION_ENGINE symbol. */\nexport function resolveDecisionEngineForContext(\n  context: unknown\n): DecisionEngine {\n  const get = (context as any)?.[DECISION_ENGINE];\n  if (typeof get !== \"function\") {\n    throw new Error(\n      \"A decision engine is only available within a flow context\"\n    );\n  }\n  return get();\n}\n\n/**\n * Resolve the extraction engine for a flow invocation: an injected engine\n * (tests), then a file-scripted engine via FAKE_EXTRACT_SCRIPT, then the\n * platform AI gateway. There is no customer-key path: Clairic runs on Workers\n * AI behind the platform's Cloudflare AI Gateway.\n */\nexport function resolveExtractionEngine(\n  injected: ExtractionEngine | undefined,\n  aiGateway?: { baseUrl: string },\n  runId?: string,\n  flowName?: string\n): ExtractionEngine {\n  if (injected) return injected;\n  const scriptPath = process.env.FAKE_EXTRACT_SCRIPT;\n  if (scriptPath) {\n    if (\n      !_fileScriptedExtractionEngine ||\n      _fileScriptedExtractionEngine.path !== scriptPath\n    ) {\n      const script = JSON.parse(readFileSync(scriptPath, \"utf8\"));\n      _fileScriptedExtractionEngine = {\n        path: scriptPath,\n        engine: new ScriptedExtractionEngine(script),\n      };\n    }\n    return _fileScriptedExtractionEngine.engine;\n  }\n  const proxy = gatewayProxy(aiGateway, runId, flowName);\n  if (proxy) {\n    // The engine POSTs to <baseURL>/extract.\n    return new CloudflareExtractionEngine({\n      baseURL: `${proxy.root}/flows/ai-proxy/cloudflare/v1`,\n      proxyToken: proxy.token,\n      headers: proxy.headers,\n    });\n  }\n  throw new Error(\n    \"No extraction engine available — extract steps run on the hosted Keel platform (which provides an AI gateway), or inject an extraction engine in tests\"\n  );\n}\n\n/** Read the extraction engine the flow context wired onto itself via the\n * EXTRACTION_ENGINE symbol. */\nexport function resolveExtractionEngineForContext(\n  context: unknown\n): ExtractionEngine {\n  const get = (context as any)?.[EXTRACTION_ENGINE];\n  if (typeof get !== \"function\") {\n    throw new Error(\n      \"An extraction engine is only available within a flow context\"\n    );\n  }\n  return get();\n}\n","/** A JSON-serializable value: the state being decided about, or a question's\n * instructions and criteria. */\nexport type DecideValue =\n  | string\n  | number\n  | boolean\n  | null\n  | DecideValue[]\n  | { [key: string]: DecideValue };\n\n/** A yes/no question. The answer is the probability that it is true. */\nexport interface BooleanQuestion {\n  type: \"boolean\";\n  instructions: DecideValue;\n  /** Optional descriptions of what counts as true and false. */\n  criteria?: { true?: DecideValue; false?: DecideValue };\n}\n\n/** Pick one option. `criteria` maps each option to its description (or null). */\nexport interface ChoiceQuestion<K extends string = string> {\n  type: \"choice\";\n  instructions: DecideValue;\n  criteria: Record<K, DecideValue>;\n}\n\n/** Rate on an ordered rubric, lowest first. The answer's `score` is a\n * zero-based index and may fall between levels. */\nexport interface ScoreQuestion {\n  type: \"score\";\n  instructions: DecideValue;\n  criteria: readonly [DecideValue, DecideValue, ...DecideValue[]];\n}\n\nexport type DecideQuestion = BooleanQuestion | ChoiceQuestion | ScoreQuestion;\n\nexport interface BooleanAnswer {\n  type: \"boolean\";\n  /** P(true), from 0 to 1. */\n  probability: number;\n}\n\nexport interface ChoiceAnswer<K extends string = string> {\n  type: \"choice\";\n  choice: K;\n  /** How concentrated the distribution is. Absent when the backing model\n   * does not report one (e.g. an LLM rather than a decision model). */\n  confidence?: number;\n  probabilities?: Record<K, number>;\n}\n\nexport interface ScoreAnswer {\n  type: \"score\";\n  score: number;\n  confidence?: number;\n  /** Keyed by zero-based level index. */\n  probabilities?: Record<string, number>;\n}\n\nexport type DecideAnswer = BooleanAnswer | ChoiceAnswer | ScoreAnswer;\n\n/** The answer type for a question, keeping choice keys as a literal union. */\nexport type AnswerFor<Q extends DecideQuestion> = Q extends {\n  type: \"choice\";\n  criteria: infer C;\n}\n  ? ChoiceAnswer<keyof C & string>\n  : Q extends { type: \"score\" }\n    ? ScoreAnswer\n    : BooleanAnswer;\n\nexport interface DecideRequest {\n  /** Provider-prefixed model, e.g. \"typesafe/jev\". */\n  model: string;\n  state: DecideValue;\n  questions: Record<string, DecideQuestion>;\n  /** The flow step this call belongs to. Attribution metadata only, as on\n   * TurnRequest. */\n  stepName?: string;\n}\n\nexport interface DecideResult {\n  answers: Record<string, DecideAnswer>;\n  /** The model that answered. */\n  model: string;\n  usage: { inputTokens: number; outputTokens: number };\n}\n\n/** One decision-model call. Library-neutral, so the backing model (Jev, Clef,\n * an OpenAI decision model, an LLM) can change without touching the step. */\nexport interface DecisionEngine {\n  decide(req: DecideRequest): Promise<DecideResult>;\n}\n\n/** Internal: how an injected decision engine rides on the flow context. */\nexport const DECISION_ENGINE = Symbol.for(\"keel.agents.decisionEngine\");\n\ntype ScriptEntry =\n  | DecideResult\n  | Record<string, DecideAnswer>\n  | ((req: DecideRequest) => DecideResult);\n\n/** Deterministic fake decision engine for tests. Returns scripted results in\n * order; an entry may be a full DecideResult or just its answers. */\nexport class ScriptedDecisionEngine implements DecisionEngine {\n  private _requests: DecideRequest[] = [];\n  private index = 0;\n\n  constructor(private readonly script: ScriptEntry[]) {}\n\n  get requests(): readonly DecideRequest[] {\n    return this._requests;\n  }\n\n  async decide(req: DecideRequest): Promise<DecideResult> {\n    this._requests.push(req);\n    if (this.index >= this.script.length) {\n      throw new Error(\n        `ScriptedDecisionEngine: no scripted result for decision ${this.index + 1}`\n      );\n    }\n    const entry = this.script[this.index++];\n    if (typeof entry === \"function\") return entry(req);\n    if (isDecideResult(entry)) return entry;\n    return {\n      answers: entry as Record<string, DecideAnswer>,\n      model: req.model,\n      usage: { inputTokens: 0, outputTokens: 0 },\n    };\n  }\n}\n\nfunction isDecideResult(entry: object): entry is DecideResult {\n  return (\n    \"answers\" in entry &&\n    \"usage\" in entry &&\n    typeof (entry as DecideResult).model === \"string\"\n  );\n}\n","import {\n  generateText,\n  jsonSchema,\n  tool,\n  stepCountIs,\n  type ModelMessage,\n  type LanguageModel,\n} from \"ai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport type {\n  AgentMessage,\n  TurnEngine,\n  TurnRequest,\n  TurnResult,\n} from \"./engine\";\n\nexport interface AiSdkEngineOptions {\n  /** Standard API key (sk-ant-api...), sent as x-api-key. */\n  apiKey?: string;\n  /** Bearer token (sk-ant-oat... OAuth tokens), sent as Authorization: Bearer\n   * together with the anthropic-beta oauth header. */\n  authToken?: string;\n  /** Scoped bearer token minted by the Keel runtime for the platform AI proxy,\n   * sent as Authorization: Bearer. Unlike authToken, NO anthropic-beta oauth\n   * header is attached — the proxy fronts the standard Messages API. */\n  proxyToken?: string;\n  /** Override the provider base URL (e.g. the platform AI proxy). Must end in\n   * /v1 — the provider appends /messages verbatim. */\n  baseURL?: string;\n  /** Extra headers merged into every request (e.g. x-keel-flow-run-id and\n   * x-keel-flow-name for usage attribution at the platform AI proxy). Also\n   * acts as the signal that per-call attribution headers (x-keel-flow-step)\n   * should be sent — it is only ever set on the proxy path. */\n  headers?: Record<string, string>;\n}\n\n// Header values must be safe to place on the wire. Flow and step names are\n// schema-author-controlled, so header injection via exotic names must be\n// impossible: keep printable ASCII only (no CR/LF, no control chars, no\n// non-ASCII) and cap the length.\nconst MAX_HEADER_VALUE_LENGTH = 256;\n\n/** Sanitize a string for use as an HTTP header value: strips everything\n * outside printable ASCII (0x20–0x7E) and truncates to 256 chars. Returns \"\"\n * when nothing survives — callers should omit the header in that case. */\nexport function sanitizeHeaderValue(value: string): string {\n  return value\n    .replace(/[^\\x20-\\x7e]/g, \"\")\n    .slice(0, MAX_HEADER_VALUE_LENGTH)\n    .trim();\n}\n\n/** Reference TurnEngine over the Vercel AI SDK. One turn per call: tools are\n * declared WITHOUT execute functions, so generateText returns tool calls\n * without running them or looping. */\nexport class AiSdkEngine implements TurnEngine {\n  constructor(private opts: AiSdkEngineOptions) {}\n\n  // Exposed as a method (not arrow function) so tests can monkey-patch at the\n  // instance level: (engine as any).resolveModel = () => mockModel(...)\n  resolveModel(model: string): LanguageModel {\n    const slash = model.indexOf(\"/\");\n    const provider = slash === -1 ? \"anthropic\" : model.slice(0, slash);\n    const id = slash === -1 ? model : model.slice(slash + 1);\n    if (provider !== \"anthropic\") {\n      throw new Error(\n        `Unsupported provider \"${provider}\" in model \"${model}\" — only anthropic/* is supported in this milestone`\n      );\n    }\n    // Endpoint comes from injected config ONLY — never from ambient env.\n    // (The AI SDK would otherwise read ANTHROPIC_BASE_URL, which uses a\n    // different convention than Anthropic's own SDK and silently 404s.)\n    const baseURL = this.opts.baseURL ?? \"https://api.anthropic.com/v1\";\n    if (this.opts.proxyToken) {\n      // Platform AI proxy auth: blank the x-api-key header the provider would\n      // set and authenticate via Authorization. Deliberately WITHOUT the\n      // anthropic-beta oauth header — that header is OAuth-token-specific and\n      // the proxy fronts the standard Messages API.\n      return createAnthropic({\n        apiKey: \"unused\",\n        baseURL,\n        headers: {\n          \"x-api-key\": \"\",\n          authorization: `Bearer ${this.opts.proxyToken}`,\n          ...this.opts.headers,\n        },\n      })(id);\n    }\n    if (this.opts.authToken) {\n      // Bearer-token auth: blank the x-api-key header the provider would set\n      // and authenticate via Authorization. OAuth tokens additionally need the\n      // oauth beta header.\n      return createAnthropic({\n        apiKey: \"unused\",\n        baseURL,\n        headers: {\n          \"x-api-key\": \"\",\n          authorization: `Bearer ${this.opts.authToken}`,\n          \"anthropic-beta\": \"oauth-2025-04-20\",\n          ...this.opts.headers,\n        },\n      })(id);\n    }\n    if (!this.opts.apiKey) {\n      throw new Error(\n        \"AiSdkEngine requires an apiKey, authToken or proxyToken\"\n      );\n    }\n    return createAnthropic({\n      apiKey: this.opts.apiKey,\n      baseURL,\n      headers: this.opts.headers,\n    })(id);\n  }\n\n  async turn(req: TurnRequest): Promise<TurnResult> {\n    const model = this.resolveModel(req.model);\n\n    // Build AI SDK tools (NO execute functions — we never auto-run tools)\n    const tools: Record<string, ReturnType<typeof tool>> = {};\n    for (const spec of req.tools ?? []) {\n      tools[spec.name] = tool({\n        description: spec.description,\n        inputSchema: jsonSchema(\n          spec.parameters as Parameters<typeof jsonSchema>[0]\n        ),\n      });\n    }\n\n    // Map toolChoice\n    let toolChoice: \"auto\" | { type: \"tool\"; toolName: string } | undefined;\n    if (req.toolChoice === \"auto\") {\n      toolChoice = \"auto\";\n    } else if (req.toolChoice && typeof req.toolChoice === \"object\") {\n      toolChoice = { type: \"tool\", toolName: req.toolChoice.name };\n    }\n\n    // Map our AgentMessage union to AI SDK ModelMessage array\n    const messages: ModelMessage[] = req.messages.map((msg): ModelMessage => {\n      if (msg.role === \"user\") {\n        if (!msg.files?.length) {\n          return { role: \"user\", content: msg.content };\n        }\n\n        return {\n          role: \"user\",\n          content: [\n            { type: \"text\", text: msg.content },\n            ...msg.files.map((file) => ({\n              type: \"file\" as const,\n              data: file.data,\n              filename: file.filename,\n              mediaType: file.mediaType,\n            })),\n          ],\n        };\n      }\n      if (msg.role === \"assistant\") {\n        // Build content array: text part + tool-call parts\n        const content: Array<\n          | { type: \"text\"; text: string }\n          | {\n              type: \"tool-call\";\n              toolCallId: string;\n              toolName: string;\n              input: unknown;\n            }\n        > = [];\n        if (msg.content) {\n          content.push({ type: \"text\", text: msg.content });\n        }\n        for (const tc of msg.toolCalls ?? []) {\n          content.push({\n            type: \"tool-call\",\n            toolCallId: tc.id,\n            toolName: tc.name,\n            input: tc.arguments,\n          });\n        }\n        return { role: \"assistant\", content };\n      }\n      // role === \"tool\"\n      return {\n        role: \"tool\",\n        content: [\n          {\n            type: \"tool-result\",\n            toolCallId: msg.toolCallId,\n            toolName: msg.toolName,\n            output: { type: \"text\", value: msg.result },\n          },\n        ],\n      };\n    });\n\n    // Per-call step attribution, only on the platform AI proxy path (which is\n    // the only path that sets opts.headers). Direct-to-Anthropic calls with a\n    // customer key must not gain custom headers. The AI SDK combines per-call\n    // headers with the provider-level ones per key (combineHeaders in\n    // @ai-sdk/anthropic), so the run-id/flow-name headers are preserved.\n    const stepHeader =\n      this.opts.headers && req.stepName\n        ? sanitizeHeaderValue(req.stepName)\n        : \"\";\n\n    let res;\n    try {\n      res = await generateText({\n        model,\n        system: req.system,\n        messages,\n        tools: Object.keys(tools).length > 0 ? tools : undefined,\n        toolChoice,\n        stopWhen: stepCountIs(1),\n        headers: stepHeader ? { \"x-keel-flow-step\": stepHeader } : undefined,\n      });\n    } catch (e) {\n      // The AI SDK's RetryError/APICallError messages are often just \"Error\" —\n      // unwrap them so step errors are actually debuggable.\n      throw new Error(describeAiError(e));\n    }\n\n    // Map result back to TurnResult\n    const toolCalls = res.toolCalls.map((tc) => ({\n      id: tc.toolCallId,\n      name: tc.toolName,\n      arguments: tc.input as Record<string, unknown>,\n    }));\n\n    return {\n      text: res.text,\n      toolCalls,\n      usage: {\n        inputTokens: res.usage.inputTokens ?? 0,\n        outputTokens: res.usage.outputTokens ?? 0,\n      },\n      stopReason: toolCalls.length > 0 ? \"tool_calls\" : \"end_turn\",\n    };\n  }\n}\n\n/** Produce a human-debuggable message from AI SDK errors: unwrap RetryError\n * to its last attempt and surface APICallError status + response body. */\nfunction describeAiError(e: unknown): string {\n  // RetryError: the interesting error is the last attempt's\n  const errors = (e as { errors?: unknown[] })?.errors;\n  const last = errors && errors.length > 0 ? errors[errors.length - 1] : e;\n  const err = last as {\n    name?: string;\n    message?: string;\n    statusCode?: number;\n    responseBody?: string;\n    url?: string;\n  };\n  let msg = \"LLM request failed\";\n  if (err?.statusCode) msg += ` (HTTP ${err.statusCode})`;\n  const detail =\n    err?.responseBody?.slice(0, 300) ||\n    (err?.message && err.message !== \"Error\" ? err.message : undefined);\n  if (detail) msg += `: ${detail}`;\n  if (err?.url) msg += ` [${err.url}]`;\n  return msg;\n}\n","import type {\n  DecideAnswer,\n  DecideQuestion,\n  DecideRequest,\n  DecideResult,\n  DecisionEngine,\n} from \"./decision\";\nimport { sanitizeHeaderValue } from \"./aiSdkEngine\";\nimport { NonRetriableError } from \"../flows/errors\";\n\nexport interface TypeSafeDecisionEngineOptions {\n  /** Base URL of a TypeSafe \"System One\" API; the engine POSTs to\n   * `${baseURL}/systemone`. On the platform this is the flows AI proxy. */\n  baseURL: string;\n  /** Scoped bearer token minted by the Keel runtime for the platform AI proxy. */\n  proxyToken: string;\n  /** Extra headers merged into every request (the x-keel-flow-* attribution\n   * headers). */\n  headers?: Record<string, string>;\n}\n\n// Wire shapes of the System One API (Jev, and Jev-compatible models such as\n// Clef). Yes/no questions are called \"noul\" there.\ntype WireQuestion =\n  | { type: \"noul\"; instructions: unknown; criteria?: unknown }\n  | { type: \"choice\" | \"score\"; instructions: unknown; criteria: unknown };\n\ntype WireAnswer =\n  | { type: \"noul\"; noul: number }\n  | {\n      type: \"choice\";\n      choice: string;\n      confidence?: number;\n      probabilities?: Record<string, number>;\n    }\n  | {\n      type: \"score\";\n      score: number;\n      confidence?: number;\n      probabilities?: Record<string, number>;\n    };\n\ninterface WireResponse {\n  model?: string;\n  answers?: Record<string, WireAnswer>;\n  usage?: { input_tokens?: number; output_tokens?: number };\n}\n\nfunction toWireQuestion(q: DecideQuestion): WireQuestion {\n  if (q.type === \"boolean\") {\n    return {\n      type: \"noul\",\n      instructions: q.instructions,\n      ...(q.criteria ? { criteria: q.criteria } : {}),\n    };\n  }\n  return { type: q.type, instructions: q.instructions, criteria: q.criteria };\n}\n\nfunction fromWireAnswer(a: WireAnswer): DecideAnswer {\n  if (a.type === \"noul\") {\n    return { type: \"boolean\", probability: a.noul };\n  }\n  if (a.type === \"choice\") {\n    return {\n      type: \"choice\",\n      choice: a.choice,\n      ...(a.confidence !== undefined ? { confidence: a.confidence } : {}),\n      ...(a.probabilities ? { probabilities: a.probabilities } : {}),\n    };\n  }\n  return {\n    type: \"score\",\n    score: a.score,\n    ...(a.confidence !== undefined ? { confidence: a.confidence } : {}),\n    ...(a.probabilities ? { probabilities: a.probabilities } : {}),\n  };\n}\n\n/** DecisionEngine over the TypeSafe System One API. Accepts \"typesafe/*\"\n * models and forwards the model id unchanged; the proxy decides which models\n * it serves. */\nexport class TypeSafeDecisionEngine implements DecisionEngine {\n  constructor(private opts: TypeSafeDecisionEngineOptions) {}\n\n  async decide(req: DecideRequest): Promise<DecideResult> {\n    const slash = req.model.indexOf(\"/\");\n    const provider = slash === -1 ? \"\" : req.model.slice(0, slash);\n    if (provider !== \"typesafe\") {\n      throw new NonRetriableError(\n        `Unsupported decision model \"${req.model}\" — only typesafe/* models are supported`\n      );\n    }\n\n    const questions: Record<string, WireQuestion> = {};\n    for (const [name, q] of Object.entries(req.questions)) {\n      questions[name] = toWireQuestion(q);\n    }\n\n    // Per-call step attribution only when attribution headers are configured,\n    // which is only on the platform AI proxy path (mirrors AiSdkEngine).\n    const stepHeader =\n      this.opts.headers && req.stepName\n        ? sanitizeHeaderValue(req.stepName)\n        : \"\";\n\n    // The same key for every attempt of one step in one run, so the proxy can\n    // answer a retry from the first attempt's result instead of evaluating\n    // (and billing) the question again.\n    const runId = this.opts.headers?.[\"x-keel-flow-run-id\"];\n    const idempotencyKey = runId && stepHeader ? `${runId}:${stepHeader}` : \"\";\n\n    let root = this.opts.baseURL;\n    while (root.endsWith(\"/\")) root = root.slice(0, -1);\n\n    const res = await fetch(`${root}/systemone`, {\n      method: \"POST\",\n      headers: {\n        \"content-type\": \"application/json\",\n        authorization: `Bearer ${this.opts.proxyToken}`,\n        ...this.opts.headers,\n        ...(stepHeader ? { \"x-keel-flow-step\": stepHeader } : {}),\n        ...(idempotencyKey ? { \"idempotency-key\": idempotencyKey } : {}),\n      },\n      body: JSON.stringify({ model: req.model, state: req.state, questions }),\n    });\n\n    if (!res.ok) {\n      const detail = (await res.text().catch(() => \"\")).slice(0, 300);\n      const msg = `Decision request failed (HTTP ${res.status})${detail ? `: ${detail}` : \"\"}`;\n      // The request itself is wrong (bad question shape, unsupported model):\n      // retrying the step won't help. Everything else may be transient.\n      if (res.status === 400 || res.status === 404 || res.status === 422) {\n        throw new NonRetriableError(msg);\n      }\n      throw new Error(msg);\n    }\n\n    const body = (await res.json()) as WireResponse;\n    if (!body.answers || typeof body.answers !== \"object\") {\n      throw new Error(\"Decision response had no answers\");\n    }\n\n    const answers: Record<string, DecideAnswer> = {};\n    for (const [name, a] of Object.entries(body.answers)) {\n      answers[name] = fromWireAnswer(a);\n    }\n\n    return {\n      answers,\n      model: body.model ?? req.model,\n      usage: {\n        inputTokens: body.usage?.input_tokens ?? 0,\n        outputTokens: body.usage?.output_tokens ?? 0,\n      },\n    };\n  }\n}\n","import type { DecideValue } from \"./decision\";\n\ninterface FieldBase {\n  /** What the field should contain, in plain language. */\n  instructions?: string;\n  /** Probability of \"not in the input\" above which the value is null\n   * (default 0.5). Raise it to get more guesses, lower it to get more nulls. */\n  nullThreshold?: number;\n}\n\n/** A span of the input text. */\nexport interface TextField extends FieldBase {\n  type: \"text\";\n}\n\nexport interface NumberField extends FieldBase {\n  type: \"number\";\n  integer?: boolean;\n  /** 0 to 6. */\n  decimals?: number;\n  /** Unit label, e.g. \"USD\" or \"kg\". */\n  unit?: string;\n}\n\n/** An ISO date (`YYYY-MM-DD`), time or datetime. */\nexport interface DateField extends FieldBase {\n  type: \"date\" | \"time\" | \"datetime\";\n}\n\n/** A length of time as a number of `unit`s. */\nexport interface DurationField extends FieldBase {\n  type: \"duration\";\n  unit?:\n    | \"seconds\"\n    | \"minutes\"\n    | \"hours\"\n    | \"days\"\n    | \"weeks\"\n    | \"months\"\n    | \"years\";\n  integer?: boolean;\n  decimals?: number;\n}\n\n/** Every matching item, in input order. */\nexport interface ListField extends FieldBase {\n  type: \"list\";\n  items: \"text\" | \"number\" | \"date\";\n  decimals?: number;\n}\n\n/** A value the input implies but may not state, as a distribution between\n * `min` and `max`. Numbers, or ISO dates for a date estimate. */\nexport interface EstimateField extends FieldBase {\n  type: \"estimate\";\n  min: number | string;\n  max: number | string;\n  /** Grid size: a number (days for a date estimate), or \"month\" / \"year\". */\n  step?: number | \"month\" | \"year\";\n  scale?: \"linear\" | \"log\";\n}\n\nexport type ExtractField =\n  | TextField\n  | NumberField\n  | DateField\n  | DurationField\n  | ListField\n  | EstimateField;\n\ninterface ScalarAnswerBase<T> {\n  /** The answer, or null when the input does not determine it. */\n  value: T | null;\n  /** The best guess even when `value` is null. */\n  guess?: T | null;\n  /** Probability that the input does not contain the value, 0 to 1. */\n  pNull?: number;\n  /** Confidence in `value`, 0 to 1. */\n  confidence?: number;\n}\n\nexport interface TextAnswer extends ScalarAnswerBase<string> {\n  type: \"text\";\n  /** [start, end) character offsets into `state`. Only present when `state`\n   * was a string. */\n  span?: [number, number];\n}\n\nexport interface NumberAnswer extends ScalarAnswerBase<number> {\n  type: \"number\";\n}\n\nexport interface DateAnswer<\n  T extends DateField[\"type\"] = DateField[\"type\"],\n> extends ScalarAnswerBase<string> {\n  type: T;\n}\n\nexport interface DurationAnswer extends ScalarAnswerBase<number> {\n  type: \"duration\";\n}\n\nexport interface ListAnswer<T = string | number> {\n  type: \"list\";\n  value: T[];\n  /** One [start, end) offset pair per item. Only present when `state` was a\n   * string. */\n  spans?: [number, number][];\n  confidence?: number;\n}\n\nexport interface EstimateAnswer<T = number | string> {\n  type: \"estimate\";\n  /** Point estimate. */\n  value: T | null;\n  mean?: T;\n  median?: T;\n  /** p10..p90 is the 80% interval. */\n  p10?: T;\n  p90?: T;\n  /** Probability that the true value is below `min` / above `max`. */\n  pBelow?: number;\n  pAbove?: number;\n}\n\nexport type ExtractAnswer =\n  | TextAnswer\n  | NumberAnswer\n  | DateAnswer\n  | DurationAnswer\n  | ListAnswer\n  | EstimateAnswer;\n\n/** The answer type for a field: list items and date estimates come back as\n * strings, everything numeric as numbers. */\nexport type ExtractAnswerFor<F extends ExtractField> = F extends TextField\n  ? TextAnswer\n  : F extends NumberField\n    ? NumberAnswer\n    : F extends DateField\n      ? DateAnswer<F[\"type\"]>\n      : F extends DurationField\n        ? DurationAnswer\n        : F extends ListField\n          ? ListAnswer<F[\"items\"] extends \"number\" ? number : string>\n          : F extends EstimateField\n            ? EstimateAnswer<F[\"min\"] extends string ? string : number>\n            : never;\n\n/** An image to read alongside the state: PNG, JPEG or WebP. */\nexport interface ExtractImage {\n  contentType: string;\n  base64: string;\n}\n\nexport interface ExtractRequest {\n  /** Provider-prefixed model, e.g. \"cloudflare/clairic\". */\n  model: string;\n  /** Text to read from. JSON state is serialised before it is sent. */\n  state: string;\n  fields: Record<string, ExtractField>;\n  images?: ExtractImage[];\n  /** ISO date that anchors dates written without a year. */\n  referenceDate?: string;\n  /** The flow step this call belongs to. Attribution metadata only. */\n  stepName?: string;\n}\n\nexport interface ExtractResult {\n  answers: Record<string, ExtractAnswer>;\n  /** True when the input was too long and was cut before it was read. */\n  truncated: boolean;\n  model: string;\n  usage: { inputTokens: number; outputTokens: number };\n}\n\n/** One extraction-model call. Library-neutral, so the backing model can\n * change without touching the step. */\nexport interface ExtractionEngine {\n  extract(req: ExtractRequest): Promise<ExtractResult>;\n}\n\n/** Internal: how an injected extraction engine rides on the flow context. */\nexport const EXTRACTION_ENGINE = Symbol.for(\"keel.agents.extractionEngine\");\n\ntype ScriptEntry =\n  | ExtractResult\n  | Record<string, ExtractAnswer>\n  | ((req: ExtractRequest) => ExtractResult);\n\n/** Deterministic fake extraction engine for tests. Returns scripted results\n * in order; an entry may be a full ExtractResult or just its answers. */\nexport class ScriptedExtractionEngine implements ExtractionEngine {\n  private _requests: ExtractRequest[] = [];\n  private index = 0;\n\n  constructor(private readonly script: ScriptEntry[]) {}\n\n  get requests(): readonly ExtractRequest[] {\n    return this._requests;\n  }\n\n  async extract(req: ExtractRequest): Promise<ExtractResult> {\n    this._requests.push(req);\n    if (this.index >= this.script.length) {\n      throw new Error(\n        `ScriptedExtractionEngine: no scripted result for extraction ${this.index + 1}`\n      );\n    }\n    const entry = this.script[this.index++];\n    if (typeof entry === \"function\") return entry(req);\n    if (isExtractResult(entry)) return entry;\n    return {\n      answers: entry as Record<string, ExtractAnswer>,\n      truncated: false,\n      model: req.model,\n      usage: { inputTokens: 0, outputTokens: 0 },\n    };\n  }\n}\n\nfunction isExtractResult(entry: object): entry is ExtractResult {\n  return (\n    \"answers\" in entry &&\n    \"usage\" in entry &&\n    typeof (entry as ExtractResult).model === \"string\"\n  );\n}\n\n/** The state an extract step reads from: text, or any JSON value. */\nexport type ExtractState = DecideValue;\n","import type {\n  ExtractAnswer,\n  ExtractField,\n  ExtractRequest,\n  ExtractResult,\n  ExtractionEngine,\n} from \"./extraction\";\nimport { sanitizeHeaderValue } from \"./aiSdkEngine\";\nimport { NonRetriableError } from \"../flows/errors\";\n\nexport interface CloudflareExtractionEngineOptions {\n  /** Base URL of the extraction API; the engine POSTs to `${baseURL}/extract`.\n   * On the platform this is the flows AI proxy, which runs the request on\n   * Workers AI. */\n  baseURL: string;\n  /** Scoped bearer token minted by the Keel runtime for the platform AI proxy. */\n  proxyToken: string;\n  /** Extra headers merged into every request (the x-keel-flow-* attribution\n   * headers). */\n  headers?: Record<string, string>;\n}\n\n// Wire shapes of the Clairic API (Workers AI \"@cf/cloudflare/clairic\").\ntype WireField = Record<string, unknown> & { type: string };\n\ntype WireAnswer = Record<string, unknown> & { type: string; value: unknown };\n\ninterface WireResponse {\n  model?: string;\n  answers?: Record<string, WireAnswer>;\n  truncated?: boolean;\n  usage?: { input_tokens?: number; output_tokens?: number };\n}\n\nfunction toWireField(f: ExtractField): WireField {\n  const { nullThreshold, ...rest } = f;\n  return {\n    ...rest,\n    ...(nullThreshold !== undefined ? { null_threshold: nullThreshold } : {}),\n  };\n}\n\n// Rename the snake_case probability keys and drop anything the step does not\n// expose (quantiles, forecast steps), so the persisted result stays small.\nfunction fromWireAnswer(a: WireAnswer): ExtractAnswer {\n  const out: Record<string, unknown> = { type: a.type, value: a.value };\n  const copy: [string, string][] = [\n    [\"guess\", \"guess\"],\n    [\"p_null\", \"pNull\"],\n    [\"confidence\", \"confidence\"],\n    [\"span\", \"span\"],\n    [\"spans\", \"spans\"],\n    [\"mean\", \"mean\"],\n    [\"median\", \"median\"],\n    [\"p10\", \"p10\"],\n    [\"p90\", \"p90\"],\n    [\"p_below\", \"pBelow\"],\n    [\"p_above\", \"pAbove\"],\n  ];\n  for (const [from, to] of copy) {\n    if (a[from] !== undefined) out[to] = a[from];\n  }\n  return out as unknown as ExtractAnswer;\n}\n\n/** ExtractionEngine over the Clairic API. Accepts \"cloudflare/*\" models and\n * forwards the model id unchanged; the proxy decides which models it serves. */\nexport class CloudflareExtractionEngine implements ExtractionEngine {\n  constructor(private opts: CloudflareExtractionEngineOptions) {}\n\n  async extract(req: ExtractRequest): Promise<ExtractResult> {\n    const slash = req.model.indexOf(\"/\");\n    const provider = slash === -1 ? \"\" : req.model.slice(0, slash);\n    if (provider !== \"cloudflare\") {\n      throw new NonRetriableError(\n        `Unsupported extraction model \"${req.model}\" — only cloudflare/* models are supported`\n      );\n    }\n\n    const fields: Record<string, WireField> = {};\n    for (const [name, f] of Object.entries(req.fields)) {\n      fields[name] = toWireField(f);\n    }\n\n    // Per-call step attribution only when attribution headers are configured,\n    // which is only on the platform AI proxy path (mirrors AiSdkEngine).\n    const stepHeader =\n      this.opts.headers && req.stepName\n        ? sanitizeHeaderValue(req.stepName)\n        : \"\";\n\n    // The same key for every attempt of one step in one run, so the proxy can\n    // answer a retry from the first attempt's result instead of reading (and\n    // billing) the input again.\n    const runId = this.opts.headers?.[\"x-keel-flow-run-id\"];\n    const idempotencyKey = runId && stepHeader ? `${runId}:${stepHeader}` : \"\";\n\n    let root = this.opts.baseURL;\n    while (root.endsWith(\"/\")) root = root.slice(0, -1);\n\n    const res = await fetch(`${root}/extract`, {\n      method: \"POST\",\n      headers: {\n        \"content-type\": \"application/json\",\n        authorization: `Bearer ${this.opts.proxyToken}`,\n        ...this.opts.headers,\n        ...(stepHeader ? { \"x-keel-flow-step\": stepHeader } : {}),\n        ...(idempotencyKey ? { \"idempotency-key\": idempotencyKey } : {}),\n      },\n      body: JSON.stringify({\n        model: req.model,\n        state: req.state,\n        fields,\n        ...(req.images?.length\n          ? {\n              images: req.images.map((i) => ({\n                content_type: i.contentType,\n                base64: i.base64,\n              })),\n            }\n          : {}),\n        ...(req.referenceDate ? { reference_date: req.referenceDate } : {}),\n      }),\n    });\n\n    if (!res.ok) {\n      const detail = (await res.text().catch(() => \"\")).slice(0, 300);\n      const msg = `Extraction request failed (HTTP ${res.status})${detail ? `: ${detail}` : \"\"}`;\n      // The request itself is wrong (bad field shape, unsupported model,\n      // oversized images): retrying the step won't help. Everything else may\n      // be transient.\n      if (\n        res.status === 400 ||\n        res.status === 404 ||\n        res.status === 413 ||\n        res.status === 422\n      ) {\n        throw new NonRetriableError(msg);\n      }\n      throw new Error(msg);\n    }\n\n    const body = (await res.json()) as WireResponse;\n    if (!body.answers || typeof body.answers !== \"object\") {\n      throw new Error(\"Extraction response had no answers\");\n    }\n\n    const answers: Record<string, ExtractAnswer> = {};\n    for (const [name, a] of Object.entries(body.answers)) {\n      answers[name] = fromWireAnswer(a);\n    }\n\n    return {\n      answers,\n      truncated: body.truncated === true,\n      model: body.model ?? req.model,\n      usage: {\n        inputTokens: body.usage?.input_tokens ?? 0,\n        outputTokens: body.usage?.output_tokens ?? 0,\n      },\n    };\n  }\n}\n","import { FlowConfig, ExtractStageKeys } from \"..\";\nimport type { ToolRef } from \"../tools\";\nimport {\n  BaseUiDisplayResponse,\n  ImplementationResponse,\n  UiElementApiResponses,\n  DisplayElementResponse,\n} from \".\";\n\nexport type AllOptional<T> = {\n  [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n}[keyof T] extends never\n  ? true\n  : false;\n\ntype RestartConfig = {\n  /**\n   * If auto, the flow will restart automatically with a notification instead of a completion screen.\n   * If manual, a button will be shown on the completion screen.\n   * Default is manual.\n   * */\n  mode?: \"manual\" | \"auto\";\n  buttonLabel?: string;\n};\n\n// The permissive tool-inputs map: any tool id, any inputs. The generated SDK\n// substitutes the project's `ToolInputs` interface (see node/codegen.go) so that\n// ctx.complete({ redirect }) narrows `toolId` and `inputs` per tool. It is\n// Record<string, any> rather than Record<string, unknown> because interfaces\n// (which is what codegen emits) are assignable to the former but not the latter.\nexport type AnyToolInputs = Record<string, any>;\n\n// `inputs` can be omitted when every field of the tool's input type is optional\n// (also true for `any`, `{}` and Record<string, never>), and is required otherwise.\nexport type RedirectInputs<In> =\n  AllOptional<In> extends true ? { inputs?: In } : { inputs: In };\n\n// A reference to one of the tools in T, as a generated accessor\n// (`tools.getOrder({ id })`) returns it. ToolRef is branded, so a hand-written\n// `{ toolId: \"...\" }` literal is not a valid redirect.\ntype ToolRefOf<T> = {\n  [K in keyof T & string]: ToolRef<K, T[K]>;\n}[keyof T & string];\n\n/**\n * Where to send the user once the flow completes: a console tool reference\n * from the generated `tools` accessors, on its own (rendered as the completion\n * screen's primary button, labelled with the tool's name) or wrapped with the\n * flow-specific presentation options.\n */\nexport type RedirectConfig<T> = RedirectConfigFor<ToolRefOf<T>>;\n\n// Split out so that a project with no tools (ToolRefOf<T> = never) gets `never`\n// rather than an unsatisfiable wrapper. The bare branch forbids the wrapper's\n// keys explicitly so that `{ ...ref, label }` cannot pass the union's\n// excess-property check and have its label silently dropped.\ntype RedirectConfigFor<R> = [R] extends [never]\n  ? never\n  :\n      | (R & { tool?: never; label?: never; autoRedirect?: never })\n      | {\n          /** The tool to open, e.g. `tools.getOrder({ id })`. */\n          tool: R;\n          /** Button label. Defaults to the target tool's name. */\n          label?: string;\n          /**\n           * Navigate to the tool as soon as the flow completes instead of\n           * showing the completion screen with a button. Title and description\n           * are shown as a notification; `content` and `allowRestart` are not\n           * shown.\n           */\n          autoRedirect?: boolean;\n        };\n\nexport type CompleteOptions<C extends FlowConfig, I, T = AnyToolInputs> = {\n  stage?: ExtractStageKeys<C>;\n  title?: string;\n  description?: string;\n\n  /** Automatically close the flow once complete.\n   * Title and description will be shown in a notification if provided.\n   * If set, you cannot return content as this will not be shown. */\n  autoClose?: boolean;\n\n  fullWidth?: boolean;\n\n  /** Restart the flow once complete.\n   * Title and description will be shown in a notification if provided.\n   * If set, the flow will be restarted with the inputs provided.\n   * If set, you cannot return content as this will not be shown. */\n  allowRestart?: //\n    // Quite messy types but this does the following:\n    // This can be false to disable.\n    // True if there are no inputs.\n    // Otherwise the config object.\n    // If the inputs are all optional then the inputs param is optional, otherwise required.\n    | false\n    | ([I] extends [never]\n        ? boolean | RestartConfig\n        : RestartConfig &\n            (AllOptional<I> extends true\n              ? {\n                  inputs?: I;\n                }\n              : {\n                  inputs: I;\n                }));\n  data?: any;\n} & (\n  | {\n      autoClose: true;\n      content?: never;\n      redirect?: never;\n    }\n  | {\n      autoClose?: false;\n      content?: DisplayElementResponse<any>[];\n      fullWidth?: boolean;\n      /** Send the user to another console tool once the flow completes.\n       * Shown as the primary button on the completion screen, so it cannot be\n       * combined with autoClose or allowRestart in \"auto\" mode. */\n      redirect?: RedirectConfig<T>;\n    }\n);\n\n// A distributive form of Omit: plain `Omit<A | B, K>` first merges the union\n// into a single object type before omitting `K`, which collapses a\n// discriminated union (like CompleteOptions' autoClose/content pairing) into a\n// single non-discriminated shape and silently defeats its mutual-exclusivity\n// check. Distributing the Omit over each union member first (via `T extends\n// any ? ... : never`) keeps the branches — and their discriminants — separate.\ntype DistributiveOmit<T, K extends PropertyKey> = T extends any\n  ? Omit<T, K>\n  : never;\n\n// Complete is generic in D (the shape of `data`), separate from CompleteOptions'\n// own type parameters (C for stage keys, I for restart inputs). CompleteOptions\n// declares `data?: any` because it has no data-specific parameter to narrow\n// with — but a fixed (non-generic) function type can never narrow a parameter\n// beyond what its signature declares, so if Complete's `data` field type came\n// from CompleteOptions<C, I> directly, `ctx.complete({ data: { n: 1 } })` would\n// always widen back to `any`, and callers like `ctx.flows.run` (which infer a\n// child flow's result from its `ctx.complete(...)` return) would see `any`\n// instead of `{ n: number }`. Overriding just the `data` field via Omit + a\n// per-call generic `D` lets TypeScript infer `D` from the actual argument at\n// each call site, so the literal shape survives. `D` defaults to `undefined`\n// (not `any`) so a call that omits `data` (e.g. `ctx.complete({ autoClose:\n// true })`) resolves to `data?: undefined` rather than re-introducing `any`\n// into the inferred result union.\n//\n// `T` (the tool-inputs map) narrows the *parameter* only. The return type keeps\n// the permissive default on purpose: the runtime's wide FlowContext must stay\n// assignable to the generated SDK's narrowed one under strictFunctionTypes, and\n// while parameters are contravariant (a narrow options type is assignable to the\n// wide one) return types are covariant, so a narrowed return would break it.\nexport type Complete<C extends FlowConfig, I, T = AnyToolInputs> = <\n  D = undefined,\n>(\n  options: DistributiveOmit<CompleteOptions<C, I, T>, \"data\"> & { data?: D }\n) => DistributiveOmit<CompleteOptions<C, I>, \"data\"> & {\n  data?: D;\n  __type: \"ui.complete\";\n};\n\nexport interface UiCompleteApiResponse extends Omit<\n  BaseUiDisplayResponse<\"ui.complete\">,\n  \"visible\"\n> {\n  stage?: string;\n  title?: string;\n  description?: string;\n  content: UiElementApiResponses;\n  autoClose?: boolean;\n  fullWidth?: boolean;\n  allowRestart?: {\n    inputs?: any;\n  } & RestartConfig;\n  redirect?: {\n    toolId: string;\n    // `any` (like allowRestart.inputs) so the generated OpenAPI schema accepts\n    // any object; a Record type would emit a closed schema with no properties.\n    inputs?: any;\n    label?: string;\n    autoRedirect?: boolean;\n  };\n}\n\n// Flattens a RedirectConfig (a bare tool reference, or one wrapped with label /\n// autoRedirect) into the wire shape the Console reads.\nfunction toWireRedirect(\n  redirect: RedirectConfig<AnyToolInputs> | undefined\n): UiCompleteApiResponse[\"redirect\"] {\n  if (!redirect) {\n    return undefined;\n  }\n  const wrapped = \"tool\" in redirect && redirect.tool !== undefined;\n  const tool: { toolId: string; inputs?: unknown } = wrapped\n    ? redirect.tool\n    : (redirect as { toolId: string; inputs?: unknown });\n  const wire: NonNullable<UiCompleteApiResponse[\"redirect\"]> = {\n    toolId: tool.toolId,\n  };\n  if (tool.inputs !== undefined) wire.inputs = tool.inputs;\n  if (wrapped) {\n    if (redirect.label !== undefined) wire.label = redirect.label;\n    if (redirect.autoRedirect !== undefined)\n      wire.autoRedirect = redirect.autoRedirect;\n  }\n  return wire;\n}\n\nexport async function complete<C extends FlowConfig, I>(\n  options: CompleteOptions<C, I>\n): Promise<UiCompleteApiResponse> {\n  const redirect = toWireRedirect(options.redirect);\n  if (redirect) {\n    if (options.autoClose) {\n      throw new Error(\n        \"ctx.complete: redirect cannot be combined with autoClose\"\n      );\n    }\n    if (\n      typeof options.allowRestart === \"object\" &&\n      options.allowRestart.mode === \"auto\"\n    ) {\n      throw new Error(\n        'ctx.complete: redirect cannot be combined with allowRestart mode \"auto\"'\n      );\n    }\n  }\n\n  // Turn these back into the actual response types\n  const content =\n    (options.content as unknown as ImplementationResponse<any, any>[]) || [];\n  const contentUiConfig = (await Promise.all(\n    content.map(async (c) => {\n      return (await c).uiConfig;\n    })\n  )) as UiElementApiResponses;\n\n  return {\n    __type: \"ui.complete\",\n    stage: options.stage,\n    title: options.title,\n    description: options.description,\n    content: contentUiConfig || [],\n    autoClose: options.autoClose,\n    fullWidth: options.fullWidth,\n    allowRestart:\n      typeof options.allowRestart === \"boolean\"\n        ? options.allowRestart\n          ? { inputs: undefined }\n          : undefined\n        : options.allowRestart,\n    redirect,\n  } satisfies UiCompleteApiResponse;\n}\n","// ACTION_ERROR_CODES is the closed set of error codes the Keel runtime returns from the internal\n// actions endpoint. It is the single source for both the ActionErrorCode union (compile time) and\n// any runtime membership check, so the two can never drift.\nexport const ACTION_ERROR_CODES = [\n  \"ERR_INTERNAL\",\n  \"ERR_INVALID_INPUT\",\n  \"ERR_INPUT_MALFORMED\",\n  \"ERR_AUTHENTICATION_FAILED\",\n  \"ERR_PERMISSION_DENIED\",\n  \"ERR_RECORD_NOT_FOUND\",\n  \"ERR_ACTION_NOT_FOUND\",\n  \"ERR_HTTP_METHOD_NOT_ALLOWED\",\n  \"ERR_UNKNOWN\",\n  \"ERR_REQUEST_BODY_TOO_LARGE\",\n  \"ERR_CONFLICT\",\n  \"ERR_LEDGER_GUARD\",\n] as const;\n\nexport type ActionErrorCode = (typeof ACTION_ERROR_CODES)[number];\n\n// ActionValidationErrorData is the shape of ActionError.data for ERR_INVALID_INPUT: the per-field\n// schema validation failures the runtime collected.\nexport type ActionValidationErrorData = {\n  errors: { field: string; error: string }[];\n};\n\n// ActionLedgerErrorData is the shape of ActionError.data for a ledger `record*` action that failed\n// on one entry: the index of the offending entry in the submitted batch.\nexport type ActionLedgerErrorData = { entryIndex: number };\n\n// ActionLedgerGuardKind is which guard refused a write: a @min or a @max.\nexport type ActionLedgerGuardKind = \"min\" | \"max\";\n\n// ActionLedgerBalanceGuardError is the guard a write would have left a balance outside of, judged\n// on the group's net effect at that position. `current` is the balance before the write and\n// `attempted` the write's net change to it; `position` has the keys a balance row has in a record\n// response's `balances`.\nexport type ActionLedgerBalanceGuardError = {\n  error: string;\n  guard: ActionLedgerGuardKind;\n  bound: number;\n  balance: string;\n  position: Record<string, unknown>;\n  current: number;\n  attempted: number;\n};\n\n// ActionLedgerAmountGuardError is the guard an entry's amount was outside of. `entryIndex` is the\n// entry's 0-based position in the record request - the earliest, when several failed.\nexport type ActionLedgerAmountGuardError = {\n  error: string;\n  guard: ActionLedgerGuardKind;\n  bound: number;\n  amount: string;\n  value: number;\n  entryIndex?: number;\n};\n\n// ActionLedgerRelatedRowGuardError is a change to a row a balance guard's condition reads, refused\n// because a current balance would then fail the guard. It carries no values: whoever changed the\n// row may not be allowed to read the ledger.\nexport type ActionLedgerRelatedRowGuardError = {\n  error: string;\n  guard: ActionLedgerGuardKind;\n  bound: number;\n  ledger: string;\n  balance: string;\n};\n\n// ActionLedgerGuardErrorData is the shape of ActionError.data for ERR_LEDGER_GUARD: the guard that\n// refused the write, in errors[0]. When the database said nothing more than its message, errors[0]\n// carries the message alone.\nexport type ActionLedgerGuardErrorData = {\n  errors: (\n    | ActionLedgerBalanceGuardError\n    | ActionLedgerAmountGuardError\n    | ActionLedgerRelatedRowGuardError\n    | { error: string }\n  )[];\n};\n\nexport type ActionErrorInit = {\n  action: string;\n  code: ActionErrorCode;\n  message: string;\n  status: number;\n  data?: Record<string, unknown>;\n  cause?: unknown;\n};\n\n// ActionError is thrown by ActionsAPI when a call to a schema-defined action fails. It carries the\n// runtime's own error envelope (code/message/data) plus the HTTP status and the action that was\n// called, so calling code can branch on the failure without parsing message strings.\nexport class ActionError extends Error {\n  readonly name = \"ActionError\";\n  readonly code: ActionErrorCode;\n  readonly status: number;\n  readonly action: string;\n  readonly data?: Record<string, unknown>;\n  // Declared explicitly rather than passed to super(): the package targets es2020, whose Error\n  // constructor has no options bag, so the ES2022 `cause` property is set here instead.\n  readonly cause?: unknown;\n\n  constructor(init: ActionErrorInit) {\n    super(init.message);\n    this.code = init.code;\n    this.status = init.status;\n    this.action = init.action;\n    this.data = init.data;\n    this.cause = init.cause;\n\n    // Restore the prototype chain so `instanceof ActionError` holds even when this file is\n    // consumed as downlevelled ES5 output.\n    Object.setPrototypeOf(this, ActionError.prototype);\n  }\n}\n\n// isActionError narrows an unknown caught value to an ActionError, optionally to one carrying a\n// specific code — e.g. `if (isActionError(e, \"ERR_RECORD_NOT_FOUND\"))`.\nexport function isActionError(\n  e: unknown,\n  code?: ActionErrorCode\n): e is ActionError {\n  if (!(e instanceof ActionError)) {\n    return false;\n  }\n  return code === undefined || e.code === code;\n}\n","import * as tracing from \"../tracing\";\nimport { getActionCallDepth, getActionAccessToken } from \"./invocationStore\";\nimport { ActionError, ACTION_ERROR_CODES } from \"./ActionError\";\nimport type { ActionErrorCode } from \"./ActionError\";\nimport { hydrateDbValue } from \"../types/registry\";\nimport { isPlainObject } from \"../type-utils\";\nimport { dateFormat } from \"../parsing\";\nimport { Duration } from \"../Duration\";\nimport { InlineFile, File } from \"../File\";\nimport type { FileWriteTypes } from \"../File\";\n\n// ActionInputs is the shape a function passes to an action: the action's input type, except that a\n// file field accepts anything the runtime can store - an InlineFile built in code as well as a stored\n// File - since a function has no stored File until the action has run. Applied recursively so nested\n// inputs (embedded creates, arrays) get the same treatment.\nexport type ActionInputs<T> = T extends File\n  ? FileWriteTypes\n  : T extends InlineFile | Date | Duration\n    ? T\n    : T extends Array<infer U>\n      ? ActionInputs<U>[]\n      : T extends object\n        ? { [K in keyof T]: ActionInputs<T[K]> }\n        : T;\n\n// ActionPaths maps each callable action to the URL segment of the API that exposes it (the lowercased\n// API name), which is how the public JSON API is addressed. Generated by codegen from the schema's api\n// blocks: an action no api block exposes has no entry and cannot be called.\nexport type ActionPaths = Record<string, string>;\n\nexport type ActionsAPIOptions = {\n  authToken?: string | null;\n  timezone?: string | null;\n};\n\n/**\n * ActionsAPI calls schema-defined actions over the runtime's public JSON API, as the identity the\n * current invocation runs as.\n *\n * The generated SDK exposes a single instance as `actions`, with a typed method per action. This\n * class provides no such methods itself: a Proxy turns any unknown property access into a call to\n * `execute`, so codegen only has to emit type declarations.\n *\n * Who the action runs as - the runtime applies that identity's permission rules, @where filters and\n * row-level checks exactly as it would for an API request; there is no backend bypass:\n *   1. withAuthToken(token) -> that token is sent; the runtime resolves the caller from it.\n *   2. otherwise            -> the access token of the invocation this call is made from: the token\n *      the function's caller presented, or one the runtime minted for a flow's or job's identity.\n *      An anonymous invocation (a subscriber, an unauthenticated request) calls anonymously.\n *\n * Options are immutable: each with* method returns a new instance, so an instance handed out by\n * the SDK can never be re-scoped by a caller elsewhere.\n */\nexport class ActionsAPI {\n  private readonly _paths: ActionPaths;\n  private readonly _authToken: string | null;\n  private readonly _timezone: string | null;\n\n  constructor(paths: ActionPaths = {}, opts: ActionsAPIOptions = {}) {\n    this._paths = paths;\n    this._authToken = opts.authToken ?? null;\n    this._timezone = opts.timezone ?? null;\n\n    // Return a proxy which turns any unknown property into a call to that action. This gives us\n    // the actions API we want without codegen having to emit an implementation per action - only\n    // the type declarations. Mirrors the testing-runtime's Executor.\n    return new Proxy(this, {\n      get(target, prop, receiver) {\n        const v = Reflect.get(target, prop, receiver);\n        if (v !== undefined) {\n          return v;\n        }\n        // The API must not look like a promise. Handing back a function for `then` makes\n        // `await actions` treat it as a thenable and dispatch an action called \"then\", which\n        // 404s and never settles the await. Symbols are never action names either.\n        if (prop === \"then\" || typeof prop === \"symbol\") {\n          return undefined;\n        }\n        return (inputs?: Record<string, unknown>) =>\n          target.execute(prop, inputs);\n      },\n    });\n  }\n\n  /**\n   * Returns a new ActionsAPI that authenticates with the given token instead of the invocation's own.\n   */\n  withAuthToken(token: string): ActionsAPI {\n    return new ActionsAPI(this._paths, {\n      authToken: token,\n      timezone: this._timezone,\n    });\n  }\n\n  /**\n   * Returns a new ActionsAPI that evaluates the action's relative dates in the given timezone.\n   */\n  withTimezone(timezone: string): ActionsAPI {\n    return new ActionsAPI(this._paths, {\n      authToken: this._authToken,\n      timezone,\n    });\n  }\n\n  /**\n   * Calls the named action with the given inputs, returning its result. Throws an ActionError\n   * when the runtime rejects the call or the request itself fails.\n   */\n  async execute(\n    actionName: string,\n    inputs?: Record<string, unknown>\n  ): Promise<any> {\n    const name = tracing.spanNameForServiceAPI(\"actions\", actionName);\n\n    return tracing.withSpan(name, async (span: any) => {\n      span.setAttribute(tracing.ATTRS.ACTION, actionName);\n\n      const apiPath = this._paths[actionName];\n      if (apiPath === undefined) {\n        // The generated types only offer exposed actions, so this is reached from untyped code (or a\n        // schema whose api blocks changed underneath a stale build).\n        throw new ActionError({\n          action: actionName,\n          code: \"ERR_ACTION_NOT_FOUND\",\n          message: `action ${actionName} is not exposed on any api`,\n          status: 404,\n        });\n      }\n\n      const url = `${getApiUrl()}/${apiPath}/json/${encodeURIComponent(\n        actionName\n      )}`;\n      const wireInputs = await toWireInputs(inputs);\n\n      let response;\n      try {\n        response = await fetch(url, {\n          method: \"POST\",\n          headers: this._buildHeaders(),\n          body: JSON.stringify(wireInputs ?? {}),\n        });\n      } catch (err) {\n        // The request never reached the runtime (DNS, connection reset, abort), so there is no\n        // envelope to read - surface it as internal with the original error as the cause.\n        throw new ActionError({\n          action: actionName,\n          code: \"ERR_INTERNAL\",\n          message: err instanceof Error ? err.message : String(err),\n          status: 0,\n          cause: err,\n        });\n      }\n\n      if (!response.ok) {\n        throw await toActionError(actionName, response);\n      }\n\n      return fromWireOutputs(await response.json());\n    });\n  }\n\n  private _buildHeaders(): Record<string, string> {\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n    };\n\n    // An explicit token wins; otherwise the call carries the invocation's own token, so the action\n    // runs as the same identity the function is running for. No token means an anonymous call.\n    const token = this._authToken ?? getActionAccessToken();\n    if (token !== null) {\n      headers[\"Authorization\"] = `Bearer ${token}`;\n    }\n\n    if (this._timezone !== null) {\n      headers[\"Time-Zone\"] = this._timezone;\n    }\n\n    // Always advertise where this call sits in the action chain: the runtime refuses calls beyond\n    // its maximum depth, which is what stops an action's own function recursing forever.\n    headers[\"X-Keel-Action-Depth\"] = String(getActionCallDepth() + 1);\n\n    return headers;\n  }\n}\n\n/**\n * Gets the API URL from environment variables.\n * @returns {string} The API URL\n * @throws {Error} If the API URL is not set\n */\nfunction getApiUrl(): string {\n  const apiUrl = process.env.KEEL_API_URL;\n  if (!apiUrl) {\n    throw new Error(\"KEEL_API_URL environment variable is not set\");\n  }\n  return apiUrl;\n}\n\n// toWireInputs recursively converts the SDK's rich input types into the JSON forms the actions\n// endpoint expects. Files are inlined as data URLs rather than stored (the types registry's\n// serializeOutputValue would upload them to storage, which is not what an action input needs).\nasync function toWireInputs(value: unknown): Promise<any> {\n  if (value instanceof Duration) {\n    return value.toISOString();\n  }\n\n  // File extends InlineFile, so this covers both.\n  if (value instanceof InlineFile) {\n    const contents = await value.read();\n    return `data:${value.contentType};name=${encodeURIComponent(\n      value.filename\n    )};base64,${contents.toString(\"base64\")}`;\n  }\n\n  if (value instanceof Date) {\n    return value.toISOString();\n  }\n\n  if (Array.isArray(value)) {\n    return Promise.all(value.map((item) => toWireInputs(item)));\n  }\n\n  if (isPlainObject(value)) {\n    const out: Record<string, unknown> = {};\n    for (const [key, item] of Object.entries(\n      value as Record<string, unknown>\n    )) {\n      out[key] = await toWireInputs(item);\n    }\n    return out;\n  }\n\n  return value;\n}\n\n// fromWireOutputs recursively rehydrates an action's JSON response into the SDK's rich types -\n// ISO strings become Dates and file records become File instances - matching what the same\n// action's result looks like when it is produced in-process.\nfunction fromWireOutputs(value: unknown): any {\n  if (typeof value === \"string\") {\n    return dateFormat.test(value) ? new Date(value) : value;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map((item) => fromWireOutputs(item));\n  }\n\n  if (isPlainObject(value)) {\n    const hydrated = hydrateDbValue(value as Record<string, any>);\n    if (hydrated !== undefined) {\n      return hydrated;\n    }\n    const out: Record<string, unknown> = {};\n    for (const [key, item] of Object.entries(\n      value as Record<string, unknown>\n    )) {\n      out[key] = fromWireOutputs(item);\n    }\n    return out;\n  }\n\n  return value;\n}\n\n// toActionError turns a non-2xx response into an ActionError, falling back to the raw body when\n// the runtime did not return its usual `{code, message, data}` envelope.\nasync function toActionError(\n  actionName: string,\n  response: Response\n): Promise<ActionError> {\n  const text = await response.text();\n\n  let envelope: any;\n  try {\n    envelope = JSON.parse(text);\n  } catch {\n    envelope = null;\n  }\n\n  if (!isPlainObject(envelope)) {\n    return new ActionError({\n      action: actionName,\n      code: \"ERR_INTERNAL\",\n      message: text,\n      status: response.status,\n    });\n  }\n\n  return new ActionError({\n    action: actionName,\n    code: toActionErrorCode(envelope.code, response.status),\n    message: typeof envelope.message === \"string\" ? envelope.message : text,\n    status: response.status,\n    data: fromWireErrorData(envelope.code, envelope.data),\n  });\n}\n\n// fromWireErrorData rehydrates what an error's data echoes from a record response, so that the two can\n// be compared. A ledger guard's position has the keys and values a balance row has in balances[], and\n// a response's values are rehydrated - a Date position is a Date there - so the position's are too.\n// Nothing else in an error's data is rewritten.\nfunction fromWireErrorData(\n  code: unknown,\n  data: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n  if (code !== \"ERR_LEDGER_GUARD\" || !isPlainObject(data)) {\n    return data;\n  }\n  const errors = data?.errors;\n  if (!Array.isArray(errors)) {\n    return data;\n  }\n  return {\n    ...data,\n    errors: errors.map((error: unknown) => {\n      const position = isPlainObject(error)\n        ? (error as { position?: unknown }).position\n        : undefined;\n      return isPlainObject(position)\n        ? {\n            ...(error as Record<string, unknown>),\n            position: fromWireOutputs(position),\n          }\n        : error;\n    }),\n  };\n}\n\n// toActionErrorCode maps the envelope's code onto the known set. The auth layer can reject a\n// request before the actions handler runs, returning `{message}` with no code at all - a 401 like\n// that is an authentication failure; anything else unrecognised is internal.\nfunction toActionErrorCode(code: unknown, status: number): ActionErrorCode {\n  if (\n    typeof code === \"string\" &&\n    (ACTION_ERROR_CODES as readonly string[]).includes(code)\n  ) {\n    return code as ActionErrorCode;\n  }\n  return status === 401 ? \"ERR_AUTHENTICATION_FAILED\" : \"ERR_INTERNAL\";\n}\n","import * as React from \"react\";\nimport {\n  Html,\n  Head,\n  Body,\n  Container,\n  Heading,\n  Text,\n  Button,\n  Section,\n  Row,\n  Column,\n  Img,\n} from \"@react-email/components\";\nimport { render } from \"@react-email/render\";\nimport type { EmailBrand, StructuredEmailContent } from \"./types\";\n\ninterface StockEmailProps {\n  content: StructuredEmailContent;\n  brand?: EmailBrand;\n}\n\nconst DARK_TEXT = \"#111827\";\nconst DEFAULT_BUTTON = { background: DARK_TEXT, text: \"#ffffff\" };\n\n// Minimum label contrast for a brand colour to be used on the primary button. Stricter than\n// WCAG AA (4.5:1): mid-tone brand colours just past AA read as washed out on a button.\nconst MIN_BUTTON_CONTRAST = 5;\n\n// A six-digit colour as CSS-ready \"#rrggbb\" (the leading \"#\" is optional on input), or\n// undefined when it does not parse.\nfunction normaliseHex(hex: string): string | undefined {\n  const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());\n  return m ? `#${m[1].toLowerCase()}` : undefined;\n}\n\n// WCAG relative luminance of a normalised #rrggbb colour.\nfunction luminance(hex: string): number {\n  const [r, g, b] = [1, 3, 5].map((i) => {\n    const c = parseInt(hex.slice(i, i + 2), 16) / 255;\n    return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n  });\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\nfunction contrast(a: number, b: number): number {\n  return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);\n}\n\n// buttonColors decides how a brand colour is applied to the primary button. The brand colour\n// stays as the background and the label takes whichever of white or dark text contrasts more;\n// a mid-tone where neither reaches MIN_BUTTON_CONTRAST falls back to the unbranded button.\nexport function buttonColors(primaryHex?: string): {\n  background: string;\n  text: string;\n} {\n  const hex = primaryHex ? normaliseHex(primaryHex) : undefined;\n  if (!hex) return DEFAULT_BUTTON;\n  const lum = luminance(hex);\n  const onWhite = contrast(lum, 1);\n  const onDark = contrast(lum, luminance(DARK_TEXT));\n  if (Math.max(onWhite, onDark) < MIN_BUTTON_CONTRAST) return DEFAULT_BUTTON;\n  return {\n    background: hex,\n    text: onWhite >= onDark ? \"#ffffff\" : DARK_TEXT,\n  };\n}\n\n// Plain-text body: preserve newlines as <br>.\nfunction renderBody(text: string): React.ReactNode[] {\n  return text\n    .split(\"\\n\")\n    .flatMap((line, i) => (i === 0 ? [line] : [<br key={`br-${i}`} />, line]));\n}\n\n// actionColors styles one action button. Primary buttons carry the brand; secondary ones are\n// unbranded outline buttons. Both take a 1px border so they size alike.\nfunction actionColors(\n  variant: \"primary\" | \"secondary\",\n  brand?: EmailBrand\n): React.CSSProperties {\n  if (variant === \"secondary\") {\n    return {\n      backgroundColor: \"#ffffff\",\n      color: DARK_TEXT,\n      border: \"1px solid #d1d5db\",\n    };\n  }\n  const { background, text } = buttonColors(brand?.primaryHex);\n  return {\n    backgroundColor: background,\n    color: text,\n    border: `1px solid ${background}`,\n  };\n}\n\nexport const StockEmailTemplate: React.FC<StockEmailProps> = ({\n  content,\n  brand,\n}) => (\n  <Html>\n    <Head>\n      <style>{`\n        @media only screen and (max-width: 480px) {\n          .email-detail-label,\n          .email-detail-value {\n            box-sizing: border-box !important;\n            display: block !important;\n            width: 100% !important;\n          }\n\n          .email-detail-label {\n            border-bottom: 0 !important;\n            padding: 12px 16px 2px !important;\n          }\n\n          .email-detail-value {\n            padding: 0 16px 12px !important;\n            text-align: left !important;\n          }\n\n          .email-action-button {\n            box-sizing: border-box !important;\n            display: block !important;\n            margin-right: 0 !important;\n            text-align: center !important;\n            width: 100% !important;\n          }\n        }\n      `}</style>\n    </Head>\n    <Body\n      style={{\n        backgroundColor: \"#f6f6f6\",\n        fontFamily: '-apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif',\n      }}\n    >\n      <Container\n        style={{\n          backgroundColor: \"#ffffff\",\n          margin: \"40px auto\",\n          padding: \"40px 40px 24px 40px\",\n          maxWidth: \"560px\",\n          borderRadius: \"8px\",\n        }}\n      >\n        {brand?.logoUrl ? (\n          <Img\n            src={brand.logoUrl}\n            alt={brand.name ?? \"\"}\n            height=\"32\"\n            style={{ height: \"32px\", width: \"auto\", margin: \"0 0 32px\" }}\n          />\n        ) : (\n          brand?.name && (\n            <Text\n              style={{\n                fontSize: \"16px\",\n                fontWeight: 600,\n                color: DARK_TEXT,\n                margin: \"0 0 32px\",\n              }}\n            >\n              {brand.name}\n            </Text>\n          )\n        )}\n\n        {content.title && (\n          <Heading\n            style={{\n              fontSize: \"22px\",\n              fontWeight: 600,\n              color: \"#111827\",\n              margin: \"0 0 24px\",\n              lineHeight: \"1.2\",\n            }}\n          >\n            {content.title}\n          </Heading>\n        )}\n\n        <Text\n          style={{\n            fontSize: \"14px\",\n            lineHeight: \"1.6\",\n            color: \"#374151\",\n            margin: \"0 0 24px\",\n          }}\n        >\n          {renderBody(content.body)}\n        </Text>\n\n        {(content.details ?? []).length > 0 && (\n          <Section\n            style={{\n              border: \"1px solid #e5e7eb\",\n              borderRadius: \"4px\",\n              margin: \"0 0 24px\",\n              overflow: \"hidden\",\n            }}\n          >\n            {content.details!.map((detail, i) => {\n              const borderBottom =\n                i < content.details!.length - 1 ? \"1px solid #e5e7eb\" : \"none\";\n\n              return (\n                <Row key={`${detail.label}-${i}`}>\n                  <Column\n                    className=\"email-detail-label\"\n                    style={{\n                      borderBottom,\n                      color: \"#6b7280\",\n                      fontSize: \"13px\",\n                      fontWeight: 400,\n                      lineHeight: \"1.5\",\n                      padding: \"12px 16px\",\n                      verticalAlign: \"top\",\n                      width: \"38%\",\n                    }}\n                  >\n                    {detail.label}\n                  </Column>\n                  <Column\n                    className=\"email-detail-value\"\n                    style={{\n                      borderBottom,\n                      color: \"#111827\",\n                      fontSize: \"13px\",\n                      fontWeight: 400,\n                      lineHeight: \"1.5\",\n                      padding: \"12px 16px\",\n                      textAlign: \"right\",\n                      verticalAlign: \"top\",\n                      wordBreak: \"break-word\",\n                    }}\n                  >\n                    {detail.value}\n                  </Column>\n                </Row>\n              );\n            })}\n          </Section>\n        )}\n\n        {(content.actions ?? []).length > 0 && (\n          <Section style={{ margin: \"0 0 12px\" }}>\n            {content.actions!.map((action, i) => (\n              <Button\n                key={i}\n                className=\"email-action-button\"\n                href={action.url}\n                style={{\n                  ...actionColors(\n                    action.variant ?? (i === 0 ? \"primary\" : \"secondary\"),\n                    brand\n                  ),\n                  padding: \"12px 24px\",\n                  borderRadius: \"4px\",\n                  fontSize: \"14px\",\n                  fontWeight: 400,\n                  textDecoration: \"none\",\n                  display: \"inline-block\",\n                  // Lay buttons out side by side; space between adjacent buttons.\n                  marginRight: i < content.actions!.length - 1 ? \"12px\" : \"0\",\n                  marginBottom: \"12px\",\n                }}\n              >\n                {action.label}\n              </Button>\n            ))}\n          </Section>\n        )}\n      </Container>\n    </Body>\n  </Html>\n);\n\nexport async function renderEmailHtml(\n  content: StructuredEmailContent,\n  brand?: EmailBrand\n): Promise<string> {\n  return render(<StockEmailTemplate content={content} brand={brand} />, {\n    pretty: false,\n  });\n}\n\nexport function renderEmailText(content: StructuredEmailContent): string {\n  const sections: string[] = [];\n\n  if (content.title) {\n    sections.push(content.title);\n  }\n\n  sections.push(content.body);\n\n  if ((content.details ?? []).length > 0) {\n    sections.push(\n      content\n        .details!.map(({ label, value }) => `${label}: ${value}`)\n        .join(\"\\n\")\n    );\n  }\n\n  if ((content.actions ?? []).length > 0) {\n    sections.push(\n      content.actions!.map(({ label, url }) => `${label}: ${url}`).join(\"\\n\")\n    );\n  }\n\n  return sections.join(\"\\n\\n\");\n}\n","import KSUID from \"ksuid\";\nimport { toPlainText } from \"@react-email/render\";\nimport * as tracing from \"../tracing\";\nimport { buildServiceAuthHeaders } from \"../auth/serviceToken\";\nimport { File } from \"../File\";\nimport { renderEmailHtml, renderEmailText } from \"./email-template\";\nimport { getBrand } from \"./brandStore\";\nimport type { EmailInput, EmailRecipientGroup, RecipientRef } from \"./types\";\n\nconst MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024; // 10MB per-file pre-flight cap\n\nfunction getApiUrl(): string {\n  const apiUrl = process.env.KEEL_API_URL;\n  if (!apiUrl) {\n    throw new Error(\"KEEL_API_URL environment variable is not set\");\n  }\n  return apiUrl;\n}\n\nfunction toArray<T>(v: T | T[] | undefined): T[] {\n  if (v === undefined) return [];\n  return Array.isArray(v) ? v : [v];\n}\n\n// normaliseGroup tags each recipient by the field it was supplied in. The field name is the\n// kind discriminator (it survives TypeScript's type erasure), so no runtime type inspection\n// of the value is needed.\nfunction normaliseGroup(group?: EmailRecipientGroup): RecipientRef[] {\n  if (!group) return [];\n  const refs: RecipientRef[] = [];\n  for (const email of toArray(group.emails)) {\n    refs.push({ kind: \"email\", value: email });\n  }\n  for (const user of toArray(group.users)) {\n    refs.push({\n      kind: \"user\",\n      value: typeof user === \"string\" ? user : user.id,\n    });\n  }\n  for (const identity of toArray(group.identities)) {\n    refs.push({\n      kind: \"identity\",\n      value: typeof identity === \"string\" ? identity : identity.id,\n    });\n  }\n  for (const team of toArray(group.teams)) {\n    refs.push({ kind: \"team\", value: team });\n  }\n  return refs;\n}\n\nexport interface NotifyApi {\n  email(input: EmailInput): Promise<string>;\n}\n\nasync function notifyEmail(input: EmailInput): Promise<string> {\n  return tracing.withSpan(\"notify.email\", async () => {\n    const id = KSUID.randomSync().string;\n\n    // `rendered` is the send-ready HTML; `text` is its plain-text alternative.\n    // `content` is the structured input, omitted when raw HTML was supplied.\n    let rendered: string;\n    let text: string;\n    let content: EmailInput[\"content\"] | undefined;\n    if (typeof input.content === \"string\") {\n      rendered = input.content;\n      text = toPlainText(input.content);\n      content = undefined;\n    } else {\n      rendered = await renderEmailHtml(\n        input.content,\n        input.branding === false ? undefined : getBrand()\n      );\n      text = renderEmailText(input.content);\n      content = input.content;\n    }\n\n    const attachments: (\n      | string\n      | { key: string; filename: string; contentType: string }\n    )[] = [];\n    for (const att of input.attachments ?? []) {\n      if (att.size > MAX_ATTACHMENT_BYTES) {\n        throw new Error(\n          `attachment \"${att.filename}\" is ${att.size} bytes, exceeding the 10MB limit`\n        );\n      }\n      if (att instanceof File) {\n        // stored → endpoint copies. The filename lives in the file record, not in S3\n        // object metadata, so it is sent explicitly; the endpoint prefers it over the\n        // stored metadata (which is absent for browser presigned uploads).\n        attachments.push({\n          key: att.key,\n          filename: att.filename,\n          contentType: att.contentType,\n        });\n      } else {\n        attachments.push(await att.toDataURL()); // generated → endpoint stores\n      }\n    }\n\n    const body: Record<string, unknown> = {\n      id,\n      subject: input.subject,\n      rendered,\n      text,\n      content,\n      recipients: {\n        to: normaliseGroup(input.recipients.to),\n        cc: normaliseGroup(input.recipients.cc),\n        bcc: normaliseGroup(input.recipients.bcc),\n      },\n      attachments,\n    };\n\n    // Reply-To is optional; only include it when supplied so the payload stays clean when unused.\n    if (input.replyTo) {\n      body.replyTo = normaliseGroup(input.replyTo);\n    }\n\n    const response = await fetch(`${getApiUrl()}/notifications/json/email`, {\n      method: \"POST\",\n      headers: buildServiceAuthHeaders(\"notifications\"),\n      body: JSON.stringify(body),\n    });\n\n    if (!response.ok) {\n      const errorBody = await response.json().catch(() => ({}));\n      throw new Error(\n        `Failed to send notification: ${response.status} ${\n          response.statusText\n        } - ${\n          (errorBody as { message?: string }).message ||\n          JSON.stringify(errorBody)\n        }`\n      );\n    }\n\n    // Consume the response body so the underlying socket is released back to the\n    // connection pool (undici holds it open until GC otherwise).\n    await response.body?.cancel();\n\n    return id;\n  });\n}\n\nexport function createNotifier(): NotifyApi {\n  return { email: notifyEmail };\n}\n","import { Kysely, sql } from \"kysely\";\nimport {\n  isInDatabaseTransaction,\n  useDatabase,\n  withDatabase,\n} from \"../database\";\n\n// DB access for the sync engine's state tables (keel.sync_cursor, keel.sync_control — created by\n// the runtime's internal migrations, see migrations/sync.sql). The engine owns every write to\n// sync_cursor; sync_control rows are written by operators through the integrations API and only\n// read (plus last_run_at stamping) here.\n\n/**\n * withSyncTransaction runs `cb` inside a database transaction and makes `useDatabase()` return\n * that transaction for the duration, so every write the callback makes (record store, cursor,\n * and the author's ModelAPI / syncUpsert writes) commits or rolls back together. When the\n * caller is already inside a transaction the callback simply joins it.\n *\n * Flow steps run in autocommit on a pinned connection, and `useDatabase().transaction()` on\n * that connection deadlocks (kysely's SingleConnectionProvider). Going through withDatabase is\n * the supported path; see TaskAPI for the same pattern.\n */\nexport async function withSyncTransaction<T>(cb: () => Promise<T>): Promise<T> {\n  if (isInDatabaseTransaction()) {\n    return cb();\n  }\n  return withDatabase(useDatabase(), true, () => cb());\n}\n\n// CursorPayload is the engine-owned, strategy-specific position state stored in the cursor\n// JSONB column. `walk` is the in-progress walk (null/absent when idle); `watermark` is promoted\n// only when a walk fully drains; `syncedCount` is the pageJump tail position.\nexport type CursorPayload = {\n  walk?: WalkState | null;\n  // An in-progress reconcile pass (a full walk that detects deletes by absence), independent\n  // of the incremental walk and never touching `watermark`.\n  reconcileWalk?: WalkState | null;\n  watermark?: string | number | null;\n  syncedCount?: number;\n  // Payload version. 2 means a time-based watermark is an epoch-millisecond number and may be\n  // padded by overlapMs. Absent (v1) watermarks are in whatever frame the author's\n  // getUpdatedAt returned and are passed through unpadded once, until the next drain promotes\n  // a v2 value.\n  v?: number;\n};\n\n// WalkState is the resumable position of an in-progress walk. `position` is strategy-specific\n// (an opaque page token, a page number, a window offset). `newestSeen` is the watermark\n// candidate gathered during the walk — promoted to the cursor's watermark only on a clean\n// drain, never on failure or pause. `page` counts pages across the whole walk (including prior\n// continuation runs) for step naming and observability.\nexport type WalkState = {\n  // reconcile only: the pass id stamped on every record it sees, and when it started. Records\n  // not stamped with this id (and not seen by anything else since the start) are deleted.\n  id?: string;\n  startedAt?: string;\n  position?: string | number | null;\n  newestSeen?: string | number | null;\n  page: number;\n  // items ingested into the record store across the walk (every fetched item is ingested, so\n  // this is also the vendor list position pageJump resumes from).\n  rows: number;\n  // legacy alias of rows from before the record store; kept so old cursor rows still parse.\n  fetched?: number;\n  // items whose payload was new or changed across the walk (the apply phase's workload).\n  changed?: number;\n  // sinceId: the most recent ids seen this walk, newest first, at most overlapCount + 1 long,\n  // so the promoted watermark can sit overlapCount ids behind the newest.\n  recentIds?: (string | number)[];\n};\n\nexport type SyncCursorRow = {\n  integrationName: string;\n  entity: string;\n  scope: string;\n  cursor: CursorPayload | null;\n  lastSyncedAt: Date | null;\n  lastError: string | null;\n  recordsProcessed: number;\n  // items whose payload was new or changed (the apply workload) — see records_processed above.\n  recordsChanged: number;\n  // Whole-walk totals from the most recent drained incremental walk. null until one drains;\n  // never written by a paused walk or a reconcile pass.\n  lastRunFetched: number | null;\n  lastRunChanged: number | null;\n  lastRunAt: Date | null;\n};\n\nexport type SyncControlRow = {\n  integrationName: string;\n  entity: string;\n  enabled: boolean;\n  cadenceOverride: string | null;\n  requestIntervalMs: number | null;\n  activeFromHour: number | null;\n  activeToHour: number | null;\n  maxRowsPerRun: number | null;\n  lastRunAt: Date | null;\n  // Reconcile schedule (null = never reconcile) and the last completed reconcile pass.\n  reconcileCadence: string | null;\n  lastReconcileAt: Date | null;\n};\n\nexport async function getCursor(\n  db: Kysely<any>,\n  integrationName: string,\n  entity: string,\n  scope: string\n): Promise<SyncCursorRow | null> {\n  const row = await db\n    .selectFrom(\"keel.sync_cursor\")\n    .selectAll()\n    .select(sql<string | null>`cursor::text`.as(\"cursorRaw\"))\n    .where(\"integration_name\", \"=\", integrationName)\n    .where(\"entity\", \"=\", entity)\n    .where(\"scope\", \"=\", scope)\n    .executeTakeFirst();\n\n  if (!row) {\n    return null;\n  }\n\n  return {\n    integrationName: row.integrationName,\n    entity: row.entity,\n    scope: row.scope,\n    cursor: row.cursorRaw ? JSON.parse(row.cursorRaw) : null,\n    lastSyncedAt: row.lastSyncedAt ?? null,\n    lastError: row.lastError ?? null,\n    recordsProcessed: Number(row.recordsProcessed ?? 0),\n    recordsChanged: Number(row.recordsChanged ?? 0),\n    lastRunFetched: row.lastRunFetched ?? null,\n    lastRunChanged: row.lastRunChanged ?? null,\n    lastRunAt: row.lastRunAt ?? null,\n  };\n}\n\n// upsertCursor writes the full engine-owned state of one cursor row. Called after every page\n// (so an interrupted walk resumes exactly where it stopped) and on drain/failure.\n//\n// last_error is sticky: it is only touched when `lastError` is given explicitly (a string to\n// record a problem, null to clear it). A successful page passes undefined and leaves whatever\n// the last failure wrote, so an error stays visible in the Console until a clean drain clears\n// it rather than disappearing on the next page.\nexport async function upsertCursor(\n  db: Kysely<any>,\n  row: {\n    integrationName: string;\n    entity: string;\n    scope: string;\n    cursor: CursorPayload;\n    lastError?: string | null;\n    lastSyncedAt?: Date | null;\n    recordsProcessedDelta?: number;\n    recordsChangedDelta?: number;\n    // Whole-walk totals for the most recent drained incremental walk. Omitted (or undefined)\n    // for a paused walk or a reconcile pass, which must leave the existing values alone.\n    lastRun?: { fetched: number; changed: number; at: Date };\n  }\n): Promise<void> {\n  await db\n    .insertInto(\"keel.sync_cursor\")\n    .values({\n      integration_name: row.integrationName,\n      entity: row.entity,\n      scope: row.scope,\n      cursor: JSON.stringify(row.cursor),\n      last_error: row.lastError ?? null,\n      last_synced_at: row.lastSyncedAt ?? null,\n      records_processed: row.recordsProcessedDelta ?? 0,\n      records_changed: row.recordsChangedDelta ?? 0,\n      ...(row.lastRun\n        ? {\n            last_run_fetched: row.lastRun.fetched,\n            last_run_changed: row.lastRun.changed,\n            last_run_at: row.lastRun.at,\n          }\n        : {}),\n    })\n    .onConflict((oc) =>\n      oc.columns([\"integration_name\", \"entity\", \"scope\"]).doUpdateSet({\n        cursor: JSON.stringify(row.cursor),\n        ...(row.lastError !== undefined ? { last_error: row.lastError } : {}),\n        ...(row.lastSyncedAt ? { last_synced_at: row.lastSyncedAt } : {}),\n        records_processed: sql`\"keel\".\"sync_cursor\".\"records_processed\" + ${row.recordsProcessedDelta ?? 0}`,\n        records_changed: sql`\"keel\".\"sync_cursor\".\"records_changed\" + ${row.recordsChangedDelta ?? 0}`,\n        ...(row.lastRun\n          ? {\n              last_run_fetched: row.lastRun.fetched,\n              last_run_changed: row.lastRun.changed,\n              last_run_at: row.lastRun.at,\n            }\n          : {}),\n      })\n    )\n    .execute();\n}\n\n// setCursorError records (or, with null, clears) the visible error on a cursor row without\n// touching its position state. Used best-effort from a failing step before it rethrows, so\n// the failure is visible in the Console even though the step's own work was rolled back, and\n// after a clean drain to clear it.\nexport async function setCursorError(\n  db: Kysely<any>,\n  key: { integrationName: string; entity: string; scope: string },\n  error: string | null\n): Promise<void> {\n  await db\n    .insertInto(\"keel.sync_cursor\")\n    .values({\n      integration_name: key.integrationName,\n      entity: key.entity,\n      scope: key.scope,\n      cursor: JSON.stringify({}),\n      last_error: error,\n    })\n    .onConflict((oc) =>\n      oc\n        .columns([\"integration_name\", \"entity\", \"scope\"])\n        .doUpdateSet({ last_error: error })\n    )\n    .execute();\n}\n\n// getRateLimitObservation reads the vendor budget the proxy last recorded on this integration's\n// connection row (keel.integration_connection, see migrations/integrations.sql): the value of the\n// header the manifest named, and when it was seen. Null when there is no connection row or the\n// proxy has not seen the header yet — the engine then walks unthrottled, exactly as it does for\n// an integration that declares no rate_limit block.\nexport async function getRateLimitObservation(\n  db: Kysely<any>,\n  integrationName: string\n): Promise<{ remaining: number; observedAt: Date } | null> {\n  const row: any = await db\n    .selectFrom(\"keel.integration_connection\")\n    .select([\"rate_limit_remaining\", \"rate_limit_observed_at\"])\n    .where(\"integration_name\", \"=\", integrationName)\n    .executeTakeFirst();\n\n  if (\n    !row ||\n    row.rateLimitRemaining == null ||\n    row.rateLimitObservedAt == null\n  ) {\n    return null;\n  }\n\n  return {\n    remaining: Number(row.rateLimitRemaining),\n    observedAt: new Date(row.rateLimitObservedAt),\n  };\n}\n\nexport async function listControls(\n  db: Kysely<any>,\n  integrationName: string\n): Promise<SyncControlRow[]> {\n  const rows = await db\n    .selectFrom(\"keel.sync_control\")\n    .selectAll()\n    .where(\"integration_name\", \"=\", integrationName)\n    .execute();\n\n  return rows.map((row: any) => ({\n    integrationName: row.integrationName,\n    entity: row.entity,\n    enabled: Boolean(row.enabled),\n    cadenceOverride: row.cadenceOverride ?? null,\n    requestIntervalMs: row.requestIntervalMs ?? null,\n    activeFromHour: row.activeFromHour ?? null,\n    activeToHour: row.activeToHour ?? null,\n    maxRowsPerRun: row.maxRowsPerRun ?? null,\n    lastRunAt: row.lastRunAt ?? null,\n    reconcileCadence: row.reconcileCadence ?? null,\n    lastReconcileAt: row.lastReconcileAt ?? null,\n  }));\n}\n\n// markEntityReconciled stamps last_reconcile_at once a reconcile pass fully drained.\nexport async function markEntityReconciled(\n  db: Kysely<any>,\n  integrationName: string,\n  entity: string,\n  at: Date\n): Promise<void> {\n  await db\n    .insertInto(\"keel.sync_control\")\n    .values({\n      integration_name: integrationName,\n      entity,\n      enabled: false,\n      last_reconcile_at: at,\n    })\n    .onConflict((oc) =>\n      oc.columns([\"integration_name\", \"entity\"]).doUpdateSet({\n        last_reconcile_at: at,\n      })\n    )\n    .execute();\n}\n\n// markEntityRan stamps last_run_at for the entity's cadence accounting. Called only when the\n// entity's walk fully drained — a paused or failed walk stays \"due\", so the next tick resumes\n// it instead of waiting out the cadence.\nexport async function markEntityRan(\n  db: Kysely<any>,\n  integrationName: string,\n  entity: string,\n  at: Date\n): Promise<void> {\n  await db\n    .insertInto(\"keel.sync_control\")\n    .values({\n      integration_name: integrationName,\n      entity,\n      enabled: false,\n      last_run_at: at,\n    })\n    .onConflict((oc) =>\n      oc.columns([\"integration_name\", \"entity\"]).doUpdateSet({\n        last_run_at: at,\n      })\n    )\n    .execute();\n}\n","import { Kysely } from \"kysely\";\nimport KSUID from \"ksuid\";\nimport { useDatabase } from \"../database\";\nimport {\n  CursorPayload,\n  WalkState,\n  getCursor,\n  getRateLimitObservation,\n  upsertCursor,\n  setCursorError,\n  withSyncTransaction,\n} from \"./store\";\nimport {\n  countLive,\n  ingestRecords,\n  IngestItem,\n  tombstone,\n  tombstoneUnseen,\n} from \"./records\";\nimport type {\n  SyncDefinition,\n  SyncStrategy,\n  ListArgs,\n  IntegrationServer,\n  SyncEngineHooks,\n  RateLimitConfig,\n} from \"./index\";\nimport * as telemetry from \"./telemetry\";\n\n// The walk: one resumable, watermark-disciplined pass over one entity in one scope. This file\n// owns the correctness rules that are easy to botch when hand-rolled:\n//\n//   - every fetched page is written to the record store (keel.sync_record) and the walk's\n//     position advanced in ONE transaction, so a crash, timeout or pause resumes exactly where\n//     it stopped — no page skipped, no record lost. Projection into the project's models is a\n//     separate phase (apply.ts) that works off the store, so a broken projector can never make\n//     the walk drop a record;\n//   - the watermark candidate (`newestSeen`) is gathered from the VENDOR's own timestamps/ids\n//     during the walk and promoted to the cursor's watermark ONLY on a clean drain — a failed\n//     or paused walk never advances it, so nothing is silently skipped;\n//   - every incremental request is padded back from the watermark (overlapMs, or overlapCount\n//     ids for sinceId). Vendors index updates late (HubSpot's search index lags writes by\n//     seconds to minutes) and several records share one timestamp at any boundary, so an\n//     exact \"since the watermark\" request misses records. Re-fetching the pad is free: the\n//     record store's hash makes an unchanged record a no-op.\n\n// Default overlap pads. dateWindow keeps its historical hour; the others re-scan five minutes.\nexport const DEFAULT_OVERLAP_MS = 5 * 60 * 1000;\nexport const DEFAULT_DATE_WINDOW_OVERLAP_MS = 60 * 60 * 1000;\nexport const CURSOR_PAYLOAD_VERSION = 2;\n\n// A reconcile pass that fetched fewer than this fraction of the live records is treated as a\n// broken or partial vendor response rather than a mass deletion: nothing is tombstoned and the\n// problem is recorded on the cursor. Env-overridable for vendors whose data genuinely churns.\nexport function reconcileMinRatio(): number {\n  const fromEnv = parseFloat(process.env.KEEL_SYNC_RECONCILE_MIN_RATIO ?? \"\");\n  return Number.isFinite(fromEnv) && fromEnv >= 0 && fromEnv <= 1\n    ? fromEnv\n    : 0.5;\n}\n\nexport type WalkOutcome = {\n  status: \"drained\" | \"paused\";\n  pages: number;\n  // items ingested this run\n  rows: number;\n  // items whose payload was new or changed this run\n  changed: number;\n  // reconcile only: records soft-deleted this run because the vendor no longer returns them\n  tombstoned: number;\n  // A problem the walk recorded on the cursor without failing (the reconcile shrink guard);\n  // the tick keeps it visible instead of clearing the error after a clean apply.\n  warning: string | null;\n  // The walk paused because the vendor's observed rate-limit budget is below the manifest's\n  // reserve. The tick must NOT continue into a fresh run for this: the item waits for the next\n  // tick, by which time the vendor's budget may have recovered.\n  budgetLow: boolean;\n};\n\n// How long an observation of the vendor's remaining budget stays meaningful: the window the\n// budget is issued over, after which the vendor has reset it.\nconst RATE_LIMIT_WINDOW_MS: Record<RateLimitConfig[\"window\"], number> = {\n  daily: 86_400_000,\n  hourly: 3_600_000,\n  minute: 60_000,\n};\n\nexport type WalkBudget = {\n  // Pages this run may fetch for this work item before pausing (the caller continues the flow).\n  pages: number;\n  // Optional row cap from the control plane (max_rows_per_run).\n  rows: number | null;\n};\n\nexport async function walkEntity(opts: {\n  db: Kysely<any>;\n  integrationName: string;\n  entity: string;\n  scope: string;\n  strategy: SyncStrategy;\n  definition: SyncDefinition<any>;\n  server: IntegrationServer;\n  budget: WalkBudget;\n  step: <T>(\n    name: string,\n    fn: () => Promise<T>\n  ) => Promise<T | null | undefined>;\n  overlapMs?: number;\n  overlapCount?: number;\n  runId?: string | null;\n  // \"reconcile\": a full walk (or the definition's reconcile feed) that detects deletes.\n  mode?: \"incremental\" | \"reconcile\";\n  hooks?: SyncEngineHooks;\n  // The manifest's vendor rate-limit budget. Absent for an integration that declares none, in\n  // which case the walk never reads the connection row.\n  rateLimit?: RateLimitConfig;\n}): Promise<WalkOutcome> {\n  const {\n    db,\n    integrationName,\n    entity,\n    scope,\n    strategy,\n    definition,\n    server,\n    budget,\n    step,\n  } = opts;\n  const pageSize = definition.pageSize ?? 100;\n  const reconcile = opts.mode === \"reconcile\";\n  // A reconcile can use the vendor's own deleted-items feed instead of a full re-walk.\n  const usesFeed = reconcile && typeof definition.reconcile === \"function\";\n\n  const itemLabel = `${entity}${scope ? `/${scope}` : \"\"}${reconcile ? \" (reconcile)\" : \"\"}`;\n\n  // A flow run replays its body across many invocations (one executed step per chunk), so this\n  // walk MUST be deterministic under replay: every piece of mutable state it branches on has to\n  // come from a cached step result, never from a live read. The anchor step captures the cursor\n  // and walk position as they were when THIS RUN first reached this item — on replay the anchor\n  // and every completed page step return their cached values, so the loop reconstructs the same\n  // sequence of decisions even though the underlying DB rows have since moved on (e.g. the walk\n  // drained and its state was cleared). Budgets are measured against the anchored position; a\n  // continuation's fresh run re-anchors from the durable cursor automatically.\n  const anchor = await step(`${itemLabel}: begin`, async () => {\n    const existing = await getCursor(db, integrationName, entity, scope);\n    const cursor: CursorPayload = existing?.cursor ?? {};\n    const fresh: WalkState = {\n      page: 0,\n      rows: 0,\n      changed: 0,\n      position: null,\n      newestSeen: null,\n    };\n    // A reconcile pass has its own walk state with a pass id stamped on every record it sees.\n    const walk: WalkState = reconcile\n      ? (cursor.reconcileWalk ?? {\n          ...fresh,\n          id: KSUID.randomSync().string,\n          startedAt: new Date().toISOString(),\n        })\n      : (cursor.walk ?? fresh);\n    return { cursor, walk };\n  });\n  if (!anchor) {\n    return {\n      status: \"paused\",\n      pages: 0,\n      rows: 0,\n      changed: 0,\n      tombstoned: 0,\n      warning: null,\n      budgetLow: false,\n    };\n  }\n\n  const cursor = anchor.cursor;\n  let walk: WalkState = anchor.walk;\n  const startPage = anchor.walk.page;\n  const startRows = anchor.walk.rows;\n  const startChanged = anchor.walk.changed ?? 0;\n\n  if (\n    !reconcile &&\n    cursor.watermark != null &&\n    cursor.v !== CURSOR_PAYLOAD_VERSION &&\n    isTimeBased(strategy) &&\n    walk.page === 0\n  ) {\n    // A watermark promoted before pads existed is in the author's own frame (seconds, ISO\n    // string, ms...), so it cannot safely be moved back by a millisecond pad. It is passed\n    // through unpadded for this one walk; the drain promotes a v2 millisecond watermark.\n    console.warn(\n      `sync ${itemLabel}: watermark predates overlap pads and is used unpadded for this walk`\n    );\n  }\n\n  let drained = false;\n  let tombstoned = 0;\n  let warning: string | null = null;\n  let budgetLow = false;\n\n  const unit: telemetry.SyncUnit = {\n    integrationName,\n    entity,\n    scope,\n    strategy,\n    mode: reconcile ? \"reconcile\" : \"incremental\",\n  };\n\n  while (walk.page - startPage < budget.pages) {\n    if (budget.rows !== null && walk.rows - startRows >= budget.rows) {\n      break;\n    }\n\n    const result = await step(`${itemLabel}: page ${walk.page + 1}`, () =>\n      recordingFailure(db, { integrationName, entity, scope }, async () => {\n        // The vendor budget is read INSIDE the step body, like every other piece of mutable\n        // state this loop branches on: the decision is then cached with the step and a replay\n        // reconstructs it instead of re-reading a row that has since moved on. An integration\n        // with no rate_limit block never issues this query.\n        if (opts.rateLimit) {\n          const reserve = opts.rateLimit.reserve;\n          const observation = await getRateLimitObservation(\n            db,\n            integrationName\n          );\n          // An out-of-contract window (e.g. a manifest value the engine predates) must not\n          // silently disable the pause: default to the daily window, which matches\n          // handler.go's buildRateLimit default for the same case.\n          const windowMs =\n            RATE_LIMIT_WINDOW_MS[opts.rateLimit.window] ??\n            RATE_LIMIT_WINDOW_MS.daily;\n          // An observation older than the budget's own window says nothing: the vendor has\n          // reset the budget since, so the walk proceeds and the next proxied response\n          // records a current value.\n          const fresh =\n            observation != null &&\n            Date.now() - observation.observedAt.getTime() < windowMs;\n          if (observation != null && fresh && observation.remaining < reserve) {\n            // Pause before the vendor call, leaving the reserve for operator flows and\n            // webhooks. The cursor position is untouched, so the next tick resumes exactly\n            // here once the vendor's budget has recovered.\n            const note = `rate budget reserved: ${observation.remaining} remaining (reserve ${reserve})`;\n            await setCursorError(db, { integrationName, entity, scope }, note);\n            telemetry.rateBudgetLow(unit, {\n              remaining: observation.remaining,\n              reserve,\n              page: walk.page + 1,\n            });\n            return {\n              ingested: 0,\n              changed: 0,\n              tombstoned: 0,\n              warning: note,\n              drained: false,\n              budgetLow: true,\n              walk,\n            };\n          }\n        }\n\n        const args = buildListArgs(\n          strategy,\n          cursor,\n          walk,\n          scope,\n          pageSize,\n          server,\n          opts.overlapMs,\n          opts.overlapCount,\n          reconcile\n        );\n\n        // A reconcile feed yields deleted keys rather than records; otherwise list a page.\n        let deletedKeys: string[] = [];\n        let page: {\n          items: any[];\n          nextPosition?: string | number | null;\n          hasMore?: boolean;\n        };\n        if (usesFeed) {\n          const feed = await definition.reconcile!({\n            scope,\n            pageSize,\n            server,\n            position: walk.position ?? null,\n          });\n          deletedKeys = feed.deletedKeys ?? [];\n          page = {\n            items: [],\n            nextPosition: feed.nextPosition ?? null,\n            hasMore: feed.hasMore,\n          };\n        } else {\n          page = await definition.list(args);\n        }\n\n        // updatedSortStop: the vendor lists newest-updated first, so the first item strictly\n        // older than the padded watermark means everything after it is already synced. Items at\n        // or inside the pad are re-ingested (free when unchanged) — equal timestamps at the\n        // boundary were the classic way to lose a record.\n        let items = page.items;\n        let stopBelow = false;\n        const stopAt = args.watermark;\n        if (\n          !reconcile &&\n          strategy === \"updatedSortStop\" &&\n          stopAt != null &&\n          definition.getUpdatedAt\n        ) {\n          const kept: any[] = [];\n          for (const item of page.items) {\n            const updatedAt = toMillis(definition.getUpdatedAt(item));\n            if (updatedAt != null && updatedAt < (stopAt as number)) {\n              stopBelow = true;\n              break;\n            }\n            kept.push(item);\n          }\n          items = kept;\n        }\n\n        const toIngest: IngestItem[] = items.map((item) => ({\n          externalId: definition.key(item),\n          payload: item,\n          sourceUpdatedMs: definition.getUpdatedAt\n            ? toMillis(definition.getUpdatedAt(item))\n            : null,\n        }));\n\n        // Advance the walk position and gather the watermark candidate.\n        const advanced = advanceWalk(\n          // The deleted-items feed pages like a cursor strategy regardless of the entity's own.\n          usesFeed ? \"cursor\" : strategy,\n          // A reconciling pageJump starts from page one, not the synced tail.\n          reconcile ? { ...cursor, syncedCount: 0 } : cursor,\n          walk,\n          page,\n          definition,\n          pageSize,\n          toIngest.length,\n          opts.overlapCount ?? 0\n        );\n        const isDrained = stopBelow || advanced.drained;\n\n        // Record store and cursor commit together: either this page is durably ingested with\n        // its advanced position, or neither happened and the step is retried.\n        const ingested = await withSyncTransaction(async () => {\n          const trx = useDatabase();\n          const recordScope = { integrationName, entity, scope };\n          const result = await ingestRecords(trx, recordScope, toIngest, {\n            source: reconcile ? \"reconcile\" : \"sync\",\n            reconcileId: reconcile ? walk.id : null,\n            runId: opts.runId ?? null,\n          });\n          advanced.walk.changed = (walk.changed ?? 0) + result.changed;\n\n          let pageTombstoned = 0;\n          let lastError: string | undefined;\n          let live = 0;\n          if (usesFeed) {\n            pageTombstoned = await tombstone(trx, recordScope, deletedKeys);\n          } else if (reconcile && isDrained) {\n            // Delete by absence: every live record this pass did not stamp (and nothing else\n            // has seen since it started) is gone at the vendor — unless the pass looks\n            // truncated, in which case tombstoning nothing is the safe failure.\n            live = await countLive(trx, recordScope);\n            const fetched = advanced.walk.rows;\n            const minRatio = reconcileMinRatio();\n            if (live > 0 && fetched < live * minRatio) {\n              lastError = `reconcile fetched ${fetched} records but ${live} are live (below the ${Math.round(minRatio * 100)}% guard); no records were tombstoned`;\n            } else {\n              pageTombstoned = await tombstoneUnseen(\n                trx,\n                recordScope,\n                walk.id!,\n                walk.startedAt ? new Date(walk.startedAt) : undefined\n              );\n            }\n          }\n\n          // A reconcile never touches the incremental watermark; it only carries its own walk.\n          const nextCursor: CursorPayload = reconcile\n            ? { ...cursor, reconcileWalk: isDrained ? null : advanced.walk }\n            : isDrained\n              ? promote(strategy, cursor, advanced.walk, opts.overlapCount ?? 0)\n              : { ...cursor, walk: advanced.walk };\n\n          await opts.hooks?.beforeCursorWrite?.({\n            entity,\n            scope,\n            page: advanced.walk.page,\n          });\n\n          // last_error is deliberately left alone here (sticky) unless the reconcile guard\n          // tripped: the tick clears it after a clean drain and apply, and a failing step\n          // records it.\n          await upsertCursor(trx, {\n            integrationName,\n            entity,\n            scope,\n            cursor: nextCursor,\n            lastError,\n            lastSyncedAt: isDrained && !reconcile ? new Date() : null,\n            recordsProcessedDelta: result.fetched,\n            recordsChangedDelta: result.changed,\n            ...(isDrained && !reconcile\n              ? {\n                  lastRun: {\n                    fetched: advanced.walk.rows,\n                    changed: advanced.walk.changed ?? 0,\n                    at: new Date(),\n                  },\n                }\n              : {}),\n          });\n          return {\n            ...result,\n            tombstoned: pageTombstoned,\n            warning: lastError ?? null,\n            live,\n          };\n        });\n\n        telemetry.pageIngested(unit, {\n          page: advanced.walk.page,\n          fetched: ingested.fetched,\n          changed: ingested.changed,\n          tombstoned: ingested.tombstoned,\n          drained: isDrained,\n          reconcileId: reconcile ? walk.id : null,\n        });\n        if (reconcile && isDrained && !usesFeed) {\n          telemetry.reconcileDrained(unit, {\n            reconcileId: walk.id!,\n            fetched: advanced.walk.rows,\n            live: ingested.live,\n            tombstoned: ingested.tombstoned,\n            guardTripped: ingested.warning != null,\n          });\n        }\n\n        return {\n          ingested: ingested.fetched,\n          changed: ingested.changed,\n          tombstoned: ingested.tombstoned,\n          warning: ingested.warning,\n          drained: isDrained,\n          budgetLow: false,\n          walk: advanced.walk,\n        };\n      })\n    );\n\n    if (!result) {\n      // Step machinery declined to run (e.g. replay edge) — pause; the next run resumes.\n      break;\n    }\n\n    walk = result.walk;\n    tombstoned += result.tombstoned;\n    warning = result.warning ?? warning;\n\n    if (result.budgetLow) {\n      // Nothing was fetched and the position did not move: wait for the next tick.\n      budgetLow = true;\n      break;\n    }\n\n    if (result.drained) {\n      drained = true;\n      break;\n    }\n  }\n\n  return {\n    status: drained ? \"drained\" : \"paused\",\n    pages: walk.page - startPage,\n    rows: walk.rows - startRows,\n    changed: (walk.changed ?? 0) - startChanged,\n    tombstoned,\n    warning,\n    budgetLow,\n  };\n}\n\n// recordingFailure runs a step body and, if it throws, writes the error onto the cursor row\n// (best-effort, in autocommit, after the body's own transaction has rolled back) before\n// rethrowing so the step machinery still sees the failure.\nexport async function recordingFailure<T>(\n  db: Kysely<any>,\n  key: { integrationName: string; entity: string; scope: string },\n  body: () => Promise<T>\n): Promise<T> {\n  try {\n    return await body();\n  } catch (e) {\n    const message = e instanceof Error ? e.message : String(e);\n    try {\n      await setCursorError(db, key, message);\n    } catch {\n      // The original failure is the one worth surfacing.\n    }\n    throw e;\n  }\n}\n\n// buildListArgs derives the author-facing request arguments for the next page from the\n// strategy, promoted (and padded) watermark, and in-progress walk position.\nfunction buildListArgs(\n  strategy: SyncStrategy,\n  cursor: CursorPayload,\n  walk: WalkState,\n  scope: string,\n  pageSize: number,\n  server: IntegrationServer,\n  overlapMs?: number,\n  overlapCount?: number,\n  reconcile = false\n): ListArgs {\n  const args: ListArgs = { scope, pageSize, server };\n  if (reconcile) {\n    // A full pass over the vendor's current record set: page or token position only, no\n    // watermark or window, so the vendor returns everything it currently has.\n    args.mode = \"reconcile\";\n    switch (strategy) {\n      case \"page\":\n      case \"updatedSortStop\":\n      case \"pageJump\":\n        args.page = typeof walk.position === \"number\" ? walk.position : 1;\n        break;\n      case \"dateWindow\":\n        args.window = { from: null };\n        args.position = walk.position ?? null;\n        break;\n      default:\n        args.position = walk.position ?? null;\n        args.watermark = null;\n    }\n    return args;\n  }\n  const overlap =\n    overlapMs ??\n    (strategy === \"dateWindow\"\n      ? DEFAULT_DATE_WINDOW_OVERLAP_MS\n      : DEFAULT_OVERLAP_MS);\n\n  switch (strategy) {\n    case \"cursor\":\n      args.position = walk.position ?? null;\n      args.watermark = paddedWatermark(cursor, overlap);\n      args.overlap = overlap;\n      break;\n    case \"page\":\n      args.page = typeof walk.position === \"number\" ? walk.position : 1;\n      break;\n    case \"sinceId\":\n      // The whole walk filters from the promoted watermark id (already overlapCount ids behind\n      // the newest seen); position is the page token the vendor hands back (if any).\n      args.watermark = cursor.watermark ?? null;\n      args.position = walk.position ?? null;\n      if (overlapCount) {\n        args.overlap = overlapCount;\n      }\n      break;\n    case \"updatedSortStop\":\n      args.page = typeof walk.position === \"number\" ? walk.position : 1;\n      // Exposed so the author can filter server-side too; the engine's stop rule uses it.\n      args.watermark = paddedWatermark(cursor, overlap);\n      args.overlap = overlap;\n      break;\n    case \"pageJump\":\n      // Jump straight to the tail: everything before floor(synced / pageSize) + 1 is already\n      // synced (stable id-ASC, append-mostly source).\n      args.page =\n        typeof walk.position === \"number\"\n          ? walk.position\n          : Math.floor((cursor.syncedCount ?? 0) / pageSize) + 1;\n      break;\n    case \"dateWindow\": {\n      // Window from (watermark − overlap) onwards. The upper bound is deliberately open: the\n      // watermark is promoted from the VENDOR's timestamps on drain, so a frozen local-clock\n      // upper bound (which drops rows when the vendor's clock runs ahead) is never needed.\n      const from = paddedWatermark(cursor, overlap);\n      args.window = {\n        from:\n          typeof from === \"number\"\n            ? new Date(from).toISOString()\n            : from == null\n              ? null\n              : String(from),\n      };\n      args.overlap = overlap;\n      args.position = walk.position ?? null;\n      break;\n    }\n  }\n\n  return args;\n}\n\n// paddedWatermark moves a v2 (millisecond) watermark back by the overlap. A v1 watermark is\n// returned as stored: its unit is unknown, so subtracting milliseconds from it would be wrong\n// (a seconds-based value would jump back decades, an ISO string cannot be subtracted at all).\nfunction paddedWatermark(\n  cursor: CursorPayload,\n  overlap: number\n): string | number | null {\n  if (cursor.watermark == null) {\n    return null;\n  }\n  if (\n    cursor.v === CURSOR_PAYLOAD_VERSION &&\n    typeof cursor.watermark === \"number\"\n  ) {\n    return Math.max(0, cursor.watermark - overlap);\n  }\n  if (cursor.v !== CURSOR_PAYLOAD_VERSION) {\n    // Pre-pad watermark: try to interpret an ISO string so the stop rule still works; a bare\n    // number is passed through as is.\n    if (typeof cursor.watermark === \"string\") {\n      const t = Date.parse(cursor.watermark);\n      return Number.isNaN(t) ? cursor.watermark : t;\n    }\n  }\n  return cursor.watermark;\n}\n\nfunction isTimeBased(strategy: SyncStrategy): boolean {\n  return (\n    strategy === \"cursor\" ||\n    strategy === \"updatedSortStop\" ||\n    strategy === \"dateWindow\"\n  );\n}\n\nfunction advanceWalk(\n  strategy: SyncStrategy,\n  cursor: CursorPayload,\n  walk: WalkState,\n  page: {\n    items: any[];\n    nextPosition?: string | number | null;\n    hasMore?: boolean;\n  },\n  definition: SyncDefinition<any>,\n  pageSize: number,\n  ingested: number,\n  overlapCount: number\n): { walk: WalkState; drained: boolean } {\n  const next: WalkState = {\n    ...walk,\n    page: walk.page + 1,\n    rows: walk.rows + ingested,\n    fetched: (walk.fetched ?? walk.rows) + page.items.length,\n    newestSeen: gatherNewestSeen(\n      strategy,\n      walk.newestSeen ?? null,\n      page.items,\n      definition\n    ),\n  };\n  if (strategy === \"sinceId\" && overlapCount > 0 && definition.getId) {\n    next.recentIds = gatherRecentIds(\n      walk.recentIds ?? [],\n      page.items,\n      definition,\n      overlapCount + 1\n    );\n  }\n\n  const shortPage = page.items.length < pageSize;\n  const explicitEnd =\n    page.hasMore === false ||\n    (page.hasMore === undefined && page.nextPosition == null);\n\n  switch (strategy) {\n    case \"cursor\":\n    case \"sinceId\":\n    case \"dateWindow\":\n      next.position = page.nextPosition ?? null;\n      return {\n        walk: next,\n        drained: page.hasMore === false || page.nextPosition == null,\n      };\n    case \"page\":\n    case \"updatedSortStop\":\n      next.position =\n        (typeof walk.position === \"number\" ? walk.position : 1) + 1;\n      return { walk: next, drained: shortPage || page.hasMore === false };\n    case \"pageJump\": {\n      const current =\n        typeof walk.position === \"number\"\n          ? walk.position\n          : Math.floor((cursor.syncedCount ?? 0) / pageSize) + 1;\n      next.position = current + 1;\n      return { walk: next, drained: shortPage || explicitEnd };\n    }\n  }\n}\n\n// gatherNewestSeen tracks the walk's watermark candidate in the vendor's own frame: the max\n// updatedAt (or id, for sinceId) observed. Promoted only on drain.\nfunction gatherNewestSeen(\n  strategy: SyncStrategy,\n  current: string | number | null,\n  items: any[],\n  definition: SyncDefinition<any>\n): string | number | null {\n  let newest = current;\n  for (const item of items) {\n    let candidate: string | number | null = null;\n    if (strategy === \"sinceId\") {\n      candidate = definition.getId ? comparable(definition.getId(item)) : null;\n    } else if (definition.getUpdatedAt) {\n      // Time-based watermarks are stored as epoch milliseconds (v2) so they can be padded;\n      // an unparseable value is kept as returned and never padded.\n      const raw = definition.getUpdatedAt(item);\n      candidate = toMillis(raw) ?? comparable(raw);\n    }\n    if (candidate != null && (newest == null || candidate > newest)) {\n      newest = candidate;\n    }\n  }\n  return newest;\n}\n\n// gatherRecentIds keeps the `keep` largest ids seen so far, newest first.\nfunction gatherRecentIds(\n  current: (string | number)[],\n  items: any[],\n  definition: SyncDefinition<any>,\n  keep: number\n): (string | number)[] {\n  const all = [...current];\n  for (const item of items) {\n    const id = definition.getId ? comparable(definition.getId(item)) : null;\n    if (id != null && !all.includes(id)) {\n      all.push(id);\n    }\n  }\n  all.sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));\n  return all.slice(0, keep);\n}\n\nfunction promote(\n  strategy: SyncStrategy,\n  cursor: CursorPayload,\n  walk: WalkState,\n  overlapCount: number\n): CursorPayload {\n  const promoted: CursorPayload = { walk: null, v: CURSOR_PAYLOAD_VERSION };\n\n  switch (strategy) {\n    case \"page\":\n      // Full-walk strategies carry no watermark.\n      break;\n    case \"pageJump\":\n      promoted.syncedCount =\n        (cursor.syncedCount ?? 0) + (walk.fetched ?? walk.rows);\n      break;\n    case \"sinceId\": {\n      // Promote to the overlapCount-th most recent id so the next walk re-fetches the newest\n      // few (ids are not always issued in commit order).\n      const ring = walk.recentIds ?? [];\n      const behind =\n        overlapCount > 0 && ring.length > 0\n          ? ring[Math.min(overlapCount, ring.length - 1)]\n          : null;\n      promoted.watermark =\n        behind ?? walk.newestSeen ?? cursor.watermark ?? null;\n      break;\n    }\n    default: {\n      // Keep the previous watermark when the walk saw nothing newer (e.g. an empty\n      // incremental window) — never regress it. A carried-over v1 watermark is normalised to\n      // milliseconds when it parses, else kept as is (and stays unpadded).\n      const carried =\n        cursor.watermark == null\n          ? null\n          : cursor.v === CURSOR_PAYLOAD_VERSION\n            ? cursor.watermark\n            : (toMillis(cursor.watermark as string | number) ??\n              cursor.watermark);\n      const candidate = walk.newestSeen ?? null;\n      promoted.watermark =\n        candidate != null && (carried == null || candidate > carried)\n          ? candidate\n          : carried;\n    }\n  }\n\n  return promoted;\n}\n\n// toMillis reduces a vendor timestamp to epoch millis for the record store's version guard, or\n// null when it is absent or unparseable (the guard is then skipped for that record).\nfunction toMillis(v: Date | string | number | null | undefined): number | null {\n  if (v == null) {\n    return null;\n  }\n  if (v instanceof Date) {\n    const t = v.getTime();\n    return Number.isNaN(t) ? null : t;\n  }\n  if (typeof v === \"number\") {\n    return Number.isFinite(v) ? v : null;\n  }\n  const t = Date.parse(v);\n  return Number.isNaN(t) ? null : t;\n}\n\n// comparable normalises Dates to epoch millis so watermark comparisons are total.\nfunction comparable(\n  v: Date | string | number | null | undefined\n): string | number | null {\n  if (v == null) {\n    return null;\n  }\n  if (v instanceof Date) {\n    return v.getTime();\n  }\n  return v;\n}\n","import { Kysely, sql } from \"kysely\";\nimport { createHash } from \"node:crypto\";\n\n// The write-ahead record store (keel.sync_record, see migrations/sync.sql). Every page the engine\n// fetches is written here first, in the same transaction as the cursor advance, and only then\n// projected into the project's models by the author's upsert/remove. That ordering is what makes\n// the engine safe by construction: a projector failure leaves a `failed` row with its error, a\n// crash between fetch and cursor write loses nothing, and re-fetching a page the vendor already\n// gave us is absorbed by the payload hash instead of producing duplicate work.\n//\n// One row per vendor record (latest payload only). A change re-issues `seq` (the apply order),\n// bumps `revision`, resets the row to `pending` and clears its attempts; an identical re-fetch\n// only stamps `last_seen_at`. Deletes are soft (`deleted_at`) so the projector's `remove` can act\n// on them.\n//\n// `payload` is JSONB and always written (a vendor `null` is stored as the JSON value null). Only\n// retention (pruneRecords, KEEL_SYNC_PAYLOAD_RETENTION_DAYS) sets the column to SQL NULL, keeping\n// `payload_hash` so the change guard still holds; a row read back in that state is `payloadShed`.\n\nexport type RecordState = \"pending\" | \"applied\" | \"failed\" | \"skipped\";\nexport type RecordSource = \"sync\" | \"reconcile\" | \"webhook\";\n\n// RecordScope identifies one entity's record set. connection_id is '' until multi-connection\n// integrations exist; it is part of the key now so that change needs no migration.\nexport type RecordScope = {\n  integrationName: string;\n  entity: string;\n  scope: string;\n  connectionId?: string;\n};\n\nexport type IngestItem = {\n  externalId: string;\n  payload: unknown;\n  // The vendor's own last-modified instant, when the author exposes one. Guards against an\n  // older payload (a late webhook, an overlapping page) overwriting a newer one.\n  sourceUpdatedMs?: number | null;\n};\n\nexport type IngestOptions = {\n  source: RecordSource;\n  reconcileId?: string | null;\n  runId?: string | null;\n};\n\nexport type IngestResult = {\n  // Items handed to ingest (after collapsing duplicates of the same key within the batch).\n  fetched: number;\n  // Rows inserted or re-issued a seq: the work the apply phase has to do for this batch.\n  changed: number;\n};\n\n// IngestedRecord is the per-row outcome of an ingest: the row's queue position and state after\n// the statement, and whether this ingest was what put it there (a new row, or a re-issued seq).\nexport type IngestedRecord = {\n  externalId: string;\n  seq: number;\n  revision: number;\n  state: RecordState;\n  // The hash the row holds after the statement: the incoming payload's when changed, else the\n  // stored one.\n  payloadHash: string;\n  changed: boolean;\n};\n\nexport type SyncRecordRow = {\n  integrationName: string;\n  connectionId: string;\n  entity: string;\n  scope: string;\n  externalId: string;\n  payload: unknown;\n  // True when retention shed the payload (SQL NULL) — `payload` is null and only `payloadHash`\n  // remains. False for a payload the vendor itself served as null.\n  payloadShed: boolean;\n  payloadHash: string;\n  sourceUpdatedMs: number | null;\n  seq: number;\n  revision: number;\n  state: RecordState;\n  attempts: number;\n  lastError: string | null;\n  appliedAt: Date | null;\n  deletedAt: Date | null;\n  firstSeenAt: Date;\n  lastSeenAt: Date;\n  lastSeenReconcileId: string | null;\n  source: RecordSource;\n  runId: string | null;\n};\n\nexport type StateCounts = Record<RecordState, number>;\n\nconst TABLE = \"keel.sync_record\";\n\n// Mutation counts in this module always come from an explicit RETURNING clause and the rows it\n// yields, never from kysely's UpdateResult/DeleteResult (numUpdatedRows). The functions\n// runtime's AuditContextPlugin appends its own RETURNING to every INSERT/UPDATE/DELETE\n// whenever a trace or identity is in scope, and kysely then resolves execute() with the\n// returned rows instead of a result object — so executeTakeFirst() on an update that matched\n// nothing is undefined in a deployed, traced runtime while it is a result object in a bare\n// test. Counting returned rows behaves the same in both.\nconst KEY_COLUMNS = [\n  \"integration_name\",\n  \"connection_id\",\n  \"entity\",\n  \"scope\",\n  \"external_id\",\n] as const;\n\n/**\n * payloadHash is a content fingerprint of a vendor payload: sha256 over a canonical JSON form\n * (object keys sorted recursively, arrays in order) so two payloads that differ only in key\n * order hash identically.\n */\nexport function payloadHash(payload: unknown): string {\n  return createHash(\"sha256\").update(stableStringify(payload)).digest(\"hex\");\n}\n\nexport function stableStringify(value: unknown): string {\n  if (value === null || typeof value !== \"object\") {\n    return JSON.stringify(value) ?? \"null\";\n  }\n  if (value instanceof Date) {\n    return JSON.stringify(value.toISOString());\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map((v) => stableStringify(v)).join(\",\")}]`;\n  }\n  const keys = Object.keys(value as Record<string, unknown>).sort();\n  const parts: string[] = [];\n  for (const key of keys) {\n    const v = (value as Record<string, unknown>)[key];\n    if (v === undefined) {\n      continue;\n    }\n    parts.push(`${JSON.stringify(key)}:${stableStringify(v)}`);\n  }\n  return `{${parts.join(\",\")}}`;\n}\n\n/**\n * ingestRecords writes one fetched batch into the record store. It always stamps every row as\n * seen (last_seen_at, and last_seen_reconcile_id when a reconcile id is given) and only\n * re-issues the row's seq (making it pending again) when the payload hash differs, or the row\n * was tombstoned, and the incoming source_updated_ms is not older than the stored one.\n *\n * Runs on the connection it is given, so inside a transaction it commits with the cursor.\n */\nexport async function ingestRecords(\n  db: Kysely<any>,\n  scope: RecordScope,\n  items: IngestItem[],\n  opts: IngestOptions\n): Promise<IngestResult> {\n  const batch = collapseBatch(items);\n  if (batch.length === 0) {\n    return { fetched: 0, changed: 0 };\n  }\n  const rows = await ingestBatch(db, scope, batch, opts);\n  return {\n    fetched: batch.length,\n    changed: rows.filter((row) => row.changed).length,\n  };\n}\n\n/**\n * ingestRecord writes a single vendor record the same way the walk does (same key, same change\n * guard) and reports the row's resulting seq, revision and state. This is the primitive behind\n * ingest from outside the walk (a webhook processor, an operator flow), where the caller needs\n * to know whether its payload was taken so it can decide whether to project it.\n */\nexport async function ingestRecord(\n  db: Kysely<any>,\n  scope: RecordScope,\n  item: IngestItem,\n  opts: IngestOptions\n): Promise<IngestedRecord> {\n  const [row] = await ingestBatch(db, scope, [item], opts);\n  return row;\n}\n\n// ingestBatch is the INSERT ... ON CONFLICT statement shared by both entry points. `batch` must\n// already be collapsed to one item per external id.\nasync function ingestBatch(\n  db: Kysely<any>,\n  scope: RecordScope,\n  batch: IngestItem[],\n  opts: IngestOptions\n): Promise<IngestedRecord[]> {\n  const connectionId = scope.connectionId ?? \"\";\n  const externalIds = batch.map((item) => item.externalId);\n\n  // A multi-row INSERT ... ON CONFLICT cannot report which rows it actually changed, so the\n  // seq of every existing row is read first; a row whose seq differs afterwards (or that did\n  // not exist) was re-issued. That read is not locking, so a writer that commits a newer\n  // version in between re-issues the seq too — the row must also hold this batch's hash for\n  // the change to count as ours (see below).\n  const before = await db\n    .selectFrom(TABLE)\n    .select([\"external_id\", \"seq\"])\n    .where(\"integration_name\", \"=\", scope.integrationName)\n    .where(\"connection_id\", \"=\", connectionId)\n    .where(\"entity\", \"=\", scope.entity)\n    .where(\"scope\", \"=\", scope.scope)\n    .where(\"external_id\", \"in\", externalIds)\n    .execute();\n  const seqBefore = new Map<string, string>(\n    before.map((row: any) => [row.externalId, String(row.seq)])\n  );\n\n  const values = batch.map((item) => ({\n    integration_name: scope.integrationName,\n    connection_id: connectionId,\n    entity: scope.entity,\n    scope: scope.scope,\n    external_id: item.externalId,\n    payload: JSON.stringify(item.payload ?? null),\n    payload_hash: payloadHash(item.payload ?? null),\n    source_updated_ms: item.sourceUpdatedMs ?? null,\n    source: opts.source,\n    run_id: opts.runId ?? null,\n    last_seen_reconcile_id: opts.reconcileId ?? null,\n  }));\n\n  // \"changed\" as seen from inside the DO UPDATE: content differs (or the row is a tombstone\n  // being revived), and the incoming version is not older than what we already hold.\n  const changed = sql`(\n    (${sql.ref(\"keel.sync_record.payload_hash\")} IS DISTINCT FROM ${sql.ref(\"excluded.payload_hash\")}\n      OR ${sql.ref(\"keel.sync_record.deleted_at\")} IS NOT NULL)\n    AND (\n      ${sql.ref(\"excluded.source_updated_ms\")} IS NULL\n      OR ${sql.ref(\"keel.sync_record.source_updated_ms\")} IS NULL\n      OR ${sql.ref(\"excluded.source_updated_ms\")} >= ${sql.ref(\"keel.sync_record.source_updated_ms\")}\n    )\n  )`;\n  const pick = (column: string) =>\n    sql`CASE WHEN ${changed} THEN ${sql.ref(`excluded.${column}`)} ELSE ${sql.ref(`keel.sync_record.${column}`)} END`;\n\n  const rows = await db\n    .insertInto(TABLE)\n    .values(values)\n    .onConflict((oc) =>\n      oc.columns([...KEY_COLUMNS]).doUpdateSet({\n        last_seen_at: sql`now()`,\n        last_seen_reconcile_id: sql`COALESCE(${sql.ref(\"excluded.last_seen_reconcile_id\")}, ${sql.ref(\"keel.sync_record.last_seen_reconcile_id\")})`,\n        payload: pick(\"payload\"),\n        payload_hash: pick(\"payload_hash\"),\n        source_updated_ms: pick(\"source_updated_ms\"),\n        source: pick(\"source\"),\n        run_id: pick(\"run_id\"),\n        seq: sql`CASE WHEN ${changed} THEN nextval(pg_get_serial_sequence('keel.sync_record', 'seq')) ELSE ${sql.ref(\"keel.sync_record.seq\")} END`,\n        revision: sql`CASE WHEN ${changed} THEN ${sql.ref(\"keel.sync_record.revision\")} + 1 ELSE ${sql.ref(\"keel.sync_record.revision\")} END`,\n        state: sql`CASE WHEN ${changed} THEN 'pending' ELSE ${sql.ref(\"keel.sync_record.state\")} END`,\n        attempts: sql`CASE WHEN ${changed} THEN 0 ELSE ${sql.ref(\"keel.sync_record.attempts\")} END`,\n        last_error: sql`CASE WHEN ${changed} THEN NULL ELSE ${sql.ref(\"keel.sync_record.last_error\")} END`,\n        applied_at: sql`CASE WHEN ${changed} THEN NULL ELSE ${sql.ref(\"keel.sync_record.applied_at\")} END`,\n        deleted_at: sql`CASE WHEN ${changed} THEN NULL ELSE ${sql.ref(\"keel.sync_record.deleted_at\")} END`,\n      })\n    )\n    .returning([\"external_id\", \"seq\", \"revision\", \"state\", \"payload_hash\"])\n    .execute();\n\n  const ourHash = new Map(values.map((v) => [v.external_id, v.payload_hash]));\n\n  // \"Taken\" means the row now carries this batch's payload and its seq was (re-)issued since\n  // the pre-read. A row re-issued by a concurrent writer whose newer payload won the guard\n  // carries that writer's hash, so a dropped stale item reports changed: false. (When the\n  // concurrent payload is byte-identical to ours the outcome is the same either way.)\n  return (rows as any[]).map((row) => ({\n    externalId: row.externalId,\n    seq: Number(row.seq),\n    revision: Number(row.revision),\n    state: row.state as RecordState,\n    payloadHash: row.payloadHash,\n    changed:\n      row.payloadHash === ourHash.get(row.externalId) &&\n      seqBefore.get(row.externalId) !== String(row.seq),\n  }));\n}\n\n// collapseBatch keeps one item per external id (the newest by source_updated_ms, else the last\n// one listed): Postgres rejects an INSERT ... ON CONFLICT DO UPDATE that touches the same row\n// twice, and a vendor page can legitimately repeat a record.\nfunction collapseBatch(items: IngestItem[]): IngestItem[] {\n  const byId = new Map<string, IngestItem>();\n  for (const item of items) {\n    const existing = byId.get(item.externalId);\n    if (\n      !existing ||\n      existing.sourceUpdatedMs == null ||\n      item.sourceUpdatedMs == null ||\n      item.sourceUpdatedMs >= existing.sourceUpdatedMs\n    ) {\n      byId.set(item.externalId, item);\n    }\n  }\n  return [...byId.values()];\n}\n\n/**\n * listPending returns the next records to project, oldest change first. Inside a transaction\n * the rows are locked (skipping ones another worker holds) for the transaction's duration.\n */\nexport async function listPending(\n  db: Kysely<any>,\n  scope: RecordScope,\n  limit: number,\n  // Only rows with a seq greater than this. The apply phase walks the queue in seq order and\n  // passes the last seq it handled, so a row that failed (and stays pending for a later retry)\n  // is not listed again in the same run.\n  afterSeq: number | string = 0\n): Promise<SyncRecordRow[]> {\n  const rows = await scoped(db.selectFrom(TABLE).selectAll(), scope)\n    .select(sql<string | null>`payload::text`.as(\"payloadRaw\"))\n    .where(\"state\", \"=\", \"pending\")\n    .where(\"seq\", \">\", String(afterSeq))\n    .orderBy(\"seq\", \"asc\")\n    .limit(limit)\n    .forUpdate()\n    .skipLocked()\n    .execute();\n  return rows.map(toRow);\n}\n\n/**\n * markApplied closes a record after its projector ran. Guarded by seq: if the record was\n * re-ingested with a new seq while the projector was running, the newer pending row is left\n * alone and false is returned.\n */\nexport async function markApplied(\n  db: Kysely<any>,\n  scope: RecordScope,\n  externalId: string,\n  seq: number | string\n): Promise<boolean> {\n  const mutated = await scoped(db.updateTable(TABLE), scope)\n    .set({\n      state: \"applied\",\n      applied_at: sql`now()`,\n      last_error: null,\n    })\n    .where(\"external_id\", \"=\", externalId)\n    .where(\"seq\", \"=\", String(seq))\n    .where(\"state\", \"=\", \"pending\")\n    .returning(\"external_id\")\n    .execute();\n  return mutated.length > 0;\n}\n\n/**\n * markAttemptFailed records a projector failure. The row stays pending until it has failed\n * maxAttempts times, then becomes `failed` and waits for a retry (resetFailed) or a new\n * revision from the vendor. Returns the resulting state, or null if the row moved on.\n */\nexport async function markAttemptFailed(\n  db: Kysely<any>,\n  scope: RecordScope,\n  externalId: string,\n  seq: number | string,\n  error: string,\n  maxAttempts: number\n): Promise<{ state: RecordState; attempts: number } | null> {\n  const row = await scoped(db.updateTable(TABLE), scope)\n    .set({\n      attempts: sql`${sql.ref(\"attempts\")} + 1`,\n      last_error: error,\n      state: sql`CASE WHEN ${sql.ref(\"attempts\")} + 1 >= ${maxAttempts} THEN 'failed' ELSE 'pending' END`,\n    })\n    .where(\"external_id\", \"=\", externalId)\n    .where(\"seq\", \"=\", String(seq))\n    .where(\"state\", \"=\", \"pending\")\n    .returning([\"state\", \"attempts\"])\n    .executeTakeFirst();\n  if (!row) {\n    return null;\n  }\n  return { state: row.state as RecordState, attempts: Number(row.attempts) };\n}\n\n/** markSkipped closes a record the projector cannot act on (e.g. a tombstone with no remove). */\nexport async function markSkipped(\n  db: Kysely<any>,\n  scope: RecordScope,\n  externalId: string,\n  seq: number | string,\n  reason: string\n): Promise<boolean> {\n  const mutated = await scoped(db.updateTable(TABLE), scope)\n    .set({ state: \"skipped\", last_error: reason })\n    .where(\"external_id\", \"=\", externalId)\n    .where(\"seq\", \"=\", String(seq))\n    .where(\"state\", \"=\", \"pending\")\n    .returning(\"external_id\")\n    .execute();\n  return mutated.length > 0;\n}\n\n/**\n * tombstoneUnseen soft-deletes every live record the given reconcile pass did not see: those\n * are the records the vendor no longer returns. Each becomes a pending delete for the apply\n * phase. Returns how many were tombstoned.\n */\nexport async function tombstoneUnseen(\n  db: Kysely<any>,\n  scope: RecordScope,\n  reconcileId: string,\n  // Only rows not seen by anyone since this instant. A record created at the vendor while the\n  // reconcile was paging (and ingested by an incremental walk or webhook meanwhile) was not in\n  // the pages the reconcile fetched, but it is alive.\n  seenBefore?: Date\n): Promise<number> {\n  let query = scoped(db.updateTable(TABLE), scope)\n    .set(tombstoneAssignments())\n    .where(\"deleted_at\", \"is\", null)\n    .where((eb) =>\n      eb.or([\n        eb(\"last_seen_reconcile_id\", \"is\", null),\n        eb(\"last_seen_reconcile_id\", \"!=\", reconcileId),\n      ])\n    );\n  if (seenBefore) {\n    query = query.where(\"last_seen_at\", \"<\", seenBefore);\n  }\n  const mutated = await query.returning(\"external_id\").execute();\n  return mutated.length;\n}\n\n/**\n * tombstone soft-deletes the given records (e.g. from a vendor's deleted-items feed or a\n * delete webhook). Each live one becomes a pending delete for the apply phase; already\n * tombstoned or unknown keys are left alone. Returns how many were tombstoned.\n */\nexport async function tombstone(\n  db: Kysely<any>,\n  scope: RecordScope,\n  externalIds: string[]\n): Promise<number> {\n  if (externalIds.length === 0) {\n    return 0;\n  }\n  const mutated = await scoped(db.updateTable(TABLE), scope)\n    .set(tombstoneAssignments())\n    .where(\"deleted_at\", \"is\", null)\n    .where(\"external_id\", \"in\", externalIds)\n    .returning(\"external_id\")\n    .execute();\n  return mutated.length;\n}\n\nfunction tombstoneAssignments() {\n  return {\n    deleted_at: sql`now()`,\n    seq: sql`nextval(pg_get_serial_sequence('keel.sync_record', 'seq'))`,\n    revision: sql`${sql.ref(\"revision\")} + 1`,\n    state: \"pending\",\n    attempts: 0,\n    last_error: null,\n    applied_at: null,\n  };\n}\n\n/** countLive counts records not tombstoned, for reconcile's shrink guard. */\nexport async function countLive(\n  db: Kysely<any>,\n  scope: RecordScope\n): Promise<number> {\n  const row = await scoped(db.selectFrom(TABLE), scope)\n    .select(sql<string>`count(*)`.as(\"n\"))\n    .where(\"deleted_at\", \"is\", null)\n    .executeTakeFirstOrThrow();\n  return Number(row.n);\n}\n\n/** countStates reports how many records are in each apply state for one entity (all scopes). */\nexport async function countStates(\n  db: Kysely<any>,\n  integrationName: string,\n  entity: string,\n  scope?: string\n): Promise<StateCounts> {\n  let query = db\n    .selectFrom(TABLE)\n    .select([\"state\", sql<string>`count(*)`.as(\"n\")])\n    .where(\"integration_name\", \"=\", integrationName)\n    .where(\"entity\", \"=\", entity);\n  if (scope !== undefined) {\n    query = query.where(\"scope\", \"=\", scope);\n  }\n  const rows = await query.groupBy(\"state\").execute();\n\n  const counts: StateCounts = { pending: 0, applied: 0, failed: 0, skipped: 0 };\n  for (const row of rows as any[]) {\n    if (row.state in counts) {\n      counts[row.state as RecordState] = Number(row.n);\n    }\n  }\n  return counts;\n}\n\n/** resetFailed puts every failed record of an entity back to pending with a clean slate. */\nexport async function resetFailed(\n  db: Kysely<any>,\n  integrationName: string,\n  entity: string\n): Promise<number> {\n  const mutated = await db\n    .updateTable(TABLE)\n    .set({ state: \"pending\", attempts: 0, last_error: null })\n    .where(\"integration_name\", \"=\", integrationName)\n    .where(\"entity\", \"=\", entity)\n    .where(\"state\", \"=\", \"failed\")\n    .returning(\"external_id\")\n    .execute();\n  return mutated.length;\n}\n\nexport type PruneOptions = {\n  // Delete applied/skipped tombstones older than this many days.\n  tombstoneRetentionDays: number;\n  // Null the payload of applied rows older than this many days, keeping the hash so an\n  // identical re-fetch is still a no-op. Undefined = keep payloads forever.\n  payloadRetentionDays?: number;\n  // Rows touched per call; the caller loops or waits for the next tick.\n  limit?: number;\n};\n\nexport type PruneResult = { tombstonesDeleted: number; payloadsShed: number };\n\n/**\n * pruneRecords applies retention to one entity's record set. It never touches pending or failed\n * rows (their payload is still needed to apply or retry them), and is bounded per call so a\n * large backlog is worked off across ticks instead of in one long statement.\n */\nexport async function pruneRecords(\n  db: Kysely<any>,\n  scope: RecordScope,\n  opts: PruneOptions\n): Promise<PruneResult> {\n  const limit = opts.limit ?? 1000;\n  const result: PruneResult = { tombstonesDeleted: 0, payloadsShed: 0 };\n\n  const tombstoneCutoff = sql`now() - make_interval(days => ${opts.tombstoneRetentionDays})`;\n  const deleted = await db\n    .deleteFrom(TABLE)\n    .where(\n      \"ctid\",\n      \"in\",\n      scoped(db.selectFrom(TABLE).select(\"ctid\"), scope)\n        .where(\"deleted_at\", \"is not\", null)\n        .where(\"deleted_at\", \"<\", tombstoneCutoff)\n        .where(\"state\", \"in\", [\"applied\", \"skipped\"])\n        .limit(limit)\n    )\n    .returning(\"external_id\")\n    .execute();\n  result.tombstonesDeleted = deleted.length;\n\n  if (opts.payloadRetentionDays !== undefined) {\n    const payloadCutoff = sql`now() - make_interval(days => ${opts.payloadRetentionDays})`;\n    const shed = await db\n      .updateTable(TABLE)\n      .set({ payload: null })\n      .where(\n        \"ctid\",\n        \"in\",\n        scoped(db.selectFrom(TABLE).select(\"ctid\"), scope)\n          .where(\"state\", \"=\", \"applied\")\n          .where(\"payload\", \"is not\", null)\n          .where(\"applied_at\", \"<\", payloadCutoff)\n          .limit(limit)\n      )\n      .returning(\"external_id\")\n      .execute();\n    result.payloadsShed = shed.length;\n  }\n\n  return result;\n}\n\n/** getRecord reads one record; mostly for tests and diagnostics. */\nexport async function getRecord(\n  db: Kysely<any>,\n  scope: RecordScope,\n  externalId: string\n): Promise<SyncRecordRow | null> {\n  const row = await scoped(db.selectFrom(TABLE).selectAll(), scope)\n    .select(sql<string | null>`payload::text`.as(\"payloadRaw\"))\n    .where(\"external_id\", \"=\", externalId)\n    .executeTakeFirst();\n  return row ? toRow(row) : null;\n}\n\nfunction scoped<Q extends { where: any }>(query: Q, scope: RecordScope): Q {\n  return query\n    .where(\"integration_name\", \"=\", scope.integrationName)\n    .where(\"connection_id\", \"=\", scope.connectionId ?? \"\")\n    .where(\"entity\", \"=\", scope.entity)\n    .where(\"scope\", \"=\", scope.scope);\n}\n\nfunction toRow(row: any): SyncRecordRow {\n  return {\n    integrationName: row.integrationName,\n    connectionId: row.connectionId,\n    entity: row.entity,\n    scope: row.scope,\n    externalId: row.externalId,\n    payload: row.payloadRaw != null ? JSON.parse(row.payloadRaw) : null,\n    payloadShed: row.payloadRaw == null,\n    payloadHash: row.payloadHash,\n    sourceUpdatedMs:\n      row.sourceUpdatedMs == null ? null : Number(row.sourceUpdatedMs),\n    seq: Number(row.seq),\n    revision: Number(row.revision),\n    state: row.state,\n    attempts: Number(row.attempts),\n    lastError: row.lastError ?? null,\n    appliedAt: row.appliedAt ?? null,\n    deletedAt: row.deletedAt ?? null,\n    firstSeenAt: row.firstSeenAt,\n    lastSeenAt: row.lastSeenAt,\n    lastSeenReconcileId: row.lastSeenReconcileId ?? null,\n    source: row.source,\n    runId: row.runId ?? null,\n  };\n}\n","import * as opentelemetry from \"@opentelemetry/api\";\nimport { log } from \"../logger\";\nimport { ATTRS } from \"../tracing\";\nimport type { RecordState } from \"./records\";\n\n// Structured observability for the sync engine. Every event carries the shared keel.sync.*\n// vocabulary (telemetry/attrs.go and tracing.js ATTRS, parity-tested) so a page, a batch or a\n// reconcile pass can be found by integration/entity/scope in logs and traces alike. Values are\n// identifiers and counts only — never a payload, a secret or a vendor response.\n\nexport type SyncUnit = {\n  integrationName: string;\n  entity: string;\n  scope: string;\n  strategy?: string;\n  mode?: \"incremental\" | \"reconcile\";\n};\n\ntype Fields = Record<string, string | number | boolean | null | undefined>;\n\n// Mirrors telemetry.AttrErrorMessage (Go). The unprefixed \"error\" family is shared by canonical\n// events and error spans and deliberately lives outside the keel.* ATTRS object (tracing.js\n// requires every ATTRS value to be keel.*-prefixed; telemetry/parity_test.go allowlists it).\nconst ERROR_MESSAGE = \"error.message\";\n\nfunction base(unit: SyncUnit, phase: \"ingest\" | \"apply\" | \"prune\"): Fields {\n  return {\n    [ATTRS.SYNC_INTEGRATION]: unit.integrationName,\n    [ATTRS.SYNC_ENTITY]: unit.entity,\n    [ATTRS.SYNC_SCOPE]: unit.scope,\n    [ATTRS.SYNC_STRATEGY]: unit.strategy,\n    [ATTRS.SYNC_MODE]: unit.mode ?? \"incremental\",\n    [ATTRS.SYNC_PHASE]: phase,\n  };\n}\n\n// annotateSpan copies the fields onto the active span (the flow step's span when called from\n// inside a step body) so the trace view shows the same numbers as the log line.\nfunction annotateSpan(fields: Fields): void {\n  const span = opentelemetry.trace.getActiveSpan();\n  if (!span) {\n    return;\n  }\n  for (const [key, value] of Object.entries(fields)) {\n    if (value !== undefined && value !== null) {\n      span.setAttribute(key, value);\n    }\n  }\n}\n\nfunction emit(\n  level: \"info\" | \"warn\" | \"error\",\n  msg: string,\n  fields: Fields\n): void {\n  const clean: Fields = {};\n  for (const [key, value] of Object.entries(fields)) {\n    if (value !== undefined) {\n      clean[key] = value;\n    }\n  }\n  annotateSpan(clean);\n  log[level](msg, clean);\n}\n\nexport function pageIngested(\n  unit: SyncUnit,\n  detail: {\n    page: number;\n    fetched: number;\n    changed: number;\n    tombstoned: number;\n    drained: boolean;\n    reconcileId?: string | null;\n  }\n): void {\n  emit(\"info\", \"sync page ingested\", {\n    ...base(unit, \"ingest\"),\n    [ATTRS.SYNC_PAGE]: detail.page,\n    [ATTRS.SYNC_RECONCILE_ID]: detail.reconcileId ?? undefined,\n    [ATTRS.SYNC_RECORDS_FETCHED]: detail.fetched,\n    [ATTRS.SYNC_RECORDS_CHANGED]: detail.changed,\n    [ATTRS.SYNC_RECORDS_TOMBSTONED]: detail.tombstoned,\n    [ATTRS.OUTCOME]: detail.drained ? \"drained\" : \"continued\",\n  });\n}\n\nexport function reconcileDrained(\n  unit: SyncUnit,\n  detail: {\n    reconcileId: string;\n    fetched: number;\n    live: number;\n    tombstoned: number;\n    guardTripped: boolean;\n  }\n): void {\n  emit(\n    detail.guardTripped ? \"warn\" : \"info\",\n    detail.guardTripped\n      ? \"sync reconcile guard tripped\"\n      : \"sync reconcile drained\",\n    {\n      ...base(unit, \"ingest\"),\n      [ATTRS.SYNC_RECONCILE_ID]: detail.reconcileId,\n      [ATTRS.SYNC_RECORDS_FETCHED]: detail.fetched,\n      [ATTRS.SYNC_RECORDS_LIVE]: detail.live,\n      [ATTRS.SYNC_RECORDS_TOMBSTONED]: detail.tombstoned,\n      [ATTRS.OUTCOME]: detail.guardTripped ? \"guarded\" : \"tombstoned\",\n    }\n  );\n}\n\n// rateBudgetLow: the walk paused before fetching a page because the vendor budget the proxy last\n// observed sits below the manifest's reserve (which exists for operator flows and webhooks).\nexport function rateBudgetLow(\n  unit: SyncUnit,\n  detail: { remaining: number; reserve: number; page: number }\n): void {\n  emit(\"warn\", \"sync rate budget low\", {\n    ...base(unit, \"ingest\"),\n    [ATTRS.SYNC_PAGE]: detail.page,\n    [ATTRS.SYNC_RATE_LIMIT_REMAINING]: detail.remaining,\n    [ATTRS.SYNC_RATE_LIMIT_RESERVE]: detail.reserve,\n    [ATTRS.OUTCOME]: \"paused\",\n  });\n}\n\n// recordIngested: one vendor record written to the store from outside the walk (syncIngest —\n// a webhook processor or an operator flow). Per record rather than per page, because that is\n// the unit those callers work in.\nexport function recordIngested(\n  unit: SyncUnit,\n  detail: { externalId: string; changed: boolean; state: RecordState }\n): void {\n  emit(\"info\", \"sync record ingested\", {\n    ...base(unit, \"ingest\"),\n    [ATTRS.SYNC_RECORD_EXTERNAL_ID]: detail.externalId,\n    [ATTRS.OUTCOME]: detail.changed ? \"changed\" : \"unchanged\",\n  });\n}\n\nexport function recordApplyFailed(\n  unit: SyncUnit,\n  detail: {\n    externalId: string;\n    attempts: number;\n    exhausted: boolean;\n    error: string;\n  }\n): void {\n  emit(\"warn\", \"sync record apply failed\", {\n    ...base(unit, \"apply\"),\n    [ATTRS.SYNC_RECORD_EXTERNAL_ID]: detail.externalId,\n    [ATTRS.SYNC_RECORD_ATTEMPTS]: detail.attempts,\n    [ATTRS.OUTCOME]: detail.exhausted ? \"failed\" : \"retrying\",\n    [ERROR_MESSAGE]: detail.error,\n  });\n}\n\nexport function batchApplied(\n  unit: SyncUnit,\n  detail: {\n    batch: number;\n    applied: number;\n    failed: number;\n    retrying: number;\n    skipped: number;\n    drained: boolean;\n  }\n): void {\n  emit(\"info\", \"sync batch applied\", {\n    ...base(unit, \"apply\"),\n    [ATTRS.SYNC_PAGE]: detail.batch,\n    [ATTRS.SYNC_RECORDS_APPLIED]: detail.applied,\n    [ATTRS.SYNC_RECORDS_FAILED]: detail.failed + detail.retrying,\n    [ATTRS.SYNC_RECORDS_SKIPPED]: detail.skipped,\n    [ATTRS.OUTCOME]: detail.drained ? \"drained\" : \"continued\",\n  });\n}\n\nexport function systemicApplyFailure(\n  unit: SyncUnit,\n  detail: { batch: number; errored: number; attempted: number; error: string }\n): void {\n  emit(\"error\", \"sync systemic apply failure\", {\n    ...base(unit, \"apply\"),\n    [ATTRS.SYNC_PAGE]: detail.batch,\n    [ATTRS.SYNC_RECORDS_FAILED]: detail.errored,\n    [ATTRS.SYNC_RECORDS_ATTEMPTED]: detail.attempted,\n    [ERROR_MESSAGE]: detail.error,\n  });\n}\n","import { Kysely } from \"kysely\";\nimport { useDatabase } from \"../database\";\nimport {\n  listPending,\n  markApplied,\n  markAttemptFailed,\n  markSkipped,\n  RecordScope,\n  SyncRecordRow,\n} from \"./records\";\nimport { withSyncTransaction } from \"./store\";\nimport { recordingFailure } from \"./walk\";\nimport * as telemetry from \"./telemetry\";\nimport type { SyncDefinition, SyncEngineHooks } from \"./index\";\n\n// The apply phase: project pending records from the store into the project's models. Runs\n// after an entity's ingest walk (drained or paused) under its own step budget, one durable step\n// per batch, records in seq order. Each record is projected in its own transaction together\n// with its state change, so a projector that throws leaves no half-written model row and the\n// record is retried on a later tick, up to a bounded number of attempts.\n\nexport type ApplyOutcome = {\n  status: \"drained\" | \"paused\";\n  batches: number;\n  applied: number;\n  // records whose attempts are exhausted (state failed)\n  failed: number;\n  // records that errored this run but stay pending for a later tick\n  retrying: number;\n  skipped: number;\n  // Sample of the first projector errors this run, for the run summary.\n  errorSamples: string[];\n};\n\nexport type ApplyBudget = {\n  // Batch steps this run may spend on this work item before pausing.\n  batches: number;\n  batchSize: number;\n};\n\nconst MAX_ERROR_SAMPLES = 3;\n\n// A batch of at least this many records where more than SYSTEMIC_FAILURE_RATIO fail is a broken\n// projector or schema, not bad data: the step fails visibly after bookkeeping instead of\n// quietly burning every record's attempts.\nconst SYSTEMIC_MIN_BATCH = 10;\nconst SYSTEMIC_FAILURE_RATIO = 0.5;\n\nexport function applyBatchSize(): number {\n  const fromEnv = parseInt(process.env.KEEL_SYNC_APPLY_BATCH ?? \"\", 10);\n  return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 100;\n}\n\nexport function applyBatchesPerRun(): number {\n  const fromEnv = parseInt(\n    process.env.KEEL_SYNC_APPLY_BATCHES_PER_RUN ?? \"\",\n    10\n  );\n  return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 40;\n}\n\nexport function applyMaxAttempts(): number {\n  const fromEnv = parseInt(process.env.KEEL_SYNC_APPLY_MAX_ATTEMPTS ?? \"\", 10);\n  return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 5;\n}\n\nexport async function applyPending(opts: {\n  db: Kysely<any>;\n  scope: RecordScope;\n  // Step-name prefix; defaults to entity[/scope].\n  label?: string;\n  // For telemetry only.\n  strategy?: string;\n  mode?: \"incremental\" | \"reconcile\";\n  definition: SyncDefinition<any>;\n  hooks?: SyncEngineHooks;\n  budget: ApplyBudget;\n  step: <T>(\n    name: string,\n    fn: () => Promise<T>\n  ) => Promise<T | null | undefined>;\n}): Promise<ApplyOutcome> {\n  const { db, scope, definition, budget, step } = opts;\n  const itemLabel =\n    opts.label ?? `${scope.entity}${scope.scope ? `/${scope.scope}` : \"\"}`;\n  const maxAttempts = applyMaxAttempts();\n  const unit: telemetry.SyncUnit = {\n    integrationName: scope.integrationName,\n    entity: scope.entity,\n    scope: scope.scope,\n    strategy: opts.strategy,\n    mode: opts.mode ?? \"incremental\",\n  };\n\n  const outcome: ApplyOutcome = {\n    status: \"paused\",\n    batches: 0,\n    applied: 0,\n    failed: 0,\n    retrying: 0,\n    skipped: 0,\n    errorSamples: [],\n  };\n\n  // Like the walk, this loop must be deterministic under replay: every decision comes from a\n  // cached step result. The queue position (last seq handled) is carried between steps in\n  // their return values rather than re-read from the store.\n  let afterSeq: string = \"0\";\n\n  while (outcome.batches < budget.batches) {\n    const batchNo = outcome.batches + 1;\n    const result = await step(`${itemLabel}: apply batch ${batchNo}`, () =>\n      recordingFailure(db, scope, async () => {\n        const rows = await listPending(db, scope, budget.batchSize, afterSeq);\n        const summary = {\n          applied: 0,\n          failed: 0,\n          retrying: 0,\n          skipped: 0,\n          errorSamples: [] as string[],\n          lastSeq: afterSeq,\n          drained: rows.length < budget.batchSize,\n        };\n\n        for (const row of rows) {\n          summary.lastSeq = String(row.seq);\n          const result = await applyOne(\n            unit,\n            scope,\n            definition,\n            row,\n            maxAttempts,\n            opts.hooks\n          );\n          summary[result.outcome]++;\n          if (\n            result.error &&\n            summary.errorSamples.length < MAX_ERROR_SAMPLES &&\n            !summary.errorSamples.includes(result.error)\n          ) {\n            summary.errorSamples.push(result.error);\n          }\n        }\n\n        const errored = summary.failed + summary.retrying;\n        const attempted = summary.applied + errored;\n        if (\n          attempted >= SYSTEMIC_MIN_BATCH &&\n          errored / attempted > SYSTEMIC_FAILURE_RATIO\n        ) {\n          // Bookkeeping is done (attempts and errors are on the rows); now fail the step so\n          // the run is visibly broken rather than silently degraded.\n          const message = `sync ${scope.entity}: ${errored}/${attempted} records failed to apply in batch ${batchNo} (first errors: ${summary.errorSamples.join(\"; \")})`;\n          telemetry.systemicApplyFailure(unit, {\n            batch: batchNo,\n            errored,\n            attempted,\n            error: message,\n          });\n          throw new Error(message);\n        }\n\n        telemetry.batchApplied(unit, {\n          batch: batchNo,\n          applied: summary.applied,\n          failed: summary.failed,\n          retrying: summary.retrying,\n          skipped: summary.skipped,\n          drained: summary.drained,\n        });\n        return summary;\n      })\n    );\n\n    if (!result) {\n      break;\n    }\n\n    outcome.batches++;\n    outcome.applied += result.applied;\n    outcome.failed += result.failed;\n    outcome.retrying += result.retrying;\n    outcome.skipped += result.skipped;\n    for (const sample of result.errorSamples) {\n      if (\n        outcome.errorSamples.length < MAX_ERROR_SAMPLES &&\n        !outcome.errorSamples.includes(sample)\n      ) {\n        outcome.errorSamples.push(sample);\n      }\n    }\n    afterSeq = result.lastSeq;\n\n    if (result.drained) {\n      outcome.status = \"drained\";\n      break;\n    }\n  }\n\n  return outcome;\n}\n\n// applyOne projects a single record. The projector and the record's state change share one\n// transaction; on failure that transaction is rolled back and the attempt is recorded in\n// autocommit so the bookkeeping survives.\nasync function applyOne(\n  unit: telemetry.SyncUnit,\n  scope: RecordScope,\n  definition: SyncDefinition<any>,\n  row: SyncRecordRow,\n  maxAttempts: number,\n  hooks?: SyncEngineHooks\n): Promise<{\n  outcome: \"applied\" | \"failed\" | \"retrying\" | \"skipped\";\n  error?: string;\n}> {\n  if (row.deletedAt && !definition.remove) {\n    await markSkipped(\n      useDatabase(),\n      scope,\n      row.externalId,\n      row.seq,\n      \"record was deleted at the vendor but the sync definition has no remove handler\"\n    );\n    return { outcome: \"skipped\" };\n  }\n\n  try {\n    await withSyncTransaction(async () => {\n      const trx = useDatabase();\n      if (row.deletedAt) {\n        await definition.remove!(row.externalId, row.payload);\n      } else {\n        await definition.upsert(row.payload);\n      }\n      await hooks?.beforeMarkApplied?.({\n        entity: scope.entity,\n        scope: scope.scope,\n        externalId: row.externalId,\n      });\n      await markApplied(trx, scope, row.externalId, row.seq);\n    });\n    return { outcome: \"applied\" };\n  } catch (e) {\n    const message = e instanceof Error ? e.message : String(e);\n    const state = await markAttemptFailed(\n      useDatabase(),\n      scope,\n      row.externalId,\n      row.seq,\n      message,\n      maxAttempts\n    );\n    // Only an exhausted row is a hard failure; one that stays pending is retried on a later\n    // tick. A row that moved on (re-ingested with a new seq meanwhile) is simply left to its\n    // new revision.\n    if (!state) {\n      return { outcome: \"skipped\", error: message };\n    }\n    telemetry.recordApplyFailed(unit, {\n      externalId: row.externalId,\n      attempts: state.attempts,\n      exhausted: state.state === \"failed\",\n      error: message,\n    });\n    return {\n      outcome: state.state === \"failed\" ? \"failed\" : \"retrying\",\n      error: message,\n    };\n  }\n}\n","import { sql } from \"kysely\";\nimport {\n  useDatabase,\n  withDatabase,\n  isInDatabaseTransaction,\n  deferFileDeletion,\n} from \"../database\";\nimport { prepareInsertRow, collectFileKeys } from \"../ModelAPI\";\nimport { snakeCase, snakeCaseObject } from \"../casing\";\nimport { transformRichDataTypes } from \"../parsing\";\nimport { DatabaseError } from \"../errors\";\nimport * as tracing from \"../tracing\";\n\n/**\n * What syncUpsert accepts as a model: a generated `models.<name>` API (anything with a typed\n * `create`). The API's create-values type becomes the type of `values`, so a projector gets the\n * same checking as `models.<name>.create`. The table metadata the statement needs lives on the\n * runtime ModelAPI instance behind that type and is read at run time.\n */\nexport type SyncUpsertModel<V = Record<string, unknown>, R = unknown> = {\n  create(values: V): Promise<R>;\n};\n\ntype ModelInternals = {\n  _tableName?: string;\n  _tableConfigMap?: Record<string, any>;\n  _modelName?: string;\n  // camelCase File field name -> repeated, from the generated fileFieldsMap.\n  _fileFields?: Record<string, boolean>;\n};\n\n// Postgres: \"there is no unique or exclusion constraint matching the ON CONFLICT specification\".\nconst NO_MATCHING_UNIQUE_CONSTRAINT = \"42P10\";\n\n/**\n * Insert a model row keyed by an external identifier, or update the existing row with the same\n * key, in a single `INSERT ... ON CONFLICT DO UPDATE` statement.\n *\n * This is the write primitive for sync projectors. The hand-rolled `findOne` + `create` /\n * `update` pair is not atomic: two writers racing on the same vendor record (a webhook and a\n * sync page, or two sync ticks) both miss on the read and one of them fails on the unique\n * constraint. A single upsert statement lets Postgres arbitrate, so it is safe to call\n * concurrently and safe to replay.\n *\n * `conflictField` must be declared `@unique` in the schema; that is what gives the table the\n * unique constraint the statement targets. Values go through the same pipeline as\n * `models.<name>.create`, so rich Keel types and belongs-to references (`{ id }`) work the same\n * way. Nested has-many creates are not supported because they cannot be expressed as one\n * statement.\n *\n * The write runs on `useDatabase()`, so inside a transaction it lands in that transaction. The\n * `id`, `created_at` and `updated_at` columns are never overwritten on conflict; `updated_at` is\n * bumped by the table's trigger when the row content changes.\n *\n * File fields get the same cleanup as `models.<name>.update`: when the upsert replaces or clears\n * a stored file on an existing row, the previous storage object is deleted once the surrounding\n * transaction commits. Knowing which keys were replaced takes a read of the row before the\n * statement, so a write that touches a File field runs in a transaction (joining the caller's\n * when there is one) and serialises with other writers on the same key through a\n * transaction-scoped advisory lock. Concurrent writers therefore see each other's files and no\n * key is deleted while a row still points at it.\n *\n * @example\n * await syncUpsert(models.stripeCustomer, \"customerId\", {\n *   customerId: customer.id,\n *   email: customer.email,\n * });\n */\nexport async function syncUpsert<V extends Record<string, any>, R = V>(\n  model: SyncUpsertModel<V, R>,\n  conflictField: Extract<keyof V, string>,\n  values: V\n): Promise<R> {\n  const internals = model as unknown as ModelInternals;\n  const tableName = internals._tableName;\n  if (!tableName) {\n    throw new Error(\n      \"syncUpsert: expected a models.<name> API (a ModelAPI instance) as the first argument\"\n    );\n  }\n  const modelName = internals._modelName ?? tableName;\n  const conflictColumn = snakeCase(conflictField);\n\n  if (!values || values[conflictField] === undefined) {\n    throw new Error(\n      `syncUpsert: values for ${modelName} must include the conflict field \"${conflictField}\"`\n    );\n  }\n\n  // Camel-case File fields the incoming values touch; these need the pre-read and cleanup.\n  const fileFields = Object.keys(values).filter(\n    (field) => field in (internals._fileFields ?? {})\n  );\n\n  const write = async (): Promise<R> => {\n    const db = useDatabase();\n\n    const { row, hasManyRecords } = await prepareInsertRow(\n      db,\n      tableName,\n      internals._tableConfigMap ?? {},\n      snakeCaseObject(values)\n    );\n\n    if (hasManyRecords.length > 0) {\n      throw new Error(\n        `syncUpsert: nested has-many writes are not supported (${modelName}.${hasManyRecords[0].key}); upsert the related records separately`\n      );\n    }\n\n    if (!(conflictColumn in row)) {\n      throw new Error(\n        `syncUpsert: conflict field \"${conflictField}\" did not resolve to a column of ${modelName}`\n      );\n    }\n    const keyValue = (row as Record<string, unknown>)[conflictColumn];\n\n    // Files the incoming values replace or clear must be removed from storage, as\n    // ModelAPI.update does. The statement below cannot return the pre-update values, so read\n    // them first, holding a per-key advisory lock for the rest of the transaction so a\n    // concurrent writer on this key waits here and then reads what this write committed.\n    let existingFileRow: Record<string, unknown> | undefined;\n    if (fileFields.length > 0) {\n      await sql`select pg_advisory_xact_lock(hashtext(${`${tableName}:${conflictColumn}:${String(keyValue)}`}))`.execute(\n        db\n      );\n      const existing = await db\n        .selectFrom(tableName)\n        .selectAll()\n        .where(conflictColumn, \"=\", keyValue)\n        .executeTakeFirst();\n      existingFileRow = existing\n        ? (transformRichDataTypes(existing) as Record<string, unknown>)\n        : undefined;\n    }\n\n    // Every provided column except the key itself and the identity/timestamp columns is\n    // overwritten from the incoming row on conflict.\n    const updateColumns = Object.keys(row).filter(\n      (column) =>\n        column !== conflictColumn &&\n        column !== \"id\" &&\n        column !== \"created_at\" &&\n        column !== \"updated_at\"\n    );\n    const updates: Record<string, unknown> = {};\n    for (const column of updateColumns) {\n      updates[column] = sql.ref(`excluded.${column}`);\n    }\n    if (updateColumns.length === 0) {\n      // A no-op assignment still makes DO UPDATE return the existing row.\n      updates[conflictColumn] = sql.ref(`excluded.${conflictColumn}`);\n    }\n\n    try {\n      const result = await db\n        .insertInto(tableName)\n        .values(row)\n        .onConflict((oc) => oc.column(conflictColumn).doUpdateSet(updates))\n        .returningAll()\n        .executeTakeFirstOrThrow();\n\n      const written = transformRichDataTypes(result) as Record<string, unknown>;\n      if (existingFileRow) {\n        const retained = new Set(collectFileKeys([written], fileFields));\n        for (const key of collectFileKeys([existingFileRow], fileFields)) {\n          if (!retained.has(key)) {\n            deferFileDeletion(key);\n          }\n        }\n      }\n      return written as R;\n    } catch (e: any) {\n      if (e?.code === NO_MATCHING_UNIQUE_CONSTRAINT) {\n        throw new Error(\n          `syncUpsert: ${modelName}.${conflictField} has no unique constraint. Mark the field @unique in the schema so the upsert can target it.`\n        );\n      }\n      throw new DatabaseError(e);\n    }\n  };\n\n  return tracing.withDbQuerySpan(modelName, \"upsert\", async () => {\n    if (fileFields.length === 0 || isInDatabaseTransaction()) {\n      return write();\n    }\n    // The advisory lock and the deferred deletions are transaction-scoped; give the write one\n    // when the caller has none. useDatabase().transaction() would deadlock on a flow step's\n    // pinned connection, so go through withDatabase like the engine does.\n    return withDatabase(useDatabase(), true, () => write());\n  });\n}\n","import { useDatabase } from \"../database\";\nimport * as tracing from \"../tracing\";\nimport {\n  getRecord,\n  ingestRecord,\n  markApplied,\n  payloadHash,\n  type IngestItem,\n  type RecordScope,\n  type RecordSource,\n  type RecordState,\n  type SyncRecordRow,\n} from \"./records\";\nimport { withSyncTransaction } from \"./store\";\nimport * as telemetry from \"./telemetry\";\n\n// The public face of the record store (keel.sync_record): read a stored vendor payload from\n// module or consumer code, and write one that arrived outside the sync walk (a webhook, an\n// operator flow) so the store stays the single source of the raw payload. Both run on\n// useDatabase(), so inside a flow step, a function, a subscriber or a route they use the caller's\n// connection and join its transaction when there is one.\n\n/**\n * A module as seen through its generated `_module.gen.ts` (`import * as acme from \"../_module.gen\"`):\n * `name` is the integration name and `syncEntities` the manifest's declared sync entities. Passing\n * the module instead of a bare name narrows the `entity` argument to those declared names.\n */\nexport type SyncModuleRef = {\n  readonly name: string;\n  readonly syncEntities?: ReadonlyArray<{ readonly name: string }>;\n};\n\ntype SyncEntityOf<M> = M extends {\n  syncEntities: ReadonlyArray<{ name: infer N extends string }>;\n}\n  ? N\n  : string;\n\nexport type SyncRecordOptions = {\n  // The record set within the entity (a store handle, an account id); \"\" — the default — is the\n  // unscoped set an entity without `scopes` writes to.\n  scope?: string;\n  // \"\" until multi-connection integrations exist.\n  connectionId?: string;\n};\n\n/**\n * One row of the record store as `syncRecord` returns it. Field names match the records\n * endpoint of the integrations API, so the two views of a record agree.\n *\n * `payload` is the vendor object exactly as it was last ingested. It is `null` in two cases the\n * `payloadShed` flag tells apart: the vendor served null (`payloadShed: false`), or retention\n * (`KEEL_SYNC_PAYLOAD_RETENTION_DAYS`) shed it (`payloadShed: true`). A shed row keeps its\n * `payloadHash`, so an identical re-fetch is still a no-op and the payload only returns once the\n * vendor record changes or is re-ingested with `syncIngest`.\n */\nexport type SyncRecord = Omit<SyncRecordRow, \"lastSeenReconcileId\">;\n\nexport type SyncIngestOptions = SyncRecordOptions & {\n  // Who is writing; defaults to \"webhook\". The walk itself writes \"sync\" and \"reconcile\".\n  source?: RecordSource;\n  // \"pending\" (the default) leaves projection to the next tick's apply phase, which calls the\n  // entity's upsert for the row. \"applied\" records that the caller has already projected this\n  // payload (typically with syncUpsert in the same handler). It takes effect when this ingest\n  // changed the row, or when the row was pending for exactly this payload; it never touches a\n  // row that holds a newer version, or one an operator skipped.\n  state?: \"pending\" | \"applied\";\n  runId?: string | null;\n};\n\nexport type SyncIngestResult = {\n  // True when this payload was taken: the row is new, or its content differs from what was\n  // stored and it is not older (by sourceUpdatedMs) than the stored version. False means the\n  // store already held this payload or a newer one, and nothing but last_seen_at moved.\n  changed: boolean;\n  // The row's state after the call.\n  state: RecordState;\n  seq: number;\n  revision: number;\n};\n\n/**\n * Read one record from the sync record store: the last payload the engine (or `syncIngest`)\n * stored for a vendor id, with its state and bookkeeping. Returns null when the entity has never\n * seen that id.\n *\n * Reads on `useDatabase()`, so it works inside flows, functions, subscribers and routes, and sees\n * the caller's own uncommitted writes when called inside a transaction.\n *\n * `integration` is the integration name, or the module's generated `_module.gen.ts` namespace\n * import, which narrows `entity` to the manifest's declared sync entities.\n *\n * @example\n * import * as xero from \"../_module.gen\";\n * const rec = await syncRecord(xero, \"invoices\", invoiceId);\n * if (rec && !rec.payloadShed) {\n *   const lineItems = (rec.payload as XeroInvoice).LineItems;\n * }\n */\nexport function syncRecord<M extends SyncModuleRef>(\n  module: M,\n  entity: SyncEntityOf<M>,\n  externalId: string,\n  opts?: SyncRecordOptions\n): Promise<SyncRecord | null>;\nexport function syncRecord(\n  integration: string,\n  entity: string,\n  externalId: string,\n  opts?: SyncRecordOptions\n): Promise<SyncRecord | null>;\nexport async function syncRecord(\n  integration: string | SyncModuleRef,\n  entity: string,\n  externalId: string,\n  opts: SyncRecordOptions = {}\n): Promise<SyncRecord | null> {\n  const scope = resolveScope(integration, entity, opts);\n  return tracing.withSpan(\"sync.record\", async (span: any) => {\n    span.setAttributes(scopeAttributes(scope, externalId));\n    const row = await getRecord(useDatabase(), scope, externalId);\n    if (!row) {\n      return null;\n    }\n    const { lastSeenReconcileId: _internal, ...record } = row;\n    return record;\n  });\n}\n\n/**\n * Write a vendor record the caller fetched itself — a webhook processor, an operator flow — into\n * the sync record store, keyed exactly as the walk keys it (the module's `key(item)` value as\n * `externalId`). The store's change guard applies: an identical payload only stamps\n * `last_seen_at`, and a payload older (by `sourceUpdatedMs`) than the stored one is dropped, so\n * a late webhook never overwrites a newer version and the next incremental walk that re-fetches\n * the same record sees a no-op.\n *\n * With the default `state: \"pending\"` the next tick's apply phase projects the row through the\n * entity's `upsert`, and until then it shows in the entity's `pendingCount`. A handler that\n * projects inline (with `syncUpsert`) passes `state: \"applied\"`: the row is marked applied when\n * this ingest changed it, or when it was pending for exactly this payload (the probe-then-project\n * pattern below). A row that holds a newer version, or that an operator skipped, is left alone, so\n * a stale or repeated delivery never un-does anything.\n *\n * Recommended shape for a webhook processor — ask the store first, project only what is news:\n *\n * @example\n * const item = { externalId: invoice.InvoiceID, payload: invoice, sourceUpdatedMs: Date.parse(invoice.UpdatedDateUTC) };\n * const probe = await syncIngest(xero, \"invoices\", item);\n * if (probe.changed) {\n *   await syncUpsert(models.xeroInvoice, \"invoiceId\", project(invoice));\n *   await syncIngest(xero, \"invoices\", item, { state: \"applied\" });\n * }\n */\nexport function syncIngest<M extends SyncModuleRef>(\n  module: M,\n  entity: SyncEntityOf<M>,\n  item: IngestItem,\n  opts?: SyncIngestOptions\n): Promise<SyncIngestResult>;\nexport function syncIngest(\n  integration: string,\n  entity: string,\n  item: IngestItem,\n  opts?: SyncIngestOptions\n): Promise<SyncIngestResult>;\nexport async function syncIngest(\n  integration: string | SyncModuleRef,\n  entity: string,\n  item: IngestItem,\n  opts: SyncIngestOptions = {}\n): Promise<SyncIngestResult> {\n  if (!item.externalId) {\n    throw new Error(\"syncIngest: externalId is required\");\n  }\n  const scope = resolveScope(integration, entity, opts);\n  const source = opts.source ?? \"webhook\";\n  const targetState = opts.state ?? \"pending\";\n\n  return tracing.withSpan(\"sync.ingest\", async (span: any) => {\n    span.setAttributes({\n      ...scopeAttributes(scope, item.externalId),\n      [tracing.ATTRS.SYNC_PHASE]: \"ingest\",\n    });\n\n    const result = await withSyncTransaction(async () => {\n      const db = useDatabase();\n      const row = await ingestRecord(db, scope, item, {\n        source,\n        runId: opts.runId ?? null,\n      });\n      // The caller projected this payload. That settles the row when the ingest took it, or when\n      // it was already queued for this very payload (a pending row with the same hash) — never\n      // when the store holds something newer or an operator parked it.\n      const settles =\n        row.changed ||\n        (row.state === \"pending\" &&\n          row.payloadHash === payloadHash(item.payload ?? null));\n      if (targetState === \"applied\" && settles) {\n        const marked = await markApplied(db, scope, item.externalId, row.seq);\n        if (marked) {\n          return { ...row, state: \"applied\" as RecordState };\n        }\n      }\n      return row;\n    });\n\n    span.setAttribute(\n      tracing.ATTRS.OUTCOME,\n      result.changed ? \"changed\" : \"unchanged\"\n    );\n    telemetry.recordIngested(\n      { integrationName: scope.integrationName, entity, scope: scope.scope },\n      {\n        externalId: item.externalId,\n        changed: result.changed,\n        state: result.state,\n      }\n    );\n\n    return {\n      changed: result.changed,\n      state: result.state,\n      seq: result.seq,\n      revision: result.revision,\n    };\n  });\n}\n\nfunction resolveScope(\n  integration: string | SyncModuleRef,\n  entity: string,\n  opts: SyncRecordOptions\n): RecordScope {\n  return {\n    integrationName:\n      typeof integration === \"string\" ? integration : integration.name,\n    entity,\n    scope: opts.scope ?? \"\",\n    connectionId: opts.connectionId ?? \"\",\n  };\n}\n\nfunction scopeAttributes(\n  scope: RecordScope,\n  externalId: string\n): Record<string, string> {\n  return {\n    [tracing.ATTRS.SYNC_INTEGRATION]: scope.integrationName,\n    [tracing.ATTRS.SYNC_ENTITY]: scope.entity,\n    [tracing.ATTRS.SYNC_SCOPE]: scope.scope,\n    [tracing.ATTRS.SYNC_RECORD_EXTERNAL_ID]: externalId,\n  };\n}\n","import { useDatabase } from \"../database\";\nimport {\n  listControls,\n  markEntityRan,\n  markEntityReconciled,\n  setCursorError,\n  upsertCursor,\n  SyncControlRow,\n} from \"./store\";\nimport { walkEntity } from \"./walk\";\nimport { applyPending, applyBatchSize, applyBatchesPerRun } from \"./apply\";\nimport { pruneRecords } from \"./records\";\n\n// The sync engine's public surface. An integration declares WHAT to sync in its manifest\n// (sync.entities → the generated syncEntities catalog) and HOW in lib/sync.config.ts\n// (defineSync per entity); the synthesized tick flow calls runSync with both. Everything else —\n// cursor discipline, resumable walks, watermarks, control-plane gating, continuation across\n// runs — is the engine's job.\n\nexport { syncUpsert, type SyncUpsertModel } from \"./upsert\";\nexport {\n  syncRecord,\n  syncIngest,\n  type SyncRecord,\n  type SyncRecordOptions,\n  type SyncIngestOptions,\n  type SyncIngestResult,\n  type SyncModuleRef,\n} from \"./recordApi\";\nexport type { RecordState, RecordSource, IngestItem } from \"./records\";\n\nexport type SyncStrategy =\n  | \"cursor\"\n  | \"page\"\n  | \"sinceId\"\n  | \"updatedSortStop\"\n  | \"pageJump\"\n  | \"dateWindow\";\n\n// IntegrationServer is the credential-injecting proxy an integration's client calls, as returned\n// by ctx.module(name).server. The engine binds it (from the tick flow's ctx) and hands it to each\n// list call, so the author's page-fetch reaches the vendor through the proxy without needing the\n// flow ctx itself.\nexport type IntegrationServer = {\n  do(request: {\n    method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n    path: string;\n    query?: Record<string, string | string[]>;\n    headers?: Record<string, string>;\n    body?: unknown;\n  }): Promise<{\n    status: number;\n    headers: Record<string, string[]>;\n    body: unknown;\n  }>;\n};\n\n// ListArgs is what the engine hands the author's page-fetch. Which fields are set depends on\n// the entity's strategy; the author maps them onto the vendor API's own parameters.\nexport type ListArgs = {\n  scope: string;\n  pageSize: number;\n  // \"reconcile\" asks for the vendor's complete current record set (no watermark, no window):\n  // the engine tombstones whatever it does not see. Defaults to \"incremental\".\n  mode?: \"incremental\" | \"reconcile\";\n  // The credential-injecting proxy for this integration — build the vendor client from it.\n  server: IntegrationServer;\n  // Strategy-managed position within the current walk (opaque token or page number).\n  position?: string | number | null;\n  // page / updatedSortStop / pageJump: the 1-based page to fetch.\n  page?: number;\n  // The promoted watermark (max vendor updatedAt/id from the last drained walk), already moved\n  // back by the overlap pad for time-based strategies — use it to narrow incremental requests\n  // (e.g. created[gte], since_id). Time-based watermarks are epoch milliseconds.\n  watermark?: string | number | null;\n  // The overlap pad (ms) applied to `watermark` / `window.from`, for authors who want to know.\n  overlap?: number;\n  // dateWindow: fetch changes from this vendor-frame instant onwards (includes overlap pad).\n  window?: { from: string | null };\n};\n\nexport type SyncPage<W> = {\n  items: W[];\n  // The next opaque position for cursor-style strategies; null/undefined means drained.\n  nextPosition?: string | number | null;\n  // Explicit more-pages signal; for page-number strategies a short page also means drained.\n  hasMore?: boolean;\n};\n\n// ReconcileArgs is what the engine hands an optional `reconcile` implementation: a paged\n// request for the vendor's own deleted-items feed, as an alternative to a full re-walk.\nexport type ReconcileArgs = {\n  scope: string;\n  pageSize: number;\n  server: IntegrationServer;\n  position?: string | number | null;\n};\n\nexport type ReconcilePage = {\n  // External ids (as returned by `key`) the vendor reports as deleted.\n  deletedKeys: string[];\n  nextPosition?: string | number | null;\n  hasMore?: boolean;\n};\n\nexport type SyncDefinition<W> = {\n  // Fetch one page from the vendor. Runs inside a durable step; throwing fails the page (and\n  // is retried by the step machinery), never silently skips it.\n  list: (args: ListArgs) => Promise<SyncPage<W>>;\n  // The vendor's stable identifier for an item. Every fetched record is stored in the engine's\n  // record store under this key before it is projected, so it must be stable across fetches\n  // and unique within the entity (and scope). Required: without it the engine cannot dedupe,\n  // detect changes or retry a record.\n  key: (item: W) => string;\n  // Projector: write one vendor record into the project's models. Called by the apply phase\n  // once per changed record, inside a transaction the engine owns; throwing rolls that\n  // transaction back and marks the record for retry. Use syncUpsert for an atomic write keyed\n  // on the vendor id — share it with the webhook processor.\n  upsert: (item: W) => Promise<unknown>;\n  // Projector for a deleted record: `last` is the last payload the engine holds for the key\n  // (null if it was shed). Without it, deletes are recorded as skipped rather than applied.\n  remove?: (key: string, last: W | null) => Promise<unknown>;\n  // Optional vendor deleted-items feed for reconcile. When absent, reconcile detects deletes by\n  // absence: a full walk tombstones every record it did not see.\n  reconcile?: (args: ReconcileArgs) => Promise<ReconcilePage>;\n  // The vendor-frame timestamp used for watermarks (cursor / updatedSortStop / dateWindow) and\n  // for the record store's \"older payload never overwrites newer\" guard.\n  getUpdatedAt?: (item: W) => Date | string | number | null | undefined;\n  // The vendor-frame id used for sinceId watermarks.\n  getId?: (item: W) => string | number;\n  // Multi-tenant scopes (e.g. store handles). Each scope gets its own cursor row. Defaults to\n  // a single unscoped walk.\n  scopes?: () => Promise<string[]>;\n  pageSize?: number;\n  // How far behind the promoted watermark each incremental walk re-scans, absorbing vendor\n  // search-index lag and equal-timestamp boundaries (the record store's hash makes the\n  // re-fetch free). Defaults to 5 minutes; dateWindow defaults to one hour.\n  overlapMs?: number;\n  // sinceId: how many of the most recent ids to re-fetch past the watermark. Defaults to 0.\n  overlapCount?: number;\n};\n\n// defineSync is an identity function that pins the definition's type — the value it returns is\n// what lib/sync.config.ts exports under the entity's name.\nexport function defineSync<W>(\n  definition: SyncDefinition<W>\n): SyncDefinition<W> {\n  return definition;\n}\n\nexport type SyncEntityDeclaration = {\n  readonly name: string;\n  readonly cadence: string;\n  readonly strategy: string;\n};\n\n// Continuation state / manual-trigger inputs for the tick flow. A scheduled tick starts with no\n// inputs; a continuation carries the remaining work list (each item's position is already\n// durable in keel.sync_cursor, so the work list is all the state a successor needs); a manual\n// trigger (Console \"Sync now\") passes force and optionally a subset of entities.\ntype TickInputs = {\n  work?: WorkItem[];\n  force?: boolean;\n  entities?: string[];\n  // Run a reconcile pass now (Console \"Reconcile now\"), regardless of the reconcile cadence.\n  reconcile?: boolean;\n};\n\ntype WorkItem = {\n  entity: string;\n  scope: string;\n  strategy: SyncStrategy;\n  maxRows: number | null;\n  // \"reconcile\" is a full walk that detects deletes by absence (or via the definition's\n  // reconcile feed); it never promotes the incremental watermark.\n  mode?: \"incremental\" | \"reconcile\";\n  // Where a continuation resumes this item: \"ingest\" (default) re-enters the walk from its\n  // durable cursor; \"apply\" skips straight to projecting the pending records.\n  phase?: \"ingest\" | \"apply\";\n};\n\n// PAGES_PER_RUN bounds one run's total page fetches; a bigger backlog continues into a fresh\n// run (fresh step budget, fresh replay baseline) via ctx.continue. Env-overridable so tests can\n// exercise the pause/continue path with small fixtures.\nfunction pagesPerRun(): number {\n  const fromEnv = parseInt(process.env.KEEL_SYNC_PAGES_PER_RUN ?? \"\", 10);\n  return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 40;\n}\n\n// DEFAULT_CADENCE_MS applies when an entity declares no cadence and the operator sets no\n// override.\nconst DEFAULT_CADENCE_MS = 15 * 60 * 1000;\n\n// Retention for the record store, swept by the prune step at the end of every tick (one bounded\n// pass per entity/scope the tick worked).\n//\n// KEEL_SYNC_TOMBSTONE_RETENTION_DAYS (default 30): applied or skipped tombstones older than this\n// are deleted outright.\n//\n// KEEL_SYNC_PAYLOAD_RETENTION_DAYS (unset = keep payloads forever): the payload of applied rows\n// older than this is set to NULL while the row and its payload_hash stay, so an identical\n// re-fetch is still a no-op. This trades storage for the store being the raw-payload source:\n// a shed row reads as `payloadShed: true` with `payload: null` from syncRecord and from the\n// records endpoint, cannot be reapplied from the Console, and hands `remove(key, null)` to the\n// projector. Modules that rely on the record store instead of a `raw` column (and consumers who\n// read payloads through syncRecord) should leave it unset, or accept a vendor refetch for old\n// records.\nfunction tombstoneRetentionDays(): number {\n  const fromEnv = parseInt(\n    process.env.KEEL_SYNC_TOMBSTONE_RETENTION_DAYS ?? \"\",\n    10\n  );\n  return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv : 30;\n}\n\nfunction payloadRetentionDays(): number | undefined {\n  const fromEnv = parseInt(\n    process.env.KEEL_SYNC_PAYLOAD_RETENTION_DAYS ?? \"\",\n    10\n  );\n  return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv : undefined;\n}\n\n// runSync builds the synthesized tick flow's implementation. `integrationName` and `entities`\n// come from the generated _module.gen.ts; `syncs` is the author's lib/sync.config.ts export.\n// SyncEngineHooks are fault-injection seams for the engine's own test suite: each fires inside\n// the transaction it names, so a hook that throws stands in for a crash at that exact point.\n// Not part of the public API; generated code never passes them.\nexport type SyncEngineHooks = {\n  // Inside the page transaction, after the records were ingested and before the cursor is\n  // written.\n  beforeCursorWrite?: (info: {\n    entity: string;\n    scope: string;\n    page: number;\n  }) => Promise<void> | void;\n  // Inside a record's apply transaction, after the projector ran and before the record is\n  // marked applied.\n  beforeMarkApplied?: (info: {\n    entity: string;\n    scope: string;\n    externalId: string;\n  }) => Promise<void> | void;\n};\n\nexport type SyncEngineInternals = {\n  hooks?: SyncEngineHooks;\n};\n\n// RateLimitConfig is the manifest's connection.rate_limit block, handed to the engine by the\n// generated tick flow. The proxy records the vendor's remaining budget on the connection every\n// time it sees the named header; the engine pauses its walks while a fresh observation sits\n// below the reserve, leaving that reserve for operator flows and webhooks (never blocked).\nexport type RateLimitConfig = {\n  remainingHeader: string;\n  reserve: number;\n  window: \"daily\" | \"hourly\" | \"minute\";\n};\n\nexport type SyncEngineOptions = SyncEngineInternals & {\n  rateLimit?: RateLimitConfig;\n};\n\nexport function runSync(\n  integrationName: string,\n  entities: ReadonlyArray<SyncEntityDeclaration>,\n  syncs: Record<string, SyncDefinition<any>>,\n  options?: SyncEngineOptions\n) {\n  return async (ctx: any, inputs: TickInputs | undefined) => {\n    const db = useDatabase();\n\n    // The engine binds the integration's proxy from the tick flow's ctx and hands it to each\n    // list call, so an entity's page-fetch reaches the vendor through the credential proxy.\n    const server: IntegrationServer = ctx.module(integrationName).server;\n\n    // Plan: decide the work list — either the continuation's remaining work, or a fresh plan\n    // from the control plane (enabled + cadence-due + in-hours entities, expanded per scope).\n    const work: WorkItem[] =\n      inputs?.work ??\n      (\n        (await ctx.step(\"plan\", async () => {\n          const controls = await listControls(db, integrationName);\n          const byEntity = new Map(controls.map((c) => [c.entity, c]));\n          const now: Date = ctx.now();\n\n          const planned: WorkItem[] = [];\n          const skipped: string[] = [];\n\n          for (const declared of entities) {\n            if (inputs?.entities && !inputs.entities.includes(declared.name)) {\n              continue;\n            }\n\n            const control = byEntity.get(declared.name);\n            const incrementalDue =\n              Boolean(inputs?.force) || isDue(declared, control, now);\n            const reconcileDue =\n              (Boolean(inputs?.reconcile) && Boolean(control?.enabled)) ||\n              isReconcileDue(control, now);\n            if (!incrementalDue && !reconcileDue) {\n              skipped.push(declared.name);\n              continue;\n            }\n\n            const definition = syncs[declared.name];\n            if (!definition) {\n              // A declared entity with no implementation: record it visibly on its cursor row\n              // and keep going — the other entities must not be held hostage.\n              await upsertCursor(db, {\n                integrationName,\n                entity: declared.name,\n                scope: \"\",\n                cursor: {},\n                lastError: `no implementation for sync entity \"${declared.name}\" in lib/sync.config.ts`,\n              });\n              continue;\n            }\n            if (typeof definition.key !== \"function\") {\n              // The type requires key, but a JS author (or an older config) can omit it. Without\n              // it nothing can be stored, so record the problem where the Console shows it.\n              await upsertCursor(db, {\n                integrationName,\n                entity: declared.name,\n                scope: \"\",\n                cursor: {},\n                lastError: `sync entity \"${declared.name}\" has no key(item) in lib/sync.config.ts; it is required to store and dedupe records`,\n              });\n              continue;\n            }\n\n            const scopes = definition.scopes ? await definition.scopes() : [\"\"];\n            for (const scope of scopes) {\n              const base = {\n                entity: declared.name,\n                scope,\n                strategy: declared.strategy as SyncStrategy,\n                maxRows: control?.maxRowsPerRun ?? null,\n              };\n              if (incrementalDue) {\n                planned.push({ ...base, mode: \"incremental\" });\n              }\n              if (reconcileDue) {\n                planned.push({ ...base, mode: \"reconcile\" });\n              }\n            }\n          }\n\n          return { planned, skipped };\n        })) ?? { planned: [], skipped: [] }\n      ).planned;\n\n    if (work.length === 0) {\n      return ctx.complete({\n        title: `Sync ${integrationName}`,\n        description: \"Nothing due this tick.\",\n      });\n    }\n\n    // Work the list sequentially under two shared budgets: pages for the ingest walks and\n    // batches for the apply phase. Position state lives in keel.sync_cursor and\n    // keel.sync_record (persisted every step), so pausing at any point loses nothing.\n    let pagesUsed = 0;\n    let batchesUsed = 0;\n    const summaries: string[] = [];\n\n    for (let i = 0; i < work.length; i++) {\n      const item = work[i];\n      const definition = syncs[item.entity];\n      if (!definition || typeof definition.key !== \"function\") {\n        continue;\n      }\n      const recordScope = {\n        integrationName,\n        entity: item.entity,\n        scope: item.scope,\n      };\n\n      const reconcile = item.mode === \"reconcile\";\n\n      // Ingest: walk the vendor, writing every page to the record store.\n      let ingest: {\n        status: \"drained\" | \"paused\";\n        rows: number;\n        changed: number;\n        tombstoned: number;\n        warning: string | null;\n        budgetLow: boolean;\n      } = {\n        status: \"drained\",\n        rows: 0,\n        changed: 0,\n        tombstoned: 0,\n        warning: null,\n        budgetLow: false,\n      };\n      let rowCapped = false;\n      if (item.phase !== \"apply\") {\n        const outcome = await walkEntity({\n          db,\n          integrationName,\n          entity: item.entity,\n          scope: item.scope,\n          strategy: item.strategy,\n          definition,\n          server,\n          mode: reconcile ? \"reconcile\" : \"incremental\",\n          budget: { pages: pagesPerRun() - pagesUsed, rows: item.maxRows },\n          step: (name, fn) => ctx.step(name, fn),\n          overlapMs: definition.overlapMs,\n          overlapCount: definition.overlapCount,\n          hooks: options?.hooks,\n          rateLimit: options?.rateLimit,\n        });\n        pagesUsed += outcome.pages;\n        ingest = outcome;\n        rowCapped =\n          outcome.status === \"paused\" &&\n          item.maxRows !== null &&\n          outcome.rows >= item.maxRows;\n      }\n\n      // Apply: project what is pending for this entity/scope, whether the walk drained or\n      // paused — a large backfill is projected as it arrives, not only after the last page.\n      const apply = await applyPending({\n        db,\n        scope: recordScope,\n        label: label(item),\n        strategy: item.strategy,\n        mode: reconcile ? \"reconcile\" : \"incremental\",\n        definition,\n        budget: {\n          batches: applyBatchesPerRun() - batchesUsed,\n          batchSize: applyBatchSize(),\n        },\n        step: (name, fn) => ctx.step(name, fn),\n        hooks: options?.hooks,\n      });\n      batchesUsed += apply.batches;\n\n      const errored = apply.failed + apply.retrying;\n      summaries.push(\n        `${label(item)}: ${ingest.rows} fetched, ${ingest.changed} changed, ` +\n          (reconcile ? `${ingest.tombstoned} tombstoned, ` : \"\") +\n          `${apply.applied} applied` +\n          (errored > 0\n            ? ` (${errored} errored: ${apply.errorSamples[0] ?? \"see records\"})`\n            : \"\") +\n          (apply.skipped > 0 ? ` (${apply.skipped} skipped)` : \"\") +\n          (ingest.budgetLow ? \" (rate budget low)\" : \"\")\n      );\n\n      if (ingest.status === \"paused\" && !rowCapped && !ingest.budgetLow) {\n        // Out of page budget with pages remaining: continue into a fresh run carrying the rest\n        // of the work list, this item included — it resumes its walk from the durable cursor.\n        await ctx.continue({ work: work.slice(i) });\n      }\n\n      if (apply.status === \"paused\") {\n        // Out of apply budget with records still pending: continue straight into applying.\n        await ctx.continue({\n          work: [{ ...item, phase: \"apply\" }, ...work.slice(i + 1)],\n        });\n      }\n\n      if (ingest.status === \"drained\") {\n        await ctx.step(`${label(item)}: mark ran`, async () => {\n          if (reconcile) {\n            await markEntityReconciled(\n              db,\n              integrationName,\n              item.entity,\n              ctx.now()\n            );\n          } else {\n            await markEntityRan(db, integrationName, item.entity, ctx.now());\n          }\n          // Both phases completed: the cursor's visible error reflects this pass. A clean\n          // pass clears whatever an earlier failure left; projector errors stay visible with\n          // their first message until a later pass applies cleanly.\n          await setCursorError(\n            db,\n            recordScope,\n            errored > 0\n              ? `${errored} record${errored === 1 ? \"\" : \"s\"} failed to apply: ${apply.errorSamples[0] ?? \"see records\"}`\n              : ingest.warning\n          );\n        });\n      }\n      // A row-capped walk — or one paused on a low vendor rate-limit budget — waits for the\n      // next tick rather than continuing now; continuing would only burn the reserve.\n    }\n\n    // Retention: one bounded prune per entity/scope worked this tick. Never touches pending or\n    // failed rows, so nothing that still has to be applied or retried is lost.\n    await ctx.step(\"prune\", async () => {\n      const seen = new Set<string>();\n      let tombstonesDeleted = 0;\n      let payloadsShed = 0;\n      for (const item of work) {\n        const key = `${item.entity}\\u0000${item.scope}`;\n        if (seen.has(key)) {\n          continue;\n        }\n        seen.add(key);\n        const pruned = await pruneRecords(\n          db,\n          { integrationName, entity: item.entity, scope: item.scope },\n          {\n            tombstoneRetentionDays: tombstoneRetentionDays(),\n            payloadRetentionDays: payloadRetentionDays(),\n          }\n        );\n        tombstonesDeleted += pruned.tombstonesDeleted;\n        payloadsShed += pruned.payloadsShed;\n      }\n      return { tombstonesDeleted, payloadsShed };\n    });\n\n    return ctx.complete({\n      title: `Sync ${integrationName}`,\n      description:\n        summaries.length > 0 ? summaries.join(\". \") : \"Nothing to do.\",\n    });\n  };\n}\n\n// label names a work item in step names and summaries. Incremental and reconcile items for the\n// same entity run in the same tick, so the mode is part of the name (step names must be unique\n// within a run).\n//\n// These names are a contract: the Go sync runs endpoint parses them back into per-entity\n// summaries, so changing this (or walk.ts's \"begin\"/\"page N\", apply.ts's \"apply batch N\") means\n// changing runtime/apis/integrationsapi/sync_runs_handler.go — see TestSyncRunStepNameTemplates.\nfunction label(item: WorkItem): string {\n  const base = item.scope ? `${item.entity}/${item.scope}` : item.entity;\n  return item.mode === \"reconcile\" ? `${base} (reconcile)` : base;\n}\n\n// isReconcileDue: the entity is enabled, has a reconcile cadence, and that interval has elapsed\n// since the last completed reconcile (a never-reconciled entity with a cadence is due).\nfunction isReconcileDue(\n  control: SyncControlRow | undefined,\n  now: Date\n): boolean {\n  if (!control?.enabled || !control.reconcileCadence) {\n    return false;\n  }\n  if (!control.lastReconcileAt) {\n    return true;\n  }\n  return (\n    now.getTime() - control.lastReconcileAt.getTime() >=\n    parseCadenceMs(control.reconcileCadence)\n  );\n}\n\n// isDue applies the control-plane gates: enabled (default OFF — a fresh install is dormant),\n// active hours (wraparound windows supported), and cadence (interval semantics: due when\n// last_run_at is at least the cadence interval ago; a never-run entity is always due).\nfunction isDue(\n  declared: SyncEntityDeclaration,\n  control: SyncControlRow | undefined,\n  now: Date\n): boolean {\n  if (!control?.enabled) {\n    return false;\n  }\n\n  if (control.activeFromHour != null && control.activeToHour != null) {\n    const hour = now.getUTCHours();\n    const from = control.activeFromHour;\n    const to = control.activeToHour;\n    const inWindow =\n      from <= to ? hour >= from && hour < to : hour >= from || hour < to;\n    if (!inWindow) {\n      return false;\n    }\n  }\n\n  if (!control.lastRunAt) {\n    return true;\n  }\n\n  const cadenceMs = parseCadenceMs(control.cadenceOverride || declared.cadence);\n  return now.getTime() - control.lastRunAt.getTime() >= cadenceMs;\n}\n\n// parseCadenceMs reduces a cadence expression to a minimum interval between drained runs. Sync\n// reconciliation wants interval semantics, not exact-time semantics, so the common natural and\n// cron forms map onto intervals; anything unrecognised falls back to the default with a warning\n// rather than failing the tick.\nexport function parseCadenceMs(cadence: string | null | undefined): number {\n  if (!cadence) {\n    return DEFAULT_CADENCE_MS;\n  }\n\n  const natural = cadence.match(/^every\\s+(\\d+)?\\s*(minute|hour|day)s?$/i);\n  if (natural) {\n    const n = natural[1] ? parseInt(natural[1], 10) : 1;\n    const unit = natural[2].toLowerCase();\n    const ms =\n      unit === \"minute\" ? 60_000 : unit === \"hour\" ? 3_600_000 : 86_400_000;\n    return n * ms;\n  }\n\n  const minuteStep = cadence.match(/^\\*\\/(\\d+)(\\s+\\*){4}$/);\n  if (minuteStep) {\n    return parseInt(minuteStep[1], 10) * 60_000;\n  }\n\n  const hourStep = cadence.match(/^\\d+\\s+\\*\\/(\\d+)(\\s+\\*){3}$/);\n  if (hourStep) {\n    return parseInt(hourStep[1], 10) * 3_600_000;\n  }\n\n  const daily = cadence.match(/^\\d+\\s+\\d+(\\s+\\*){3}$/);\n  if (daily) {\n    return 86_400_000;\n  }\n\n  console.warn(\n    `sync: unrecognised cadence ${JSON.stringify(cadence)} — using the default interval`\n  );\n  return DEFAULT_CADENCE_MS;\n}\n","// Experimental agent + LLM primitives.\n//\n// Everything re-exported here is pre-release: the API surface is not yet stable\n// and may change without a major version bump. Consume it via the `experimental`\n// namespace so the instability is explicit at every call site:\n//\n//   import { experimental, models, z } from \"@teamkeel/sdk\";\n//   const tool = experimental.ai.defineTool({ ... });\n//   const result = await experimental.ai.generate(ctx, \"classify\", { ... });\n//\n// `ai` holds what flow authors call; `testing` holds test doubles.\n\nimport * as ai from \"./ai\";\nimport * as testing from \"./testing\";\nimport { AiSdkEngine as _AiSdkEngine } from \"../agents/aiSdkEngine\";\n\nexport { ai, testing };\n\n// ---- deprecated top-level names ---------------------------------------------\n// The flat names from before `ai` / `testing` existed. Kept for one release so\n// existing flows keep compiling; remove after that.\n\n/** @deprecated Use `experimental.ai.generate`. */\nexport const LlmFlowStep = ai.generate;\n/** @deprecated Use `experimental.ai.GenerateOptions`. */\nexport type LlmOptions<R> = ai.GenerateOptions<R>;\n/** @deprecated Use `experimental.ai.defineAgent`. */\nexport const defineAgent = ai.defineAgent;\n/** @deprecated Use `experimental.ai.Agent`. */\nexport type Agent<I = any, R = any> = ai.Agent<I, R>;\n/** @deprecated Use `experimental.ai.AgentConfig`. */\nexport type AgentConfig<I = any, R = any> = ai.AgentConfig<I, R>;\n/** @deprecated Use `experimental.ai.defineTool`. */\nexport const defineTool = ai.defineTool;\n/** @deprecated Use `experimental.ai.ToolDefinition`. */\nexport type ToolDefinition<P = any> = ai.ToolDefinition<P>;\n/** @deprecated Use `experimental.ai.TurnEngine`. */\nexport type TurnEngine = ai.TurnEngine;\n/** @deprecated Use `experimental.ai.TurnRequest`. */\nexport type TurnRequest = ai.TurnRequest;\n/** @deprecated Use `experimental.ai.TurnResult`. */\nexport type TurnResult = ai.TurnResult;\n/** @deprecated Use `experimental.ai.AgentMessage`. */\nexport type AgentMessage = ai.AgentMessage;\n/** @deprecated Use `experimental.testing.ScriptedEngine`. */\nexport const ScriptedEngine = testing.ScriptedEngine;\n/** @deprecated Use `experimental.testing.ScriptedEngine`. */\nexport type ScriptedEngine = testing.ScriptedEngine;\n/** @deprecated Use `experimental.testing.scriptedTurn`. */\nexport const scriptedTurn = testing.scriptedTurn;\n/** @deprecated The engine is chosen by the runtime; flows don't construct it. */\nexport const AiSdkEngine = _AiSdkEngine;\n/** @deprecated The engine is chosen by the runtime; flows don't construct it. */\nexport type AiSdkEngine = _AiSdkEngine;\n","// AI primitives for flows: LLM, decision and extraction steps, and agents. Consumed as\n// `experimental.ai` (see ../experimental/index.ts).\n\nexport { generate } from \"../agents/llm\";\nexport type { GenerateOptions } from \"../agents/llm\";\nexport { decide } from \"../agents/decide\";\nexport type { DecideOptions, DecideAnswers } from \"../agents/decide\";\nexport type {\n  DecideValue,\n  DecideQuestion,\n  BooleanQuestion,\n  ChoiceQuestion,\n  ScoreQuestion,\n  DecideAnswer,\n  BooleanAnswer,\n  ChoiceAnswer,\n  ScoreAnswer,\n  DecisionEngine,\n  DecideRequest,\n  DecideResult,\n} from \"../agents/decision\";\nexport { extract } from \"../agents/extract\";\nexport type { ExtractOptions, ExtractAnswers } from \"../agents/extract\";\nexport type {\n  ExtractField,\n  TextField,\n  NumberField,\n  DateField,\n  DurationField,\n  ListField,\n  EstimateField,\n  ExtractAnswer,\n  ExtractAnswerFor,\n  TextAnswer,\n  NumberAnswer,\n  DateAnswer,\n  DurationAnswer,\n  ListAnswer,\n  EstimateAnswer,\n  ExtractionEngine,\n  ExtractRequest,\n  ExtractResult,\n  ExtractImage,\n} from \"../agents/extraction\";\nexport { defineAgent } from \"../agents/defineAgent\";\nexport type { Agent, AgentConfig } from \"../agents/defineAgent\";\nexport { defineTool } from \"../agents/defineTool\";\nexport type { ToolDefinition } from \"../agents/defineTool\";\nexport type {\n  TurnEngine,\n  TurnRequest,\n  TurnResult,\n  AgentMessage,\n} from \"../agents/engine\";\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport type ResultSchema<T = unknown> = StandardSchemaV1<unknown, T>;\n\n/**\n * Deterministic JSON serialization: object keys are sorted at every depth.\n * Used wherever step values become prompt bytes, so first execution and replay\n * produce identical strings regardless of JSONB key normalization.\n * Arrays preserve their original order; primitives use JSON.stringify.\n * Matches JSON.stringify semantics: object properties with undefined values are omitted,\n * array elements that are undefined become null.\n */\nexport function canonicalStringify(value: unknown): string {\n  if (value === null || typeof value !== \"object\") {\n    return JSON.stringify(value);\n  }\n  if (Array.isArray(value)) {\n    return (\n      \"[\" +\n      value\n        .map((v) => (v === undefined ? \"null\" : canonicalStringify(v)))\n        .join(\",\") +\n      \"]\"\n    );\n  }\n  const sorted = Object.keys(value as object)\n    .sort()\n    .filter((k) => (value as any)[k] !== undefined)\n    .map((k) => JSON.stringify(k) + \":\" + canonicalStringify((value as any)[k]))\n    .join(\",\");\n  return \"{\" + sorted + \"}\";\n}\n\n/**\n * Round-trip through canonicalStringify so in-memory objects have the same key\n * order as their replayed counterparts (which come back from JSONB in sorted\n * key order).\n */\nexport function canonicalize<T>(value: T): T {\n  if (value === undefined) return value;\n  return JSON.parse(canonicalStringify(value));\n}\n\nexport type ValidationOutcome<T> =\n  | { ok: true; value: T }\n  | { ok: false; issues: string };\n\nexport async function validateSchema<T>(\n  schema: StandardSchemaV1<unknown, T>,\n  value: unknown\n): Promise<ValidationOutcome<T>> {\n  let result = schema[\"~standard\"].validate(value);\n  if (result instanceof Promise) result = await result;\n  if (result.issues) {\n    const issues = result.issues\n      .map((i) => {\n        const path = (i.path ?? [])\n          .map((p) =>\n            typeof p === \"object\" && p !== null && \"key\" in p\n              ? String(p.key)\n              : String(p)\n          )\n          .join(\".\");\n        return path ? `${path}: ${i.message}` : i.message;\n      })\n      .join(\"; \");\n    return { ok: false, issues };\n  }\n  return { ok: true, value: result.value };\n}\n\n/** Derive a JSON Schema object from a Standard Schema. v1 supports Zod v4\n * (which ships native z.toJSONSchema). Other vendors throw a helpful error. */\nexport async function toJsonSchema(\n  schema: StandardSchemaV1\n): Promise<Record<string, unknown>> {\n  const vendor = schema[\"~standard\"].vendor;\n  if (vendor === \"zod\") {\n    const zod = await import(\"zod\");\n    const toJSONSchema =\n      (zod as any).toJSONSchema ?? (zod as any).z?.toJSONSchema;\n    if (typeof toJSONSchema !== \"function\") {\n      throw new Error(\n        \"Deriving a JSON schema from a zod schema requires zod v4\"\n      );\n    }\n    return toJSONSchema(schema) as Record<string, unknown>;\n  }\n  throw new Error(\n    `Unsupported schema vendor \"${vendor}\" — agent result/parameter schemas currently support Zod v4`\n  );\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentFile, AgentMessage } from \"./engine\";\nimport { toJsonSchema, validateSchema, canonicalize } from \"./schema\";\nimport { resolveEngineForContext } from \"./engineResolver\";\nimport { NonRetriableError } from \"../flows/errors\";\nimport { FileSizeLimitError, type InlineFile } from \"../File\";\n\nconst MAX_LLM_FILE_BYTES = 10 * 1024 * 1024;\nconst MAX_LLM_FILES_BYTES = 20 * 1024 * 1024;\n\nexport type GenerateOptions<R> = {\n  /** Provider-prefixed model, e.g. \"anthropic/claude-sonnet-4-6\". */\n  model: string;\n  prompt: string;\n  /** Optional system instructions. */\n  system?: string;\n  /** Keel files to include with the prompt. Stored File values and InlineFile values are supported. */\n  files?: readonly InlineFile[];\n  /** Standard Schema for the typed result. Omit for plain text. */\n  result?: StandardSchemaV1<unknown, R>;\n  /** Max wall-clock ms for the step (default 300000). */\n  timeout?: number;\n};\n\n/**\n * Run one typed LLM call as a single checkpointed flow step. No tools, no loop:\n * it's an ordinary step, so the result is cached on replay and retried on\n * transient failure. Pass a `result` schema for structured output (validated\n * with a bounded repair loop) or omit it to get the model's plain text.\n *\n * Takes the flow `ctx` explicitly so it can be called as a free function:\n *\n *   const triage = await experimental.ai.generate(ctx, \"classify\", {\n *     model: \"anthropic/claude-haiku-4-5\",\n *     prompt: `Classify this ticket: ${body}`,\n *     files: [ticket.attachment],\n *     result: z.object({ category: z.enum([\"billing\", \"bug\", \"other\"]) }),\n *   });\n */\nexport async function generate<R>(\n  ctx: any,\n  name: string,\n  options: GenerateOptions<R> & { result: StandardSchemaV1<unknown, R> }\n): Promise<R>;\nexport async function generate(\n  ctx: any,\n  name: string,\n  options: GenerateOptions<never>\n): Promise<string>;\nexport async function generate(\n  ctx: any,\n  name: string,\n  options: GenerateOptions<any>\n): Promise<any> {\n  // Wrap with canonicalize so key order is deterministic on first execution\n  // and replay (JSONB normalises key order; canonicalize sorts keys to match).\n  const stepValue = await ctx.step(\n    name,\n    { retries: 2, timeout: options.timeout ?? 300_000 },\n    async () => {\n      const engine = resolveEngineForContext(ctx);\n      const llmFiles = options.files ?? [];\n      let declaredTotalBytes = 0;\n      for (const file of llmFiles) {\n        if (file.size > MAX_LLM_FILE_BYTES) {\n          throw new NonRetriableError(\n            `generate(\"${name}\"): file \"${file.filename}\" is ${file.size} bytes, exceeding the 10MB limit`\n          );\n        }\n        declaredTotalBytes += Math.max(file.size, 0);\n      }\n      if (declaredTotalBytes > MAX_LLM_FILES_BYTES) {\n        throw new NonRetriableError(\n          `generate(\"${name}\"): attached files total ${declaredTotalBytes} bytes, exceeding the 20MB limit`\n        );\n      }\n\n      const files: AgentFile[] = [];\n      let actualTotalBytes = 0;\n      for (const file of llmFiles) {\n        const remainingBytes = MAX_LLM_FILES_BYTES - actualTotalBytes;\n        const readLimit = Math.min(MAX_LLM_FILE_BYTES, remainingBytes);\n        let contents: Buffer;\n        try {\n          contents = await file.read(readLimit);\n        } catch (error) {\n          if (!(error instanceof FileSizeLimitError)) throw error;\n          if (error.actualBytes > MAX_LLM_FILE_BYTES) {\n            throw new NonRetriableError(\n              `generate(\"${name}\"): file \"${file.filename}\" is ${error.actualBytes} bytes, exceeding the 10MB limit`\n            );\n          }\n          throw new NonRetriableError(\n            `generate(\"${name}\"): attached files exceed the 20MB limit`\n          );\n        }\n        actualTotalBytes += contents.byteLength;\n        files.push({\n          data: contents.toString(\"base64\"),\n          filename: file.filename,\n          mediaType: file.contentType,\n        });\n      }\n      const messages: AgentMessage[] = [\n        {\n          role: \"user\",\n          content: options.prompt,\n          ...(files.length > 0 ? { files } : {}),\n        },\n      ];\n\n      if (!options.result) {\n        const res = await engine.turn({\n          model: options.model,\n          system: options.system,\n          messages,\n          stepName: name,\n        });\n        return res.text;\n      }\n\n      const parameters = await toJsonSchema(options.result);\n\n      for (let attempt = 0; attempt < 3; attempt++) {\n        const res = await engine.turn({\n          model: options.model,\n          system: options.system,\n          messages,\n          tools: [\n            {\n              name: \"complete_task\",\n              description: \"Return the final result of the task.\",\n              parameters,\n            },\n          ],\n          toolChoice: { name: \"complete_task\" },\n          stepName: name,\n        });\n\n        const call = res.toolCalls.find((c) => c.name === \"complete_task\");\n        if (call) {\n          const v = await validateSchema(options.result, call.arguments);\n          if (v.ok) return v.value as any;\n          messages.push(\n            {\n              role: \"assistant\",\n              content: res.text,\n              toolCalls: res.toolCalls,\n            },\n            {\n              role: \"tool\",\n              toolCallId: call.id,\n              toolName: \"complete_task\",\n              result: `Validation failed: ${v.issues}. Call complete_task again with corrected arguments.`,\n            }\n          );\n          continue;\n        }\n        messages.push(\n          { role: \"assistant\", content: res.text },\n          {\n            role: \"user\",\n            content: \"You must call complete_task with the final result.\",\n          }\n        );\n      }\n\n      throw new NonRetriableError(\n        `generate(\"${name}\"): result failed validation after 3 attempts`\n      );\n    }\n  );\n  return canonicalize(stepValue);\n}\n","import type {\n  AnswerFor,\n  DecideAnswer,\n  DecideQuestion,\n  DecideValue,\n} from \"./decision\";\nimport { resolveDecisionEngineForContext } from \"./engineResolver\";\nimport { canonicalize } from \"./schema\";\nimport { NonRetriableError } from \"../flows/errors\";\nimport { RetryBackoffLinear } from \"../flows\";\n\nexport const DEFAULT_DECISION_MODEL = \"typesafe/jev\";\n\nexport type DecideOptions<Q extends Record<string, DecideQuestion>> = {\n  /** Provider-prefixed decision model. Default \"typesafe/jev\". */\n  model?: string;\n  /** What is being decided about: text, or any JSON value. */\n  state: DecideValue;\n  /** Named questions; each name becomes a key on the result. */\n  questions: Q;\n  /** Max wall-clock ms for the step (default 30000). */\n  timeout?: number;\n};\n\nexport type DecideAnswers<Q extends Record<string, DecideQuestion>> = {\n  [K in keyof Q]: AnswerFor<Q[K]>;\n};\n\n/**\n * Ask a decision model typed questions about some state, as a single\n * checkpointed flow step. Each answer carries probabilities instead of free\n * text, so the flow can act on the answer or fall back (for example to a human\n * task) when the model is unsure. The result is cached on replay and the call\n * is retried on transient failure, like any other step.\n *\n *   const triage = await experimental.ai.decide(ctx, \"triage\", {\n *     state: { subject, body },\n *     questions: {\n *       team: {\n *         type: \"choice\",\n *         instructions: \"Which team should handle this?\",\n *         criteria: { billing: \"Invoices and refunds\", support: \"Bugs\" },\n *       },\n *       urgent: { type: \"boolean\", instructions: \"Is this urgent?\" },\n *     },\n *   });\n *   triage.team.choice;        // \"billing\" | \"support\"\n *   triage.urgent.probability; // 0..1\n */\nexport async function decide<const Q extends Record<string, DecideQuestion>>(\n  ctx: any,\n  name: string,\n  options: DecideOptions<Q>\n): Promise<DecideAnswers<Q>> {\n  const stepValue = await ctx.step(\n    name,\n    {\n      retries: 2,\n      // Space retries out so a rate-limited or briefly unavailable model has\n      // time to recover before the next attempt (5s, then 10s).\n      retryPolicy: RetryBackoffLinear(5),\n      timeout: options.timeout ?? 30_000,\n    },\n    async () => {\n      validateQuestions(name, options.questions);\n      const engine = resolveDecisionEngineForContext(ctx);\n      const res = await engine.decide({\n        model: options.model ?? DEFAULT_DECISION_MODEL,\n        state: options.state,\n        questions: options.questions,\n        stepName: name,\n      });\n\n      // Only keep answers to the questions asked, and require every one of\n      // them with the right type: a flow branching on a missing answer would\n      // otherwise fail far from the cause. Retrying would not help: the proxy\n      // answers a retry of the same step with the first attempt's result.\n      const answers: Record<string, unknown> = {};\n      for (const [key, question] of Object.entries(options.questions)) {\n        const answer = res.answers[key];\n        if (!answer || answer.type !== question.type) {\n          throw new NonRetriableError(\n            `decide(\"${name}\"): model returned no ${question.type} answer for \"${key}\"`\n          );\n        }\n        if (!isValidAnswer(question, answer)) {\n          throw new NonRetriableError(\n            `decide(\"${name}\"): model returned an invalid ${question.type} answer for \"${key}\"`\n          );\n        }\n        answers[key] = answer;\n      }\n      return answers;\n    }\n  );\n  // Wrap with canonicalize so key order is deterministic on first execution\n  // and replay (JSONB normalises key order; canonicalize sorts keys to match).\n  return canonicalize(stepValue) as DecideAnswers<Q>;\n}\n\nfunction validateQuestions(\n  name: string,\n  questions: Record<string, DecideQuestion>\n): void {\n  const entries = Object.entries(questions ?? {});\n  if (entries.length === 0) {\n    throw new NonRetriableError(`decide(\"${name}\"): no questions given`);\n  }\n  for (const [key, q] of entries) {\n    if (q.type === \"choice\" && Object.keys(q.criteria ?? {}).length < 2) {\n      throw new NonRetriableError(\n        `decide(\"${name}\"): choice question \"${key}\" needs at least two options`\n      );\n    }\n    if (q.type === \"score\" && (q.criteria?.length ?? 0) < 2) {\n      throw new NonRetriableError(\n        `decide(\"${name}\"): score question \"${key}\" needs at least two levels`\n      );\n    }\n  }\n}\n\n// The answer's value must be usable as its type promises: a probability in\n// [0, 1], one of the declared choices, or a score within the rubric.\nfunction isValidAnswer(\n  question: DecideQuestion,\n  answer: DecideAnswer\n): boolean {\n  const inRange = (n: unknown, max: number) =>\n    typeof n === \"number\" && Number.isFinite(n) && n >= 0 && n <= max;\n  if (question.type === \"boolean\" && answer.type === \"boolean\") {\n    return inRange(answer.probability, 1);\n  }\n  if (question.type === \"choice\" && answer.type === \"choice\") {\n    return (\n      typeof answer.choice === \"string\" &&\n      Object.prototype.hasOwnProperty.call(question.criteria, answer.choice)\n    );\n  }\n  if (question.type === \"score\" && answer.type === \"score\") {\n    return inRange(answer.score, question.criteria.length - 1);\n  }\n  return false;\n}\n","import type {\n  EstimateAnswer,\n  ExtractAnswer,\n  ExtractAnswerFor,\n  ExtractField,\n  ExtractImage,\n  ExtractState,\n} from \"./extraction\";\nimport { resolveExtractionEngineForContext } from \"./engineResolver\";\nimport { canonicalize } from \"./schema\";\nimport { NonRetriableError } from \"../flows/errors\";\nimport { RetryBackoffLinear } from \"../flows\";\nimport { FileSizeLimitError, type InlineFile } from \"../File\";\nimport { log } from \"../logger\";\nimport { ATTRS } from \"../attrs\";\n\nexport const DEFAULT_EXTRACTION_MODEL = \"cloudflare/clairic\";\n\n// Limits of the extraction API, checked here so a bad request fails the step\n// with a clear message instead of an HTTP 400 after a network round trip.\nconst MAX_IMAGES = 4;\nconst MAX_IMAGE_BYTES = 4 * 1024 * 1024;\nconst MAX_TOTAL_IMAGE_BYTES = 8 * 1024 * 1024;\nconst IMAGE_TYPES = new Set([\"image/png\", \"image/jpeg\", \"image/webp\"]);\nconst FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_.\\-]{0,63}$/;\n\nexport type ExtractOptions<F extends Record<string, ExtractField>> = {\n  /** Provider-prefixed extraction model. Default \"cloudflare/clairic\". */\n  model?: string;\n  /** What to read: text, or any JSON value (serialised before it is sent).\n   * Answer spans are only returned for text state. */\n  state: ExtractState;\n  /** Up to four PNG, JPEG or WebP images read alongside the state: Keel files\n   * or `data:` URLs. */\n  images?: (InlineFile | string)[];\n  /** Named fields; each name becomes a key on the result. */\n  fields: F;\n  /** ISO date that anchors dates written without a year, e.g. the date the\n   * email was received. */\n  referenceDate?: string;\n  /** Max wall-clock ms for the step (default 30000). */\n  timeout?: number;\n};\n\nexport type ExtractAnswers<F extends Record<string, ExtractField>> = {\n  [K in keyof F]: ExtractAnswerFor<F[K]>;\n};\n\n/**\n * Read typed values out of unstructured text and images with an extraction\n * model, as a single checkpointed flow step. Every value comes back with a\n * confidence and is null when the input does not contain it, so the flow can\n * act on what it is sure of and send the rest to a person. The result is\n * cached on replay and the call is retried on transient failure, like any\n * other step.\n *\n *   const invoice = await experimental.ai.extract(ctx, \"read invoice\", {\n *     state: email.body,\n *     fields: {\n *       orderId: { type: \"text\", instructions: \"The order number\" },\n *       amount: { type: \"number\", decimals: 2, unit: \"USD\" },\n *       dueDate: { type: \"date\" },\n *     },\n *   });\n *   invoice.amount.value;      // number | null\n *   invoice.amount.confidence; // 0..1\n *\n * Extraction models are not reliable at multi-step arithmetic: extract the\n * parts (line items, quantities) and do the sums in code.\n */\nexport async function extract<const F extends Record<string, ExtractField>>(\n  ctx: any,\n  name: string,\n  options: ExtractOptions<F>\n): Promise<ExtractAnswers<F>> {\n  const stepValue = await ctx.step(\n    name,\n    {\n      retries: 2,\n      // Space retries out so a rate-limited or briefly unavailable model has\n      // time to recover before the next attempt (5s, then 10s).\n      retryPolicy: RetryBackoffLinear(5),\n      timeout: options.timeout ?? 30_000,\n    },\n    async () => {\n      validateFields(name, options.fields);\n      const images = await readImages(name, options.images ?? []);\n      const textState = typeof options.state === \"string\";\n      const state = textState\n        ? (options.state as string)\n        : JSON.stringify(canonicalize(options.state));\n      if (state.trim() === \"\" && images.length === 0) {\n        throw new NonRetriableError(\n          `extract(\"${name}\"): nothing to read — state is empty and no images were given`\n        );\n      }\n\n      const engine = resolveExtractionEngineForContext(ctx);\n      const res = await engine.extract({\n        model: options.model ?? DEFAULT_EXTRACTION_MODEL,\n        state,\n        fields: options.fields,\n        ...(images.length ? { images } : {}),\n        ...(options.referenceDate\n          ? { referenceDate: options.referenceDate }\n          : {}),\n        stepName: name,\n      });\n\n      warnIfTruncated(name, res.truncated);\n\n      // Only keep answers to the fields asked for, and require every one of\n      // them with the right type: a flow reading a missing answer would\n      // otherwise fail far from the cause. Retrying would not help: the proxy\n      // answers a retry of the same step with the first attempt's result.\n      const answers: Record<string, unknown> = {};\n      for (const [key, field] of Object.entries(options.fields)) {\n        const answer = res.answers[key];\n        if (!answer || answer.type !== field.type) {\n          throw new NonRetriableError(\n            `extract(\"${name}\"): model returned no ${field.type} answer for \"${key}\"`\n          );\n        }\n        if (!isValidAnswer(field, answer)) {\n          throw new NonRetriableError(\n            `extract(\"${name}\"): model returned an invalid ${field.type} answer for \"${key}\"`\n          );\n        }\n        // Offsets into JSON the model was sent but the flow never sees would\n        // only mislead.\n        answers[key] = textState ? answer : withoutSpans(answer);\n      }\n      return answers;\n    }\n  );\n  // Wrap with canonicalize so key order is deterministic on first execution\n  // and replay (JSONB normalises key order; canonicalize sorts keys to match).\n  return canonicalize(stepValue) as ExtractAnswers<F>;\n}\n\n/**\n * The model reports when the input was too long and was cut before it was\n * read. The answers are still returned, since most fields usually sit early in\n * a document, but a value past the cut comes back as `null` (or as a guess from\n * what the model did see), so leave a warning to explain it.\n */\nfunction warnIfTruncated(name: string, truncated: boolean): void {\n  if (!truncated) return;\n  log.warn(\n    `extract(\"${name}\"): the input was too long and was cut before it was read; answers only reflect the start of it`,\n    { [ATTRS.STEP_NAME]: name }\n  );\n}\n\nfunction validateFields(\n  name: string,\n  fields: Record<string, ExtractField>\n): void {\n  const entries = Object.entries(fields ?? {});\n  if (entries.length === 0) {\n    throw new NonRetriableError(`extract(\"${name}\"): no fields given`);\n  }\n  for (const [key, f] of entries) {\n    if (!FIELD_NAME.test(key)) {\n      throw new NonRetriableError(\n        `extract(\"${name}\"): field name \"${key}\" must start with a letter or underscore and use only letters, digits, \"_\", \".\" or \"-\" (max 64 characters)`\n      );\n    }\n    if (f.type === \"list\" && !f.items) {\n      throw new NonRetriableError(\n        `extract(\"${name}\"): list field \"${key}\" needs \"items\" (\"text\", \"number\" or \"date\")`\n      );\n    }\n    if (f.type === \"estimate\" && (f.min === undefined || f.max === undefined)) {\n      throw new NonRetriableError(\n        `extract(\"${name}\"): estimate field \"${key}\" needs \"min\" and \"max\"`\n      );\n    }\n  }\n}\n\nasync function readImages(\n  name: string,\n  images: (InlineFile | string)[]\n): Promise<ExtractImage[]> {\n  if (images.length > MAX_IMAGES) {\n    throw new NonRetriableError(\n      `extract(\"${name}\"): at most ${MAX_IMAGES} images can be read, got ${images.length}`\n    );\n  }\n  const out: ExtractImage[] = [];\n  let total = 0;\n  for (const [i, image] of images.entries()) {\n    let contentType: string;\n    let bytes: Buffer;\n    if (typeof image === \"string\") {\n      const match = /^data:([^;,]+)(?:;[^,]*)?;base64,(.*)$/is.exec(image);\n      if (!match) {\n        throw new NonRetriableError(\n          `extract(\"${name}\"): image ${i + 1} is not a base64 data URL`\n        );\n      }\n      contentType = match[1].toLowerCase();\n      bytes = Buffer.from(match[2], \"base64\");\n    } else {\n      contentType = image.contentType.toLowerCase();\n      try {\n        bytes = await image.read(MAX_IMAGE_BYTES);\n      } catch (e) {\n        if (e instanceof FileSizeLimitError) {\n          throw new NonRetriableError(\n            `extract(\"${name}\"): image ${i + 1} is larger than 4 MiB`\n          );\n        }\n        throw e;\n      }\n    }\n    if (!IMAGE_TYPES.has(contentType)) {\n      throw new NonRetriableError(\n        `extract(\"${name}\"): image ${i + 1} is ${contentType}; only PNG, JPEG and WebP can be read`\n      );\n    }\n    if (bytes.length > MAX_IMAGE_BYTES) {\n      throw new NonRetriableError(\n        `extract(\"${name}\"): image ${i + 1} is larger than 4 MiB`\n      );\n    }\n    total += bytes.length;\n    if (total > MAX_TOTAL_IMAGE_BYTES) {\n      throw new NonRetriableError(\n        `extract(\"${name}\"): images total more than 8 MiB`\n      );\n    }\n    out.push({ contentType, base64: bytes.toString(\"base64\") });\n  }\n  return out;\n}\n\n// The value must be usable as the field type promises. null is a valid value\n// for every scalar field: it means the input does not contain it.\nfunction isValidAnswer(field: ExtractField, answer: ExtractAnswer): boolean {\n  const v = answer.value;\n  switch (field.type) {\n    case \"text\":\n    case \"date\":\n    case \"time\":\n    case \"datetime\":\n      return v === null || isString(v);\n    case \"number\":\n    case \"duration\":\n      return v === null || isNumber(v);\n    case \"list\": {\n      // Every item must match `items`, or a number list could hold strings.\n      const isItem = field.items === \"number\" ? isNumber : isString;\n      return Array.isArray(v) && v.every(isItem);\n    }\n    case \"estimate\": {\n      // The point and the distribution come back in the bounds' type: ISO\n      // date strings for a date estimate, numbers otherwise.\n      const isPoint = typeof field.min === \"string\" ? isString : isNumber;\n      const e = answer as EstimateAnswer;\n      return (\n        (v === null || isPoint(v)) &&\n        [e.mean, e.median, e.p10, e.p90].every(\n          (x) => x === undefined || isPoint(x)\n        )\n      );\n    }\n  }\n}\n\nfunction isString(x: unknown): x is string {\n  return typeof x === \"string\";\n}\n\nfunction isNumber(x: unknown): x is number {\n  return typeof x === \"number\" && Number.isFinite(x);\n}\n\nfunction withoutSpans(answer: ExtractAnswer): ExtractAnswer {\n  const {\n    span: _span,\n    spans: _spans,\n    ...rest\n  } = answer as ExtractAnswer & {\n    span?: unknown;\n    spans?: unknown;\n  };\n  return rest as ExtractAnswer;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentMessage, ToolSpec, TurnResult } from \"./engine\";\nimport type { ToolDefinition } from \"./defineTool\";\nimport {\n  validateSchema,\n  toJsonSchema,\n  canonicalize,\n  canonicalStringify,\n} from \"./schema\";\nimport { resolveEngineForContext } from \"./engineResolver\";\n\n// ---- types ----------------------------------------------------------------\n\nexport interface AgentConfig<I = any, R = any> {\n  /** Unique agent name; used to namespace checkpointed steps. */\n  name: string;\n  model: string;\n  instructions: string;\n  tools?: ReadonlyArray<ToolDefinition>;\n  /** Sealed prompt template — callers pass inputs, never a raw prompt. */\n  prompt: (args: { inputs: I; context: Record<string, unknown> }) => string;\n  /** Result contract. Omit for free-text agents (run resolves to final assistant text). */\n  result?: StandardSchemaV1<unknown, R>;\n  /** Max LLM turns before the run fails. Default 10. */\n  maxTurns?: number;\n  /**\n   * Pre-run hook; the object it returns merges into the prompt template context.\n   * Like the agent body, this runs again on every orchestrator replay, so any\n   * side effects must be wrapped in `ctx.step(...)` to stay idempotent (see the\n   * `beforeRun` test, which loads its value through a checkpointed step).\n   */\n  beforeRun?: (\n    ctx: any,\n    args: { inputs: I }\n  ) => Promise<Record<string, unknown> | void>;\n  /**\n   * Post-run hook, called with the final result once the agent completes. Like\n   * `beforeRun` it runs again on every orchestrator replay, so any side effects\n   * (writes, notifications) must be wrapped in `ctx.step(...)` to stay\n   * idempotent — an un-checkpointed write here repeats on each replay.\n   */\n  afterRun?: (ctx: any, result: R | string) => Promise<void>;\n}\n\nexport interface Agent<I = any, R = any> {\n  readonly name: string;\n  readonly config: AgentConfig<I, R>;\n  run(ctx: any, inputs: I): Promise<any>;\n}\n\n// ---- validation -----------------------------------------------------------\n\nconst AGENT_NAME_RE = /^[A-Za-z][A-Za-z0-9]*$/;\n\n// ---- run-counter ----------------------------------------------------------\n// Keyed on the context object so the counter resets per context instance\n// (i.e., per orchestration invocation). Each fresh testFlowContext() call\n// produces a new object, so the counter naturally restarts each cycle.\n// Within one context instance, multiple agent.run() calls for the same\n// agent name get incrementing numbers: OrderTriage#1, OrderTriage#2, …\nconst runCounters = new WeakMap<object, Map<string, number>>();\n\nfunction nextRunNumber(ctx: object, agentName: string): number {\n  let byName = runCounters.get(ctx);\n  if (!byName) {\n    byName = new Map();\n    runCounters.set(ctx, byName);\n  }\n  const n = (byName.get(agentName) ?? 0) + 1;\n  byName.set(agentName, n);\n  return n;\n}\n\n// ---- main implementation --------------------------------------------------\n\nasync function runAgent<I, R>(\n  config: AgentConfig<I, R>,\n  ctx: any,\n  inputs: I\n): Promise<R | string> {\n  const engine = resolveEngineForContext(ctx);\n\n  const runNumber = nextRunNumber(ctx, config.name);\n  const prefix = `${config.name}#${runNumber}`;\n\n  // beforeRun hook\n  const promptContext: Record<string, unknown> =\n    (await config.beforeRun?.(ctx, { inputs })) ?? {};\n\n  // System prompt\n  let system = config.instructions;\n  if (config.result) {\n    system +=\n      \"\\n\\nWhen the task is complete you MUST call complete_task with the final result.\";\n  }\n\n  // Build tool specs\n  const userTools: ReadonlyArray<ToolDefinition> = config.tools ?? [];\n  const toolSpecs: ToolSpec[] = await Promise.all(\n    userTools.map(async (t) => ({\n      name: t.name,\n      description: t.usage ? `${t.description}\\n${t.usage}` : t.description,\n      parameters: await toJsonSchema(t.parameters),\n    }))\n  );\n\n  // Add complete_task synthetic tool if there is a result schema\n  if (config.result) {\n    toolSpecs.push({\n      name: \"complete_task\",\n      description:\n        \"Call this when the task is complete, with the final result.\",\n      parameters: await toJsonSchema(config.result),\n    });\n  }\n\n  const toolMap = new Map<string, ToolDefinition>(\n    userTools.map((t) => [t.name, t])\n  );\n\n  // Initial messages\n  const messages: AgentMessage[] = [\n    {\n      role: \"user\",\n      content: config.prompt({ inputs, context: promptContext }),\n    },\n  ];\n\n  const maxTurns = config.maxTurns ?? 10;\n  const maxCompletionNudges = 2;\n  let nudges = 0;\n\n  for (let turn = 1; turn <= maxTurns; turn++) {\n    // --- LLM step -----------------------------------------------------------\n    // Wrap with canonicalize so that on replay the object has the same key\n    // order as on first execution (JSONB normalises key order on storage).\n    const llmStepName = `${prefix}/turn-${turn}/llm`;\n    const res: TurnResult = canonicalize(\n      await ctx.step(llmStepName, { retries: 2, timeout: 300_000 }, () =>\n        engine.turn({\n          model: config.model,\n          system,\n          messages,\n          ...(toolSpecs.length ? { tools: toolSpecs } : {}),\n          stepName: llmStepName,\n        })\n      )\n    );\n\n    // Push the assistant message so subsequent turns have the full history.\n    // On replay this path is traversed again with the exact same messages,\n    // reconstructing the conversation identically because:\n    //   1. The LLM step returns its cached value immediately.\n    //   2. Tool steps also return cached values immediately.\n    //   3. Every push happens in deterministic order — same inputs, same outputs.\n    messages.push({\n      role: \"assistant\",\n      content: res.text,\n      toolCalls: res.toolCalls,\n    });\n\n    // complete_task is the agent's \"I'm done\" signal. We only act on it when it\n    // is the SOLE tool call in the turn. If the model batches it with other\n    // tools, completion is premature — it hasn't seen those tools' results yet —\n    // so we defer it (below), run the other tools, and let the model re-confirm\n    // completion on a later turn. This guarantees a side-effect tool batched\n    // with complete_task is never silently skipped.\n    const toolCalls = res.toolCalls ?? [];\n    const completeCall = toolCalls.find((c) => c.name === \"complete_task\");\n    const otherCalls = toolCalls.filter((c) => c.name !== \"complete_task\");\n\n    // --- complete_task (structured result) ---------------------------------\n    if (completeCall && config.result && otherCalls.length === 0) {\n      const v = await validateSchema(config.result, completeCall.arguments);\n      if (v.ok) {\n        await config.afterRun?.(ctx, v.value as R);\n        return v.value as R;\n      }\n      // Validation failed — feed the error back and let the model retry.\n      messages.push({\n        role: \"tool\",\n        toolCallId: completeCall.id,\n        toolName: \"complete_task\",\n        result: `Validation failed: ${v.issues}. Call complete_task again with corrected arguments.`,\n      });\n      continue;\n    }\n\n    // --- end_turn (no result schema) ---------------------------------------\n    if (res.stopReason === \"end_turn\") {\n      if (!config.result) {\n        await config.afterRun?.(ctx, res.text);\n        return res.text;\n      }\n      // Has result schema but model stopped without calling complete_task:\n      // nudge a bounded number of times, then fail rather than burn turns.\n      if (++nudges > maxCompletionNudges) {\n        throw new Error(\n          `Agent \"${config.name}\" finished without calling complete_task after ${maxCompletionNudges} reminders`\n        );\n      }\n      messages.push({\n        role: \"user\",\n        content: \"You must call complete_task with the final result.\",\n      });\n      continue;\n    }\n\n    // --- tool calls --------------------------------------------------------\n    // complete_task reaches here when it was batched with other tool calls\n    // (deferred above) or hallucinated with no result schema. Either way it\n    // needs a tool_result so the conversation has no orphaned tool_use; the\n    // real tools then run as their own checkpointed steps below.\n    if (completeCall) {\n      messages.push({\n        role: \"tool\",\n        toolCallId: completeCall.id,\n        toolName: \"complete_task\",\n        result: config.result\n          ? \"complete_task must be the only tool call in a turn. The other tools you called this turn have been run — review their results, then call complete_task on its own.\"\n          : `Unknown tool \"complete_task\" — available tools: ${userTools\n              .map((t) => t.name)\n              .join(\", \")}`,\n      });\n    }\n\n    for (let i = 0; i < otherCalls.length; i++) {\n      const call = otherCalls[i];\n      const tool = toolMap.get(call.name);\n\n      if (!tool) {\n        // Unknown tool — feed error back without creating a step\n        const available = userTools.map((t) => t.name).join(\", \");\n        messages.push({\n          role: \"tool\",\n          toolCallId: call.id,\n          toolName: call.name,\n          result: `Unknown tool \"${call.name}\" — available tools: ${available}`,\n        });\n        continue;\n      }\n\n      const approved = await checkApproval(\n        ctx,\n        prefix,\n        turn,\n        i + 1,\n        tool,\n        call.arguments\n      );\n\n      if (!approved) {\n        messages.push({\n          role: \"tool\",\n          toolCallId: call.id,\n          toolName: call.name,\n          result: `The user rejected this tool call. Do not retry it; choose another course of action.`,\n        });\n        continue;\n      }\n\n      // Execute the tool as its own checkpointed step.\n      // Use `ok` flag (not double-underscore keys) to avoid the KeelCamelCasePlugin\n      // mangling __prefix keys when the JSONB value is read back from the DB.\n      // Wrap with canonicalize so key order is identical on first execution and\n      // replay (JSONB normalises key order on storage).\n      const stepResult = canonicalize(\n        await ctx.step(\n          `${prefix}/turn-${turn}/tool-${i + 1}:${call.name}`,\n          { retries: 2, timeout: 60_000 },\n          async () => {\n            const v = await validateSchema(tool.parameters, call.arguments);\n            if (!v.ok) {\n              return { ok: false, error: `Invalid arguments: ${v.issues}` };\n            }\n            return { ok: true, value: (await tool.execute(v.value)) ?? null };\n          }\n        )\n      );\n\n      // Use canonicalStringify so the tool-result bytes are identical on first\n      // execution and replay regardless of JSONB key-order normalisation.\n      const resultText = stepResult.ok\n        ? canonicalStringify((stepResult as any).value)\n        : (stepResult as any).error;\n\n      messages.push({\n        role: \"tool\",\n        toolCallId: call.id,\n        toolName: call.name,\n        result: resultText,\n      });\n    }\n  }\n\n  throw new Error(`Agent \"${config.name}\" exceeded maxTurns (${maxTurns})`);\n}\n\n/**\n * Gate a tool call behind a UI approval step when the tool's `approval` field\n * requires it. Returns true if the call is approved (or no approval needed),\n * false if the user rejected it.\n *\n * On first encounter this throws UIRenderDisrupt (via ctx.ui.page) to pause\n * the run. On replay after the step is COMPLETED, ui.page returns the cached\n * {data, action} immediately, so approved calls continue into the tool step\n * and rejected calls return false.\n */\nasync function checkApproval(\n  ctx: any,\n  prefix: string,\n  turn: number,\n  index: number,\n  tool: ToolDefinition,\n  args: Record<string, unknown>\n): Promise<boolean> {\n  const needsApproval =\n    tool.approval === true ||\n    (typeof tool.approval === \"function\" && tool.approval(args as any));\n  if (!needsApproval) return true;\n\n  const result = await ctx.ui.page(\n    `${prefix}/turn-${turn}/approve-${index}:${tool.name}`,\n    {\n      title: `Approve tool call: ${tool.name}`,\n      content: [\n        ctx.ui.display.markdown({\n          content: `The agent wants to call **${tool.name}** with:\\n\\n\\`\\`\\`json\\n${canonicalStringify(args)}\\n\\`\\`\\``,\n        }),\n      ],\n      actions: [\n        { label: \"Approve\", value: \"approve\" },\n        { label: \"Reject\", value: \"reject\" },\n      ],\n    }\n  );\n\n  return (result as any).action === \"approve\";\n}\n\n// ---- public factory -------------------------------------------------------\n\nexport function defineAgent<I = any, R = any>(\n  config: AgentConfig<I, R>\n): Agent<I, R> {\n  if (!AGENT_NAME_RE.test(config.name)) {\n    throw new Error(\n      `Invalid agent name \"${config.name}\" — must be alphanumeric PascalCase`\n    );\n  }\n\n  const names = new Set<string>();\n  for (const tool of config.tools ?? []) {\n    if (names.has(tool.name)) {\n      throw new Error(\n        `Duplicate tool \"${tool.name}\" on agent \"${config.name}\"`\n      );\n    }\n    names.add(tool.name);\n  }\n\n  return Object.freeze({\n    name: config.name,\n    config,\n    run: (ctx: any, inputs: I) => runAgent(config, ctx, inputs),\n  });\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\ntype JsonValue =\n  | string\n  | number\n  | boolean\n  | null\n  | JsonValue[]\n  | { [k: string]: JsonValue };\n\nexport interface ToolDefinition<P = any> {\n  /** snake_case identifier the model sees. */\n  name: string;\n  description: string;\n  /** Extra guidance on when/how to use the tool, appended to the description. */\n  usage?: string;\n  /** Standard Schema (Zod v4) for the tool's arguments. */\n  parameters: StandardSchemaV1<unknown, P>;\n  /** true = always gate behind a UI approval step; predicate = gate when it returns true. */\n  approval?: boolean | ((args: P) => boolean);\n  execute: (args: P) => Promise<JsonValue | void>;\n}\n\nconst NAME_RE = /^[a-z][a-z0-9_]*$/;\nconst RESERVED = new Set([\"complete_task\"]);\n\nexport function defineTool<P>(\n  config: ToolDefinition<P>\n): Readonly<ToolDefinition<P>> {\n  if (!NAME_RE.test(config.name)) {\n    throw new Error(\n      `Invalid tool name \"${config.name}\" — must be snake_case ([a-z][a-z0-9_]*)`\n    );\n  }\n  if (RESERVED.has(config.name)) {\n    throw new Error(`Tool name \"${config.name}\" is reserved`);\n  }\n  return Object.freeze({ ...config });\n}\n","// Test doubles for the experimental AI primitives. Consumed as\n// `experimental.testing` (see ../experimental/index.ts).\n\nexport { ScriptedEngine, scriptedTurn } from \"../agents/engine\";\nexport { ScriptedDecisionEngine } from \"../agents/decision\";\nexport { ScriptedExtractionEngine } from \"../agents/extraction\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAaM,OAoJA,OAWA;AA5KN;AAAA;AAAA;AAaA,IAAM,QAAQ;AAAA,MACZ,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,uBAAuB;AAAA,MACvB,OAAO;AAAA,MACP,KAAK;AAAA,MACL,UAAU;AAAA,MACV,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,mBAAmB;AAAA,MACnB,iBAAiB;AAAA,MACjB,YAAY;AAAA,MACZ,eAAe;AAAA,MACf,WAAW;AAAA,MACX,aAAa;AAAA,MACb,WAAW;AAAA,MACX,WAAW;AAAA,MACX,aAAa;AAAA,MACb,SAAS;AAAA,MACT,kBAAkB;AAAA,MAClB,cAAc;AAAA,MACd,eAAe;AAAA,MACf,SAAS;AAAA,MACT,qBAAqB;AAAA,MACrB,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,yBAAyB;AAAA,MACzB,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,kBAAkB;AAAA,MAClB,yBAAyB;AAAA,MACzB,yBAAyB;AAAA,MACzB,mBAAmB;AAAA,MACnB,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,MACT,kBAAkB;AAAA,MAClB,aAAa;AAAA,MACb,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,yBAAyB;AAAA,MACzB,2BAA2B;AAAA,MAC3B,4BAA4B;AAAA,MAC5B,0BAA0B;AAAA,MAC1B,4BAA4B;AAAA,MAC5B,mCAAmC;AAAA,MACnC,+BAA+B;AAAA,MAC/B,iCAAiC;AAAA,MACjC,iCAAiC;AAAA,MACjC,gCAAgC;AAAA,MAChC,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C,QAAM,WAAW,EAAE;AAC5B;AAFgB;AAeT,IAAM,SAAS,eAAe;","names":["file","KSUID","KSUID","createTraceAPI","import_kysely","import_kysely","import_node_async_hooks","TraceParent","import_kysely","pgTypes","parseInterval","import_pg","pgTypes","context","import_pg","SpanKind","opentelemetry","fetch","SpanKind","opentelemetry","import_pg","pgTypes","parsePostgresArray","deleteStoredFile","result","sql","SpanKind","pgTypes","pgDefaults","WebSocket","import_kysely","snakeCaseBase","camelCaseBase","complete","sql","context","context","context","table","code","table","context","context","builder","row","import_jsonwebtoken","jwt","identity","jwt","identity","import_jsonwebtoken","import_node_async_hooks","identity","buildHeaders","identity","jwt","getApiUrl","identity","buildHeaders","opentelemetry","getApiUrl","identity","SpanKind","base","import_json_rpc_2","import_async_hooks","opentelemetry","import_async_hooks","import_node_async_hooks","result","SpanKind","import_json_rpc_2","opentelemetry","SpanKind","import_json_rpc_2","opentelemetry","SpanKind","import_json_rpc_2","opentelemetry","SpanKind","import_json_rpc_2","opentelemetry","code","TypeError","evaluate","check","Duration","identity","list","op","returnType","context","dynType","code","types","check","listType","label","evaluate","Duration","list","types","code","base","context","base","ref","list","scoped","import_change_case","context","isObject","summary","file","context","list","file","file","label","import_kysely","import_node_fs","file","fromWireAnswer","context","import_ksuid","STEP_STATUS","STEP_TYPE","KSUID","context","completed","parsedData","file","tool","import_change_case","SpanKind","import_ksuid","init","code","getApiUrl","code","label","import_ksuid","import_render","getApiUrl","identity","KSUID","import_kysely","import_ksuid","import_kysely","pick","opentelemetry","emit","fromEnv","cursor","walk","KSUID","page","result","t","fromEnv","summary","result","import_kysely","write","keyValue","fromEnv","base","AiSdkEngine","ScriptedEngine","defineAgent","defineTool","scriptedTurn","file","isValidAnswer","image","tool","RESERVED","defineAgent","defineTool","ScriptedEngine","scriptedTurn","AiSdkEngine","createTraceAPI","KSUID"]}