@usenaive-sdk/blueprints 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-CVZ2DY27.js +50 -0
- package/dist/chunk-CVZ2DY27.js.map +1 -0
- package/dist/define-DiOsp5oY.d.ts +846 -0
- package/dist/index.d.ts +3 -836
- package/dist/index.js +1194 -923
- package/dist/index.js.map +1 -1
- package/dist/template.d.ts +2 -0
- package/dist/template.js +9 -0
- package/dist/template.js.map +1 -0
- package/package.json +6 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../core/src/id.ts","../../core/src/errors.ts","../../core/src/money.ts","../../core/src/schema/audit-actions.ts","../../core/src/schema/common.ts","../../core/src/schema/harness.ts","../../core/src/schema/agent.ts","../../core/src/schema/browser.ts","../../core/src/schema/org.ts","../../core/src/schema/model-selection.ts","../../core/src/schema/session.ts","../../core/src/schema/social.ts","../../core/src/schema/event.ts","../../core/src/schema/board.ts","../../core/src/schema/identity.ts","../../core/src/schema/resource.ts","../../core/src/schema/files-library.ts","../../core/src/schema/comms.ts","../../core/src/schema/app.ts","../../core/src/schema/install.ts","../../core/src/schema/blueprint.ts","../../core/src/schema/vault.ts","../../core/src/schema/handoff.ts","../../core/src/schema/show.ts","../../core/src/schema/compose.ts","../../core/src/schema/catalog.ts","../../core/src/schema/media.ts","../../core/src/schema/app-data.ts","../../core/src/schema/stock-photo.ts","../../core/src/schema/creator.ts","../../core/src/schema/legal.ts","../../core/src/schema/wallet.ts","../../core/src/schema/cards.ts","../../core/src/schema/proxy-trace.ts","../../core/src/schema/review.ts","../../core/src/schema/mini-app.ts","../../core/src/session-token.ts","../../core/src/logo-svg.ts","../../core/src/file-url.ts","../src/define.ts","../src/roster.ts","../src/report.ts","../src/template.ts","../src/load.ts","../src/files.ts","../src/up.ts","../src/apps.ts","../src/buckets.ts","../src/migrations.ts","../src/agents.ts","../src/reconcile-cards.ts","../src/reconcile-legal.ts","../src/tasks.ts","../src/vaults.ts","../src/reconcile-wallet.ts","../src/scoped.ts"],"sourcesContent":["/** Identifiers — one prefix per type, `prefix_` + Crockford base32 (canonical-spec §2). */\n\nexport type IdPrefix =\n | \"org\"\n | \"usr\"\n | \"key\"\n | \"agt\"\n | \"ses\"\n | \"evt\"\n | \"cmp\"\n | \"skl\"\n | \"fil\"\n | \"dep\"\n | \"whk\"\n | \"run\"\n | \"led\"\n | \"snp\"\n | \"vol\"\n | \"whd\"\n | \"aud\"\n /** Computer workspace (`canonical-spec §41`): one recorded command, one managed browser session. */\n | \"cmd\"\n | \"brw\"\n /**\n * P2 identity (`canonical-spec §22`–`§25`): a persona an agent acts as, a vault bound to it and one\n * credential in that vault, and the persona's endpoints — a domain, an email inbox, a phone\n * number, an inbound message, and one it sent (§24.1, ADR-1076).\n */\n | \"idn\"\n | \"vlt\"\n | \"vcr\"\n | \"dom\"\n | \"eml\"\n | \"pho\"\n | \"inb\"\n | \"out\"\n /**\n * The team board (`canonical-spec §28`): one board per coordinator session, a card on it, and one\n * comment on a card.\n */\n | \"brd\"\n | \"crd\"\n | \"bcm\"\n /** Support surface (`apps/central`): a ticket and one message on it. Not control-plane objects. */\n | \"tkt\"\n | \"spm\"\n /** Apps (`canonical-spec §29`): a hosted web application and one deployment of it. */\n | \"app\"\n | \"apd\"\n /** One applied blueprint declaration, per organization and project (`canonical-spec §29.6`). */\n | \"bpi\"\n /** A video clipping job (`canonical-spec §30`). */\n | \"clj\"\n /**\n * One published blueprint artifact (`canonical-spec §31`): the built tree of one blueprint ×\n * template × released version. The only id here that names a row belonging to no organization.\n */\n | \"bpa\"\n // core-gaps: contracts (`canonical-spec §32–§37`)\n /** An async media job — video, clip, transcription (§33, D5). */\n | \"med\"\n /** One open managed browser, one saved login (identity-scoped, D4), one grant on it (§32.1). */\n | \"brw\"\n | \"bct\"\n | \"bgr\"\n /** One migration applied to an app's own database (§37.1). */\n | \"dbm\"\n /**\n * The creator program (`canonical-spec §42`): a creator, an application to become one, a referred\n * organization, one commission, one payout, and a creator template. Like `bpa`, rows belonging\n * to no organization; a template *version* has no id and is keyed `(template, version)`.\n */\n | \"crt\"\n | \"cra\"\n | \"crf\"\n | \"crc\"\n | \"crp\"\n | \"ctp\"\n /** A budget hold. Internal only: it is never a field on any wire object (`canonical-spec §2`). */\n | \"res\"\n /** One priced tool call. Internal only, and the settlement's idempotency key (`§11`, ADR-0272). */\n | \"tol\"\n /**\n * Identity-owned legal, wallet and cards (`canonical-spec §43`–`§45`): a verification and one of\n * its members, a company and one of its documents; a wallet and one transaction; a card and one\n * logged card transaction.\n */\n | \"lgv\"\n | \"lgm\"\n | \"lgc\"\n | \"lgd\"\n | \"wlt\"\n | \"wtx\"\n | \"vcd\"\n | \"vct\"\n /** A person's verdict on agent work given outside the approval box (`canonical-spec §47`). */\n | \"rev\"\n /** Not a stored object: the per-request id echoed in `x-request-id` and every envelope (§3). */\n | \"req\";\n\n/** Crockford base32, lowercase on the wire. Decoding is case-insensitive (i/l/o/u excluded). */\nconst ALPHABET = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst SUFFIX_LENGTH = 26;\nconst SUFFIX_PATTERN = new RegExp(`^[${ALPHABET}]{${SUFFIX_LENGTH},}$`);\n\n/** `${prefix}_` + 26 random Crockford base32 chars (130 bits). */\nexport function newId(prefix: IdPrefix): string {\n return idFromBytes(prefix, crypto.getRandomValues(new Uint8Array(SUFFIX_LENGTH)));\n}\n\n/**\n * `${prefix}_` + one Crockford char per byte of `bytes` (at least 26). Deterministic: the same\n * bytes name the same id, which is how a retried `Idempotency-Key` names the same `med_` job.\n */\nexport function idFromBytes(prefix: IdPrefix, bytes: Uint8Array): string {\n if (bytes.length < SUFFIX_LENGTH) throw new Error(`an id needs ${SUFFIX_LENGTH} bytes`);\n let suffix = \"\";\n for (const byte of bytes.subarray(0, SUFFIX_LENGTH)) suffix += ALPHABET[byte & 31];\n return `${prefix}_${suffix}`;\n}\n\n/**\n * The same shape, **derived** rather than drawn: one seed always names one id.\n *\n * For work that can be redone — a render collected again because the wake that collected it died\n * before it could say so — a random id makes the retry a second object with a second row. Deriving\n * the id from the work's own idempotency key makes the retry name what is already there, so the\n * upsert behind it lands once and the bytes overwrite themselves (ADR-0514).\n */\nexport async function derivedId(prefix: IdPrefix, seed: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(seed));\n let suffix = \"\";\n for (const byte of new Uint8Array(digest, 0, SUFFIX_LENGTH)) suffix += ALPHABET[byte & 31];\n return `${prefix}_${suffix}`;\n}\n\n/** True when `value` is a well-formed id of exactly this prefix (aliases such as `agent_` fail). */\nexport function isId(prefix: IdPrefix, value: string): boolean {\n const head = `${prefix}_`;\n if (!value.startsWith(head)) return false;\n return SUFFIX_PATTERN.test(value.slice(head.length).toLowerCase());\n}\n","/** The one error envelope and the one code taxonomy (canonical-spec §3). */\n\nexport type ErrorType =\n | \"invalid_request\"\n | \"authentication\"\n | \"permission\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limit\"\n | \"quota\"\n | \"api_error\"\n | \"not_implemented\";\n\n/** Every P1 code, with its coarse `type` and HTTP status. Adding one is a spec change. */\nconst CODES = {\n window_unavailable: [\"invalid_request\", 400],\n validation_failed: [\"invalid_request\", 400],\n unauthorized: [\"authentication\", 401],\n forbidden: [\"permission\", 403],\n not_found: [\"not_found\", 404],\n /** The path exists; the method does not. The response carries `Allow` (§3). */\n method_not_allowed: [\"invalid_request\", 405],\n budget_exceeded: [\"quota\", 402],\n insufficient_credits: [\"quota\", 402],\n /**\n * The organization holds no active plan, so it may not be used. `402`, alongside the other two\n * money codes, because the remedy is a payment — not `403`, which reads as \"your credential is\n * wrong\" and would send a customer to rotate a perfectly good key. Distinct from\n * `insufficient_credits`: that one means \"fund the balance\", this one means \"start the plan\".\n */\n subscription_required: [\"quota\", 402],\n version_conflict: [\"conflict\", 409],\n /**\n * The name is taken by a resource another project owns, and the request did not ask to take it\n * (ADR-0375). Nothing existing fits: `validation_failed` says the request is malformed and it is\n * not, `forbidden` reads as \"your credential is wrong\" and sends a customer to rotate a good key,\n * and `version_conflict` means optimistic concurrency.\n */\n name_conflict: [\"conflict\", 409],\n /**\n * A shared declaration moved underneath the applier: the install's `revision` is not the\n * `expected_revision` the apply carried (`§29.6`). Not `version_conflict`, which is one\n * immutable-versioned object's optimistic concurrency and whose remedy is to re-read that\n * object — this one carries a set of drifted PATHS and its remedy is a merge, and a client that\n * cannot tell them apart shows a config diff for a stale agent version.\n */\n revision_conflict: [\"conflict\", 409],\n idempotency_conflict: [\"conflict\", 409],\n /**\n * A lifecycle action asked of an object whose status does not admit it (§43–§45): forming a\n * company on an unverified verification, funding a `frozen` wallet, cancelling a card that is not\n * `active`. Not `version_conflict` — nothing raced; the remedy is to read the status.\n */\n state_conflict: [\"conflict\", 409],\n session_running: [\"conflict\", 409],\n session_terminal: [\"conflict\", 409],\n computer_unavailable: [\"conflict\", 409],\n /**\n * Two P2 additions (ADR-0118). Both mean \"not an error — retry later\", and no existing code\n * carries that: `feature_not_configured` is permanent, `computer_unavailable` is about a\n * sandbox, and `validation_failed` would tell a durable runtime to give up on something that\n * will succeed once verification or carrier approval clears.\n */\n job_not_ready: [\"conflict\", 409],\n compliance_pending: [\"conflict\", 409],\n // core-gaps: contracts (`canonical-spec §32`, §37; ADR-0448)\n /** `--app` omitted and the org has more than one fullstack app to resolve it to (§37.2). */\n ambiguous_app: [\"conflict\", 409],\n /** A saved browser login is held by a human-login flow for the next 15 minutes (§32.6). */\n context_locked: [\"conflict\", 409],\n rate_limited: [\"rate_limit\", 429],\n feature_not_configured: [\"not_implemented\", 501],\n internal_error: [\"api_error\", 500],\n /**\n * A configured upstream answered with a failure of its own — a 5xx, or a browser automation that\n * did nothing (§32.5). Not `internal_error`: the remedy is a retry, and nothing of ours broke.\n */\n provider_error: [\"api_error\", 502],\n} as const satisfies Record<string, readonly [ErrorType, number]>;\n\nexport type ErrorCode = keyof typeof CODES;\n\nexport interface ErrorEnvelope {\n error: {\n type: ErrorType;\n code: ErrorCode;\n message: string;\n request_id: string;\n param?: string;\n };\n}\n\n/** How much of an error's own words one log line may carry (`faultOf`). */\nconst FAULT_MAX_CHARS = 2_000;\n\n/**\n * One error, as one **operator log line**. Never a customer-facing message — that is `toEnvelope` —\n * and never the error *object*.\n *\n * WHY NOT `console.error(prefix, error)`, which is what this replaces. Handed the object, the\n * runtime serialises whatever the thrower hung on it: a vendor client's `response`, `request` or\n * `config`, and with them the `authorization` header that carried our key (`CLAUDE.md §2`). It also\n * loses the one part worth reading — in production a media job failed every seven seconds for hours\n * and the captured line held stack frames with no message at all (ADR-0733). A derived string is\n * both safer and more legible.\n *\n * WHAT IS SAFE HERE is the same judgement `media-openrouter/src/wire.ts` already makes: that adapter\n * repeats a failed call's **status** and never its **body**, precisely because a body may quote the\n * request. So a vendor body never becomes a `message` in the first place, and a `message` is already\n * held repeatable — `providerFailure` puts an arbitrary `Error.message` into a *customer-facing*\n * `VettaError`. The cap is the backstop for the message we did not author.\n *\n * The name and the message are guaranteed rather than left to the stack: a `DOMException` carries its\n * whole answer in its name, and a workerd stack does not always repeat either of them — which is\n * exactly how the production line came out with frames and no reason at all.\n */\nexport function faultOf(error: unknown): string {\n if (!(error instanceof Error)) return `a non-Error ${typeof error} was thrown`;\n const head = `${error.name}: ${error.message}`;\n const stack = error.stack ?? \"\";\n const cause =\n error.cause instanceof Error\n ? ` | caused by ${error.cause.name}: ${error.cause.message}`\n : \"\";\n const body = stack.startsWith(head) ? stack : `${head}\\n${stack}`.trimEnd();\n // THE CAUSE IS RESERVED ITS ROOM BEFORE THE BODY SPENDS IT. Capping `body + cause` as one string\n // drops from the END, and the end is the cause — so on the one shape that most needs it, a\n // bundled worker's stack (every frame a one-line `index.js:1:NNNNN`, thousands of characters\n // before the first word of ours), the most diagnostic half was the first thing lost. The cause is\n // itself capped at half the line so that neither half can crowd the other out entirely: a real\n // cause is tens of characters and survives whole, and one long enough to be a payload still\n // leaves `head` and the top frames legible. The total is `FAULT_MAX_CHARS` either way.\n const room = cause.slice(0, FAULT_MAX_CHARS / 2);\n return `${body.slice(0, FAULT_MAX_CHARS - room.length)}${room}`;\n}\n\n/** The only error thrown across a boundary. SDKs subclass on `type`, branch on `code`. */\nexport class VettaError extends Error {\n readonly type: ErrorType;\n readonly code: ErrorCode;\n readonly httpStatus: number;\n readonly param: string | undefined;\n\n constructor(code: ErrorCode, message: string, param?: string) {\n super(message);\n this.name = \"VettaError\";\n const [type, httpStatus] = CODES[code];\n this.type = type;\n this.code = code;\n this.httpStatus = httpStatus;\n this.param = param;\n }\n\n toEnvelope(requestId: string): ErrorEnvelope {\n return {\n error: {\n type: this.type,\n code: this.code,\n message: this.message,\n request_id: requestId,\n ...(this.param === undefined ? {} : { param: this.param }),\n },\n };\n }\n}\n","/** Money — integer micro-USD everywhere on the wire and in storage (canonical-spec §1). */\n\nimport { VettaError } from \"./errors\";\n\nexport type MicroUsd = number & { readonly __brand: \"MicroUsd\" };\n\n/** 1 USD = 1_000_000 micro-USD. */\nexport const USD = 1_000_000;\n\nconst DECIMAL_USD = /^-?\\d+(?:\\.\\d+)?$/;\n\nfunction invalid(message: string): never {\n throw new VettaError(\"validation_failed\", message);\n}\n\n/** Brand a number as micro-USD. Rejects anything that is not a safe integer. */\nexport function microUsd(value: number): MicroUsd {\n if (!Number.isSafeInteger(value)) invalid(`micro-USD must be an integer within range, got ${value}`);\n return value as MicroUsd;\n}\n\nfunction fromBigInt(value: bigint): MicroUsd {\n if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {\n invalid(`micro-USD amount out of range: ${value}`);\n }\n return microUsd(Number(value));\n}\n\n/**\n * Decimal USD string -> integer micro-USD, rounding half-up (ties away from zero) exactly once.\n * `\"2.00\"` -> `2_000_000`. Clients convert here; a float dollar never reaches the wire.\n */\nexport function microFromDecimalString(usd: string): MicroUsd {\n const text = usd.trim();\n if (!DECIMAL_USD.test(text)) invalid(`not a decimal USD amount: ${usd}`);\n const negative = text.startsWith(\"-\");\n const [whole = \"0\", fraction = \"\"] = (negative ? text.slice(1) : text).split(\".\");\n const digits = fraction.padEnd(7, \"0\");\n let micro = BigInt(whole) * BigInt(USD) + BigInt(digits.slice(0, 6));\n if (Number(digits[6]) >= 5) micro += 1n;\n return fromBigInt(negative ? -micro : micro);\n}\n\n/** Integer micro-USD -> decimal USD string, for display only. Round-trips exactly. */\nexport function decimalStringFromMicro(amount: MicroUsd): string {\n const absolute = BigInt(Math.abs(amount));\n const fraction = (absolute % BigInt(USD))\n .toString()\n .padStart(6, \"0\")\n .replace(/0+$/, \"\")\n .padEnd(2, \"0\");\n return `${amount < 0 ? \"-\" : \"\"}${absolute / BigInt(USD)}.${fraction}`;\n}\n\nexport function addMicro(a: MicroUsd, b: MicroUsd): MicroUsd {\n return fromBigInt(BigInt(a) + BigInt(b));\n}\n\nexport function subMicro(a: MicroUsd, b: MicroUsd): MicroUsd {\n return fromBigInt(BigInt(a) - BigInt(b));\n}\n","/**\n * The audit action vocabulary (`canonical-spec.md §17`, PRODUCTION-READINESS #18).\n *\n * The compliance claim is \"every control-plane mutation is attributed to a principal and filed\".\n * Before this file the vocabulary held 11 P1 actions and zero P2 ones, so creating an agent, a\n * computer, a file, a webhook or a deployment — and the whole identity-and-credentials half of the\n * product — left no trace at all. A log that is trusted and incomplete is worse than no log.\n *\n * Two rules keep this list honest:\n * 1. **Never re-spell an action that has already been written.** Rows exist in customers' logs and\n * `?action=` filters exist in their queries. `agent.rolled_back` is therefore kept as a\n * deprecated alias of `agent.rollback` rather than renamed away.\n * 2. **Every action here is claimed by a route** in `coverage.ts`, and every mutating route either\n * claims an action or is listed there as deliberately unfiled. The gate proves both.\n */\n\n/** Actions already written by the deploy of 2026-08-22. Removing or re-spelling one breaks a query. */\nexport const AUDIT_ACTIONS_SHIPPED = [\n \"agent.updated\",\n \"agent.rolled_back\", // deprecated alias of `agent.rollback`; kept so historic rows still validate\n \"api_key.created\",\n \"api_key.rotated\",\n \"api_key.revoked\",\n \"member.role_changed\",\n \"member.removed\",\n \"policy.denied\",\n \"credits.topped_up\",\n \"webhook.secret_rotated\",\n \"session.interrupted\",\n] as const;\n\n/** P1: the control plane a customer pays for and an auditor asks about first. */\nexport const AUDIT_ACTIONS_P1 = [\n \"agent.created\",\n \"agent.deleted\",\n \"agent.rollback\",\n \"computer.created\",\n \"computer.deleted\",\n \"computer.paused\",\n \"computer.resumed\",\n \"computer.snapshot_created\",\n \"computer.updated\",\n \"computer.taken_over\",\n \"computer.handed_back\",\n \"browser.live_view_opened\",\n \"deployment.created\",\n \"deployment.updated\",\n \"deployment.deleted\",\n \"deployment.paused\",\n \"deployment.resumed\",\n \"deployment.run\",\n \"file.created\",\n \"file.published\",\n \"file.deleted\",\n \"member.invited\",\n \"org.updated\",\n \"subscription.updated\",\n \"subscription.canceled\",\n \"session.budget_updated\",\n \"session.cancelled\",\n \"skill.created\",\n \"skill.version_created\",\n \"skill.deleted\",\n \"webhook.created\",\n \"webhook.updated\",\n \"webhook.deleted\",\n] as const;\n\n/** P2: identity and credentials. Not one of these was recorded anywhere before this change. */\nexport const AUDIT_ACTIONS_P2 = [\n \"identity.created\",\n \"identity.updated\",\n \"identity.deleted\",\n \"identity.granted\",\n \"identity.revoked\",\n \"vault.created\",\n \"vault.deleted\",\n \"credential.sealed\",\n \"credential.destroyed\",\n \"connection.created\",\n \"connection.disconnected\",\n \"connection.auth_config_created\",\n \"connection.auth_config_deleted\",\n \"domain.created\",\n \"domain.purchased\",\n \"domain.purchase_refunded\",\n \"domain.verified\",\n \"domain.deleted\",\n \"email.created\",\n \"email.deleted\",\n \"phone.created\",\n \"phone.deleted\",\n \"social.activated\",\n \"social.post_created\",\n \"social.post_deleted\",\n] as const;\n\n/**\n * P3: apps — hosted web applications (`canonical-spec §29`), and the install that applies a\n * declaration across them (§29.6). The install's row is the only trace of *which writer* moved a\n * whole organization's configuration, so it is exactly the kind of mutation §17 exists for.\n */\nexport const AUDIT_ACTIONS_P3 = [\n \"app.created\",\n \"app.updated\",\n \"app.deleted\",\n \"app.deployed\",\n \"app.secret_set\",\n \"app.secret_deleted\",\n \"app.domain_connected\",\n \"app.domain_disconnected\",\n \"app.db_queried\",\n /** A ticket was minted that lets one browser past an app's own operator gate (§29.7). */\n \"app.entered\",\n /** The dashboard password was read — the one audited reveal of an app secret (§29.7, ADR-0656). */\n \"app.access_read\",\n /** The dashboard password was regenerated (and a lost `DASHBOARD_TOKEN` copy repaired). */\n \"app.access_rotated\",\n /** A link was minted that serves one file's bytes to anyone holding it, for seven days (§40). */\n \"file.linked\",\n \"blueprint.installed\",\n /** An install's answers were rewritten — what a template's crew is told about the business (§31.8). */\n \"blueprint.context_updated\",\n /** The one creator-program effect inside a tenant: a new organization attributed to a creator (§42.6). */\n \"referral.attributed\",\n] as const;\n\n/** Identity-owned legal, wallet and cards (`canonical-spec §43.4`, `§44.3`, `§45.3`). */\nexport const AUDIT_ACTIONS_PRIMITIVES = [\n \"legal_verification.started\",\n \"legal_member.completed\",\n \"legal_member.link_resent\",\n \"legal_company.created\",\n \"legal_company.submitted\",\n \"wallet.created\",\n \"wallet.policy_updated\",\n \"wallet.frozen\",\n \"wallet.unfrozen\",\n \"wallet.funded\",\n \"wallet.transferred\",\n \"wallet.swept\",\n \"wallet.paid\",\n \"card.issued\",\n \"card.retried\",\n \"card.cancelled\",\n \"card.refunded\",\n /** The one read that files: a credential left the vault for a caller (§45.3). */\n \"card.credentials_revealed\",\n] as const;\n\n// core-gaps: contracts — the mutations §32, §36–§38 make audit rows of (REST passthrough and object\n// puts/gets are audit rows, not stream events).\nexport const AUDIT_ACTIONS_CORE_GAPS = [\n \"browser.context_saved\",\n \"browser.context_granted\",\n \"browser.context_revoked\",\n \"browser.credential_stored\",\n // core-gaps: U2-browser-api — §32.8's session events, audit-only when no session drove them.\n \"browser.session_opened\",\n \"browser.session_closed\",\n \"file.imported\",\n \"app.db_rest\",\n \"app.db_migrated\",\n \"app.bucket_created\",\n \"app.bucket_deleted\",\n \"app.storage_put\",\n \"app.storage_get\",\n // core-gaps: U9-storage\n \"app.storage_deleted\",\n] as const;\n\nexport const AUDIT_ACTIONS = [\n ...AUDIT_ACTIONS_SHIPPED,\n ...AUDIT_ACTIONS_P1,\n ...AUDIT_ACTIONS_P2,\n ...AUDIT_ACTIONS_P3,\n ...AUDIT_ACTIONS_PRIMITIVES,\n ...AUDIT_ACTIONS_CORE_GAPS,\n] as const;\n\nexport type AuditAction = (typeof AUDIT_ACTIONS)[number];\n\n/** `agent.rolled_back` reads as `agent.rollback`; nothing else is aliased. */\nexport const AUDIT_ACTION_ALIASES: Readonly<Record<string, AuditAction>> = {\n \"agent.rolled_back\": \"agent.rollback\",\n};\n\n/** The spelling a filter should match on, collapsing a deprecated alias onto its canonical name. */\nexport function canonicalAction(action: string): string {\n return AUDIT_ACTION_ALIASES[action] ?? action;\n}\n","/** Shared wire primitives — every canonical object is built from these (canonical-spec §§1-2, §9, §11, §17). */\n\nimport { z } from \"zod\";\nimport { AUDIT_ACTIONS } from \"./audit-actions\";\nimport { isId, type IdPrefix } from \"../id\";\n\n/** A string that is a well-formed id of exactly this prefix. */\nexport const idOf = (prefix: IdPrefix): z.ZodString =>\n z.string().refine((value) => isId(prefix, value), { error: `expected a ${prefix}_ id` });\n\n/** RFC 3339 UTC, `_at` suffix on the wire (§9). */\nexport const Timestamp = z.iso.datetime({ offset: true });\n\n/** Integer micro-USD (§1). The `MicroUsd` brand is for arithmetic in `core`; the wire is an integer. */\nexport const MicroUsdField = z.number().int();\n\nexport const Metadata = z.record(z.string(), z.unknown());\n\n/**\n * A JSON Schema document for a session's answer (`output_schema`, §16).\n *\n * Constrained to an object schema with at least one property, because the schema *becomes* the\n * `submit_output` tool's parameters and a tool call's arguments are always a JSON object: a\n * `{\"type\":\"string\"}` schema can never be satisfied by any call, and a `{}` schema is satisfied by\n * everything. Both would end the session with a silent `structured_output: null` (or an empty\n * document) that `structured_output_required` cannot even catch — the exact failure §16 exists to\n * delete. Refuse them at the boundary instead.\n */\nexport const JsonSchemaDocument = z\n .record(z.string(), z.unknown())\n .refine((schema) => schema.type === \"object\", {\n error: 'an output schema must be a JSON Schema with \"type\": \"object\"',\n })\n .refine(\n (schema) =>\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n Object.keys(schema.properties).length > 0,\n { error: \"an output schema must declare at least one property\" },\n );\n\n/** Completion window — these three strings, everywhere (§4). */\nexport const WindowSchema = z.enum([\"immediate\", \"priority\", \"loose\"]);\nexport type Window = z.infer<typeof WindowSchema>;\n\n/** The five metered token tiers (§11). */\nexport const TOKEN_TIERS = [\"input\", \"cache_write\", \"cache_read\", \"output\", \"reasoning\"] as const;\nexport const TokenTierSchema = z.enum(TOKEN_TIERS);\n\n/**\n * The tiers a **non-model** call bills under (§11). `search` is one priced retrieval call, `media`\n * one priced media job — the tier name IS the component on `GET /v1/agents/{id}/spend?by=component`,\n * so these are capability names a customer reads, never vendor names.\n */\n// core-gaps: contracts — `browser` (minutes + hosted actions, §32.8), `storage` (bucket-days, §38.3).\n// `email` is one outbound email send (§11, ADR-0818).\nexport const TOOL_TIERS = [\"search\", \"media\", \"social\", \"browser\", \"storage\", \"email\"] as const;\nexport type ToolTier = (typeof TOOL_TIERS)[number];\n\n/**\n * Every tier a ledger line item can carry: the five token tiers, the sandbox (`computer`), and the\n * priced tool tiers. `packages/billing` has emitted `computer` since ADR-0160 while this enum still\n * only admitted the five, so a sandbox debit failed validation on `GET /v1/credits/ledger` — the\n * wire schema was narrower than the money the ledger already stored.\n */\nexport const LINE_ITEM_TIERS = [...TOKEN_TIERS, \"computer\", ...TOOL_TIERS] as const;\nexport const LineItemTierSchema = z.enum(LINE_ITEM_TIERS);\nexport type LineItemTier = z.infer<typeof LineItemTierSchema>;\nexport const TokenUsageSchema = z.object({\n input: z.number().int().nonnegative(),\n cache_write: z.number().int().nonnegative(),\n cache_read: z.number().int().nonnegative(),\n output: z.number().int().nonnegative(),\n reasoning: z.number().int().nonnegative(),\n});\nexport type TokenUsage = z.infer<typeof TokenUsageSchema>;\n\n/**\n * The acting actor, threaded through auth → every mutation, audit entry and ledger row (§17).\n *\n * `system` names an effect no API principal caused — a credit reconciled from a verified payment\n * webhook, the initial test-tier grant, a debit committed by the durable loop. Its `id` names the\n * subsystem (`\"payment_webhook\"`, `\"bootstrap\"`), never a stored object (ADR-0065).\n */\nexport const PrincipalSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"user\"), id: idOf(\"usr\") }),\n z.object({ type: z.literal(\"key\"), id: idOf(\"key\") }),\n z.object({ type: z.literal(\"system\"), id: z.string().min(1) }),\n]);\nexport type Principal = z.infer<typeof PrincipalSchema>;\n\n/**\n * The audited actions (§17). The list is `./audit-actions`: one definition, so what the wire\n * validates and what the emitters write cannot diverge.\n */\nexport const AuditActionSchema = z.enum(AUDIT_ACTIONS);\n\n/** Cursor pagination envelope (§9). */\nexport const page = <T extends z.ZodType>(item: T) =>\n z.object({ data: z.array(item), has_more: z.boolean(), next_cursor: z.string().nullable() });\nexport const PAGE_LIMIT_DEFAULT = 20;\nexport const PAGE_LIMIT_MAX = 100;\n\n/** The one supported API version; every surface reads it from here rather than re-declaring it (§9). */\nexport const API_VERSION = \"2026-09-30\";\n\n/**\n * Every `Vetta-Version` date a caller may pin, oldest first (§9). A date outside this list is a\n * typo or a guess, and answering it with a 200 served under some *other* version is exactly the\n * quiet-success class this surface exists to refuse — so `readVersion` 400s on it.\n */\nexport const API_VERSIONS = [\"2026-01-01\", \"2026-09-01\", API_VERSION] as const;\n\n/**\n * From this pin onward the request contract is **strict**: unknown body keys and unknown query\n * parameters are rejected rather than silently dropped (readiness entry 7). Older pins keep the\n * lenient behaviour so a client already sending junk is not broken by a deploy.\n */\nexport const STRICT_REQUEST_VERSION = \"2026-09-01\";\n\n/**\n * From this pin onward a question's fields may be `connect` (ADR-1102) and `media` (ADR-1103). An\n * older pin parses only `text` and `choice`, and strictly: one new field in one parked question\n * threw on its whole session list. So an older pin is served each new field as `text` (ADR-1105).\n */\nexport const QUESTION_KINDS_VERSION = \"2026-09-30\";\n\n/** Published event-replay window (§8). */\nexport const EVENT_RETENTION_HOURS = 72;\n","/**\n * The harness catalog — the one layer a customer selects at agent create (§19).\n *\n * `billing` is how the loop is paid for. `location` is where it can run. Hosted\n * sessions start only a hosted harness; a local one is stored and fails closed.\n */\n\nimport { z } from \"zod\";\n\nexport const HARNESS_IDS = [\"pi\", \"claude_code\", \"vetta\", \"hermes\"] as const;\nexport type HarnessId = (typeof HARNESS_IDS)[number];\n\nexport const HarnessIdSchema = z.enum(HARNESS_IDS);\n\n/**\n * The four facts an admission check can act on **today**, and no more (`CLAUDE.md §3`):\n *\n * - `approvals` — the loop can hold a tool call and wait for a decision on\n * `POST /v1/sessions/{id}/tool_confirmations` (§6). A loop without it cannot serve a toolset\n * whose permission is `ask`.\n * - `structuredOutput` — it can honour `structured_output_required` (§16).\n * - `streamingDeltas` — it emits incremental deltas rather than only a completed message (§8).\n * - `injectedTools` — THE PLATFORM'S TOOLS REACH THIS LOOP'S MODEL. Semantics, not mechanism: it\n * says the team tools (`send_to_agent`, `wait_for_agents`, `list_agents`, `board_read`,\n * `board_write`), an agent's `mcp_servers`, a connected account's tools, the Passport tools,\n * `social`, the app-declared MCP tools and `apps` are all offered to the model, governed by\n * `tools.configs`. There are TWO delivery mechanisms behind that one answer, and a caller should\n * not have to know which:\n * · an IN-ISOLATE loop reads `RuntimePort.runTurn`'s `input.tools` (`harness-pi/src/harness.ts`,\n * `harness-vetta/src/index.ts`);\n * · a PROCESS loop — a CLI in a micro-VM that carries its own toolset and could never read that\n * array — dials the session-scoped MCP bridge, `POST /v1/sandbox/mcp`, with the door token\n * already in its box. Which mechanism a harness uses is `RUNS_AS_A_PROCESS` below, and that\n * is the predicate `apps/runtime-do` gates its decorators on; it is NOT this field.\n * A `false` here is therefore still one fact with the same consequences — a coordinator cannot\n * run on such a loop, because its model would never be shown `send_to_agent` — but no published\n * harness declares it today.\n *\n * A `false` here is what lets a start refuse up front instead of promising behaviour the loop\n * cannot produce — the same fail-closed rule §4 applies to windows. Field names are TS\n * identifiers; the wire spells them `snake_case` like every other object (`code-standards §6`).\n */\nexport interface HarnessCapabilities {\n approvals: boolean;\n structuredOutput: boolean;\n streamingDeltas: boolean;\n injectedTools: boolean;\n}\n\n/**\n * Maturity, not place. `preview` says the loop runs but its contract may still move.\n *\n * `claude_code` is `ga` rather than a third `\"local\"` value: where a harness runs is already\n * `location`, and a `status` that answered the same question would be two fields to keep in\n * agreement — the day one changed, one of them would be wrong.\n */\nexport type HarnessStatus = \"ga\" | \"preview\";\n\n/**\n * WHAT A PARKED SESSION COSTS, WHICH IS NOT THE SAME QUESTION AS WHERE THE LOOP RUNS.\n *\n * `isolate` runs the loop in the session object itself: its workspace is rows in that object's own\n * storage, so a session between turns holds no sandbox and bills storage only. `sandbox` runs the\n * agent as a process on a micro-VM, which the session holds across turns — the same profile `pi`\n * has, and unavoidable for a harness that is a process rather than a loop we host.\n *\n * Published because it is a real difference in what a customer pays for an idle session, and\n * without it they would discover it from a bill rather than from the catalogue.\n */\nexport type HarnessExecution = \"isolate\" | \"sandbox\" | \"local\";\n\n/**\n * WHETHER THE HOSTED RUNTIME HAS A DISPATCHER FOR THIS LOOP — separate from `status`, and from\n * `location`, because it answers a different question: not \"how settled is the contract\" and not\n * \"whose machine runs it\", but \"will a session on it actually run today\".\n *\n * `vetta` is `preview` AND runnable; `hermes` is neither. Without this a session on a loop the\n * runtime refuses is admitted, queued, and then burns the turn engine's five-attempt retry ladder\n * on an error that can never succeed before parking as `failed` — minutes of a customer's time to\n * reach an answer we knew at start.\n */\n\nexport const HARNESSES = {\n pi: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Pi\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"ga\",\n capabilities: {\n approvals: true,\n structuredOutput: true,\n streamingDeltas: true,\n injectedTools: true,\n },\n },\n claude_code: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Claude Code\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /**\n * `approvals` IS THE LOAD-BEARING FALSE. The turn runs with `--permission-mode\n * bypassPermissions`, which is not a preference: measured, without it every tool call in\n * one-shot mode is DENIED outright — not prompted — and the turn still exits 0 having done\n * nothing. So nothing can hold a call for a decision, and `true` here would admit an `ask`\n * toolset and then bypass it in silence, which is the failure the catalogue exists to prevent.\n * `structured_output`: no schema is passed. `streaming_deltas`: the stream carries whole\n * assistant messages, never token deltas.\n *\n * `injectedTools` IS TRUE, AND NOT BECAUSE THE CLI LEARNED TO READ `input.tools` — it still\n * does not, and never will. `harness-claude-code-hosted` writes a per-turn MCP config in the\n * session's folder naming the session-scoped bridge and joins `--mcp-config …\n * --strict-mcp-config` to the command, so the platform's tools reach the model as MCP tools\n * of one server. `tools.configs` still governs them, by the same `server.tool` /\n * `<connector>.<tool>` names: the bridge applies `permissionOf` before it answers\n * `tools/list`, so a `deny` is never emitted and cannot be called. `approvals` staying\n * `false` is what makes an `ask` OMITTED rather than gated — nothing under\n * `bypassPermissions` can hold a call, so omission is the only honest enforcement, and\n * `startSession` still refuses an explicit `ask` toolset here outright.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n vetta: {\n execution: \"isolate\",\n runnable: true,\n label: \"Vetta\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /** `injectedTools`: `index.ts:284` spreads `input.tools` into the toolset it builds. */\n capabilities: {\n approvals: false,\n structuredOutput: true,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n hermes: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Hermes\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /**\n * BOTH `false`, AND BOTH WERE OPTIMISTIC. `approvals` claimed a gate that does not exist:\n * nothing connects `POST …/tool_confirmations` to the agent's own in-box prompt, and that\n * prompt is now closed with `</dev/null` so it fails immediately and SILENTLY. Declaring\n * `true` admitted an `ask` toolset and then dropped every approval with no event — the exact\n * \"quiet best effort\" the catalogue exists to prevent. `false` refuses such a session at start,\n * naming the field.\n *\n * `streamingDeltas` was true of an earlier invocation. The command now captures the agent's\n * answer and re-emits it as ONE `text` frame (`spec.ts`), because `chat -Q` writes a terminal\n * transcript rather than JSONL — so a caller gets `message.completed`, never a delta.\n *\n * `injectedTools` WAS THE THIRD FALSE AND IS NOW TRUE. It was never declared at all until it\n * had to be: the runtime wrapped this loop in `withTeamTools` like every other, and the five\n * team tools were registered against an adapter that never reads `input.tools`. A coordinator\n * on hermes was admitted, billed, and shown a toolset with no `send_to_agent` in it. The array\n * still goes nowhere — what changed is that `harness-hermes` now writes `$HERMES_HOME/\n * config.yaml` naming the session-scoped bridge (`POST /v1/sandbox/mcp`), so the platform's\n * tools reach the model as MCP tools of one server. `tools.configs` governs them by the same\n * names, because the bridge applies `permissionOf` before answering `tools/list` and a denied\n * tool is never emitted. `approvals` stays `false`, so an `ask` tool is omitted rather than\n * gated — the prompt in the box is closed with `</dev/null` and nothing can hold a call.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n} as const satisfies Record<\n HarnessId,\n {\n execution: HarnessExecution;\n runnable: boolean;\n label: string;\n billing: \"usage\" | \"account\";\n location: \"hosted\" | \"local\";\n status: HarnessStatus;\n capabilities: HarnessCapabilities;\n }\n>;\n\n/**\n * Harnesses whose AGENT IS A PROCESS IN THE BOX, rather than a loop we host that merely uses one.\n * They need a box whatever the tool policy says, and they need their own image — a stock one has no\n * agent installed on it.\n *\n * It lives beside the table rather than in `apps/api` because it is a fact about the harness, and\n * because the two places that provision a box now sit in different workers: `startSession` for a\n * session a customer starts, and the spawn path for a delegated member with no box to borrow (§28).\n *\n * IT IS ALSO THE MECHANISM GATE. `apps/runtime-do` asks this — not `capabilities.injectedTools` —\n * before it wraps a loop in `withTeamTools` and the other tool decorators, because those decorators\n * fill `RuntimePort.runTurn`'s `input.tools` and only an in-isolate loop reads it. A process loop\n * is served the same tools out of band, over the session-scoped MCP bridge. The two questions used\n * to have the same answer and no longer do: this set is the mechanism, `injectedTools` is whether\n * the tools arrive at all, and it is now `true` for every published harness.\n */\nexport const RUNS_AS_A_PROCESS = new Set<HarnessId>([\"hermes\", \"claude_code\"]);\n\n/** Picker-only. Not on the wire until an adapter exists. */\nexport const COMING_SOON = [\n { id: \"codex\", label: \"Codex\" },\n { id: \"cursor\", label: \"Cursor\" },\n { id: \"opencode\", label: \"OpenCode\" },\n] as const;\n\nexport function parseHarness(value: string): HarnessId | undefined {\n const parsed = HarnessIdSchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nexport function isHosted(id: HarnessId): boolean {\n return HARNESSES[id].location === \"hosted\";\n}\n\nexport function harnessOption(id: HarnessId): string {\n const spec = HARNESSES[id];\n const bill = spec.billing === \"usage\" ? \"Vetta usage-based\" : \"your logged-in account\";\n const place = spec.location === \"hosted\" ? \"hosted\" : \"local CLI\";\n return `${spec.label} — ${bill}, ${place}`;\n}\n","/**\n * Agents, immutable agent versions, and the one toolset schema (canonical-spec §6, §12, §13).\n * The layer an agent selects is its **harness** — never its runtime, which is the metered\n * infrastructure we provide and not a parameter (canonical-spec §19).\n */\n\nimport { z } from \"zod\";\nimport {\n JsonSchemaDocument,\n Metadata,\n MicroUsdField,\n PrincipalSchema,\n Timestamp,\n WindowSchema,\n idOf,\n} from \"./common\";\nimport { BrowserOptionsSchema } from \"./browser\";\nimport { HarnessIdSchema } from \"./harness\";\nimport { ModelSelectionPolicySchema } from \"./model-selection\";\nimport type { SessionMode } from \"./session\";\n\n/** `allow` runs silently · `ask` pauses · `deny` never offers the tool to the model (§6). */\nexport const ToolPermissionSchema = z.enum([\"allow\", \"ask\", \"deny\"]);\nexport type ToolPermission = z.infer<typeof ToolPermissionSchema>;\n\n/**\n * Built-in P1 tools — the names an agent's `configs` may govern. External tools register through\n * the same shape (§6). `bash`, `read`, `write`, `edit`, `ls` and `find` are the harness's own\n * sandbox tools; `browser`, `read_skill`, `publish_file`, `web_search`, `web_fetch`,\n * `generate_image` and `generate_video` are Vetta's (ADR-0102, ADR-0275, ADR-0277). A customer can\n * only deny a tool it can name, so this list is the tool surface, not a subset of it — and that is\n * why the six team tools (§28) are here even though only an agent with a roster or a room seat is\n * ever offered one: a name that cannot be written into `configs` cannot be denied.\n *\n * It is also what makes a built-in **default-on**: the runtime never reads this constant, but the\n * CLI and the dashboard write `enabled:false` for every name *not* in it, so a tool omitted here is\n * silently denied everywhere except the raw API.\n */\nexport const BUILTIN_TOOLS = [\n \"bash\",\n \"read\",\n \"write\",\n \"edit\",\n \"ls\",\n \"find\",\n \"browser\",\n \"read_skill\",\n \"publish_file\",\n \"web_search\",\n \"web_fetch\",\n \"generate_image\",\n \"generate_video\",\n \"clip_video\",\n \"apps\",\n \"send_to_agent\",\n \"wait_for_agents\",\n \"list_agents\",\n \"post_to_channel\",\n \"board_read\",\n \"board_write\",\n \"ask_operator\",\n \"request_tools\",\n \"project_context\",\n // core-gaps: contracts — names only (`canonical-spec §35.3`, §36.3, §39); U6/U7/U10 add the modules.\n \"transcribe_audio\",\n \"generate_speech\",\n \"find_files\",\n // The read half of the library: `find_files` answers WHICH images exist, this one shows them\n // (§16.2, ADR-0758). Separate names because only one of the two costs context.\n \"view_image\",\n // The write half: `view_image` shows the model a file, this one puts it on the box's DISK so\n // bash can work on the bytes (ffmpeg joining a long-form render, say). The exact inverse of\n // `publish_file`, and the first way anything the platform itself produced could be read back.\n \"fetch_file\",\n \"find_stock_photo\",\n \"session_spend\",\n // A view the chat draws — spend, post views, the roadmap, the week ahead — read by code (§48).\n \"show\",\n // A card the model lays out, every number bound to a source code reads (§49).\n \"compose\",\n // Plan mode's two (§7.5): offered only to a session in plan mode or holding a plan.\n \"write_plan\",\n \"propose_plan\",\n] as const;\n\n/**\n * The tools the Effect ledger (`canonical-spec §19`, ADR-0822) runs again on a replay instead of\n * answering from its record, because the record would describe a world the replay has changed:\n *\n * - the effect is held by the turn and written at its commit, so a failed attempt lost it — the\n * thread `send_to_agent` queues, the park `wait_for_agents` asks for;\n * - the effect depends on state the arguments do not name, which the replay may have rewritten —\n * the box's files `publish_file` and `apps` read, the live page `browser` acts on.\n */\nexport const UNJOURNALED_TOOLS: ReadonlySet<string> = new Set([\n \"send_to_agent\",\n \"wait_for_agents\",\n \"publish_file\",\n \"apps\",\n \"browser\",\n]);\n\n/**\n * The platform's own namespaced tools — Vetta's, not a declared server's or a connected app's. They\n * ride on the session's identity and are offered only when it owns what they reach: an inbox\n * (§24.9), a social workspace (§27), the connections layer (§25). Named here so a dashboard can\n * tell them from an external `server.tool` it cannot enumerate; `isToolName` already admits them\n * by shape, so this list widens nothing on the wire.\n */\nexport const PLATFORM_TOOLS = [\n \"email.inboxes\",\n \"email.read\",\n \"email.send\",\n \"social.accounts\",\n \"social.post\",\n \"social.status\",\n \"social.post_metrics\",\n \"connections.search\",\n \"connections.connect\",\n \"connections.status\",\n \"legal.verifications\",\n \"legal.verification\",\n \"legal.companies\",\n \"legal.company\",\n \"legal.documents\",\n \"legal.naics\",\n \"legal.verify\",\n \"legal.resend_link\",\n \"legal.form\",\n \"legal.submit\",\n \"wallet.balance\",\n \"wallet.transactions\",\n \"wallet.receipts\",\n \"wallet.quote\",\n \"wallet.pay\",\n \"wallet.transfer\",\n \"card.list\",\n \"card.show\",\n \"card.quote\",\n \"card.transactions\",\n \"card.spend\",\n \"card.issue\",\n \"card.credentials\",\n \"card.cancel\",\n // The company's timezone (§20.6, ADR-0904): offered to every session; asks unless the owner sets it to allow.\n \"company.set_timezone\",\n // The company's logo (§20.7, ADR-1085): offered to every session; asks unless the owner sets it to allow.\n \"company.set_logo\",\n // An app's key (§29.10, ADR-1004): minted only when a person approves the card that lists it.\n \"apps.request_access\",\n] as const;\n\n/**\n * Platform tools that publish, spend, file, reveal or change the company's settings, and therefore\n * default to `ask` unless the toolset says otherwise (§20.6, §27, §43.5, §44.4, §45.4). One list, so a bridge and a harness agree.\n */\nexport const ASK_BY_DEFAULT_TOOLS: ReadonlySet<string> = new Set([\n \"social.post\",\n \"email.send\",\n \"legal.verify\",\n \"legal.resend_link\",\n \"legal.form\",\n \"legal.submit\",\n \"wallet.pay\",\n \"wallet.transfer\",\n \"card.issue\",\n \"card.credentials\",\n \"card.cancel\",\n \"company.set_timezone\",\n \"company.set_logo\",\n \"apps.request_access\",\n]);\n\n/**\n * The control plane's tools that spend money, move value or act in the outside world: the `SPENDS`\n * routes of `apps/api/src/mcp-tools.ts`, by tool name (a test there keeps the two equal).\n */\nexport const SPENDS_OR_PUBLISHES: ReadonlySet<string> = new Set([\n \"connections_connect\",\n \"creator_publish_template\",\n \"creator_request_payout\",\n \"credits_create_subscription\",\n \"credits_create_topup\",\n \"domains_purchase\",\n \"identities_cancel_card\",\n \"identities_create_company\",\n \"identities_create_post\",\n \"identities_issue_card\",\n \"identities_pay\",\n \"identities_resend_member_link\",\n \"identities_reveal_credentials\",\n \"identities_send_email\",\n \"identities_send_sms\",\n \"identities_start_verification\",\n \"identities_submit_company\",\n \"identities_transfer\",\n \"media_create_clip\",\n \"media_create_conversation\",\n \"media_create_speech\",\n \"media_create_transcription\",\n \"media_generate_image\",\n \"media_generate_video\",\n]);\n\n/** A control-plane call each person sees: it spends money or acts in the outside world. Any server's name. */\nconst seenEachTime = (name: unknown): boolean =>\n typeof name === \"string\" && [...SPENDS_OR_PUBLISHES].some((tool) => name === tool || name.endsWith(`.${tool}`) || name.endsWith(`__${tool}`));\n\n/**\n * Whether a tool may be granted for the rest of a chat (§7.3). Not one that publishes, pays or\n * files: a grant runs every later call with no card, and the model rewrites the arguments (ADR-0810).\n * That holds for the control plane's own such tools too, called directly or through the invoker\n * (`args.tool`). Nor a pause\n * (`asksAPerson`): a question, a toolset change or a plan is answered each time. Nor a template\n * install: each one hires a crew, so each is its own card (ADR-1104).\n */\nexport const grantable = (name: string, args: Record<string, unknown> = {}): boolean =>\n !ASK_BY_DEFAULT_TOOLS.has(name) &&\n !asksAPerson(name) &&\n !namesInstall(name) &&\n !seenEachTime(name) &&\n !(invokesAnyTool(name) && (namesInstall(args[\"tool\"]) || seenEachTime(args[\"tool\"])));\n\n/**\n * Tools no policy can set to `allow` (`permissionOf`): each call is a signed-in owner's or admin's\n * decision. The logo is here because its API write is admin-only (ADR-1086): a member must not\n * change what every member sees by approving the agent's call.\n */\nexport const ALWAYS_ASKS: ReadonlySet<string> = new Set([\"apps.request_access\", \"company.set_logo\"]);\n\n/**\n * The tool that asks a person something (§7.1). Named here rather than spelled inline at each of\n * its reading sites, because `permissionOf` below has to recognise it and a typo there would\n * silently hand a model a tool that runs without ever asking anyone.\n */\nexport const ASK_OPERATOR = \"ask_operator\";\n\n/** The tool that proposes a change to this agent's own toolset (§7.4). Same rule, same reason. */\nexport const REQUEST_TOOLS = \"request_tools\";\n\n/** Plan mode's tools (§7.5): the compare-and-set on the plan, and the card that asks to build it. */\nexport const WRITE_PLAN = \"write_plan\";\nexport const PROPOSE_PLAN = \"propose_plan\";\n\n/**\n * The built-ins that ARE a pause: a person answers them, so none can ever be `allow`. `propose_plan`\n * is here because its allow is what leaves plan mode (§7.5): run unasked, it would record an\n * approval nobody gave and leave the session planning.\n */\nexport const asksAPerson = (name: string): boolean =>\n name === ASK_OPERATOR || name === REQUEST_TOOLS || name === PROPOSE_PLAN;\n\n/**\n * The control plane's tool invoker (`apps/api/src/mcp-meta.ts`): ONE tool that runs any of the\n * catalogue's 240, chosen by an argument, so it is enabled `allow` and the card is decided per\n * call from what it is invoking. Named here because two layers must recognise it and neither may\n * guess: the harness asks before a write (`harness-pi/src/catalogue.ts`), and a `scope: \"session\"`\n * grant for it is keyed on the TARGET in `args.tool` (`harness-pi/src/approvals.ts`) — a grant is\n * one tool name, and this name is every tool, so a grant for the bare invoker is dropped rather\n * than read as a standing licence to write anything for the rest of the chat with no card at all.\n *\n * Namespaced, because an MCP tool is `server.tool` and the server is the customer's to name.\n */\nexport const TOOLS_EXECUTE = \"tools_execute\";\n\n/** Its other half: the catalogue, searched instead of carried (`apps/api/src/mcp-meta.ts`). */\nexport const TOOLS_SEARCH = \"tools_search\";\n\n/**\n * The control-plane tools the CEO carries directly, beside the two above; the rest of the catalogue\n * it reaches only through `TOOLS_EXECUTE`. Why each one is here is `apps/web/app/lib/orchestrator.server.ts`.\n * It lives here because the catalogue's own descriptions have to agree with it: a carried tool's\n * description that names a sibling the CEO cannot call directly reads as \"call it directly\", and\n * the model did — `vetta__blueprints_list_installs`, answered \"not found\" (ADR-1025). The API's test\n * reads this list against the published descriptions (`apps/api/src/mcp-meta.test.ts`).\n */\nexport const ORCHESTRATOR_CORE_TOOLS = [\n \"agents_list\",\n \"agents_get\",\n \"sessions_create\",\n \"sessions_get\",\n \"sessions_list\",\n \"sessions_list_events\",\n \"files_list\",\n \"credits_get_balance\",\n \"blueprints_list_artifacts\",\n \"blueprints_list_installs\",\n \"blueprints_get_context\",\n] as const;\n\nexport const invokesAnyTool = (name: string): boolean =>\n name === TOOLS_EXECUTE || name.endsWith(`.${TOOLS_EXECUTE}`) || name.endsWith(`__${TOOLS_EXECUTE}`);\n\n/** The template install (§31): the one held call whose `answers` a person may edit as they approve it (ADR-1030). */\nexport const INSTALL_TOOL = \"blueprints_apply_install\";\n\n/** Bare, namespaced (`vetta.…`) or in the MCP spelling (`vetta__…`) the invoker also runs (`bareToolName`). */\nconst namesInstall = (name: unknown): boolean =>\n typeof name === \"string\" && (name === INSTALL_TOOL || name.endsWith(`.${INSTALL_TOOL}`) || name.endsWith(`__${INSTALL_TOOL}`));\n\n/**\n * A held call read as a template install — called directly or through the invoker, whose target's\n * arguments sit in `arguments` — or `null` for any other call. `answered` is the same call with its\n * `answers` replaced and nothing else touched: the one edit an approval may carry (§7, ADR-1030).\n */\nexport function installCall(\n name: string,\n args: Record<string, unknown>,\n): { args: Record<string, unknown>; answered: (answers: Record<string, unknown>) => Record<string, unknown> } | null {\n if (namesInstall(name)) return { args, answered: (answers) => ({ ...args, answers }) };\n const inner = args[\"arguments\"];\n if (!invokesAnyTool(name) || !namesInstall(args[\"tool\"]) || typeof inner !== \"object\" || inner === null || Array.isArray(inner)) return null;\n const own = inner as Record<string, unknown>;\n return { args: own, answered: (answers) => ({ ...args, arguments: { ...own, answers } }) };\n}\n\n/**\n * Is this a tool name a `configs` key may govern?\n *\n * A built-in, or a **namespaced** `<namespace>.<tool>` — the form every tool that is not built in\n * registers under: a connection contributes `<connector>.<tool>` (`tracker.get_issue`) and an MCP\n * server contributes `<server>.<tool>` (`vetta.agents_create`), both documented as `tools.configs`\n * keys (`docs/capabilities/tools.mdx`). The namespace cannot be enumerated ahead of time — it comes\n * from the org's live connections — so the check is on the *shape*, which is still enough to catch\n * the typo it exists for: a bare name that is not a built-in is refused.\n */\nexport const isToolName = (name: string): boolean =>\n (BUILTIN_TOOLS as readonly string[]).includes(name) || /^[a-z0-9_-]+(\\.[a-z0-9_-]+)+$/i.test(name);\n\nexport const ToolConfigSchema = z.object({\n enabled: z.boolean(),\n permission: ToolPermissionSchema,\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * The toolset wrapper — the only `tools` schema (§6).\n *\n * Every tool's `config` is open — the web filters, the media pins and `apps.allowed_apps` are all\n * read leniently at the catalogue — except `browser`'s, which is the browser option object\n * (§32.2, `BrowserOptionsSchema`): the runtime answers a malformed one with a browser that reaches\n * nothing, a refusal the author would never see, so it is refused here, by field, wherever a toolset\n * is written (`POST/PATCH /v1/agents`, the CLI, a blueprint). Validated, not parsed: the stored\n * config keeps exactly the keys the author wrote, and the defaults are applied where it is read.\n */\nexport const ToolsetSchema = z\n .object({\n default_config: z.object({ permission: ToolPermissionSchema }),\n configs: z.record(z.string(), ToolConfigSchema),\n })\n .superRefine((tools, ctx) => {\n const config = tools.configs[\"browser\"]?.config;\n if (config === undefined) return;\n for (const issue of BrowserOptionsSchema.safeParse(config).error?.issues ?? []) {\n ctx.addIssue({ code: \"custom\", message: issue.message, path: [\"configs\", \"browser\", \"config\", ...issue.path] });\n }\n });\nexport type Toolset = z.infer<typeof ToolsetSchema>;\n\n/**\n * The agent's policy for one tool. An unlisted tool takes `default_config.permission`, so a tool a\n * harness builds itself is governed by the same rule as one the platform injects (§6).\n *\n * IT LIVES IN `core` BECAUSE THREE DELIVERY PATHS APPLY IT and a tool reaching a model outside this\n * filter is a security hole: `harness-pi`'s catalogue gates its own tools with it, the session tool\n * bridge (`apps/runtime-do/src/bridge.ts`) filters what a boxed CLI is offered with it, and\n * `harness-vetta` filters the modules it is handed with it. Three copies is how one of them comes\n * to disagree, so there is one.\n */\nexport function permissionOf(toolset: Toolset): (name: string) => ToolPermission {\n return (name) => {\n const config = toolset.configs[name];\n if (config?.enabled === false) return \"deny\";\n /**\n * `ask_operator` HAS NO `allow`, and that one line is what makes it safe everywhere else.\n * The tool *is* the pause: running it without stopping the turn would be a tool that asked\n * nobody and returned nothing, so `allow` is not a coherent policy for it and collapses to\n * `ask`. `deny` still forbids an agent to ask at all, from either level.\n *\n * The other two delivery paths keep only what this function calls `allow` — the session tool\n * bridge (`apps/runtime-do/src/bridge.ts`) and `harness-vetta`'s `injected` — so they drop it\n * without either of them naming it. That is the point: neither can hold a `tools/call` open\n * for the hours an answer takes (ADR-0400), and being unable to say `allow` here is a stronger\n * guarantee than a second copy of the rule in each of them.\n */\n if (asksAPerson(name)) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // A key for an app is approved one card at a time, whatever the policy says (ADR-1009): with\n // `allow` an agent would mint its own keys with no person asked. `deny` still forbids it.\n if (ALWAYS_ASKS.has(name)) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // Publishing, spending, filing and revealing default to approval; an explicit per-tool policy still wins.\n return config?.permission ?? (ASK_BY_DEFAULT_TOOLS.has(name) ? \"ask\" : toolset.default_config.permission);\n };\n}\n\n/**\n * What plan mode offers besides a tool whose module published `readOnly: true` (§7.5): asking,\n * the plan's two tools, and reading — the box, the web, the board, the roster, the library.\n */\nexport const PLAN_READ_ONLY: ReadonlySet<string> = new Set([\n ASK_OPERATOR,\n WRITE_PLAN,\n PROPOSE_PLAN,\n \"read\",\n \"ls\",\n \"find\",\n \"web_search\",\n \"web_fetch\",\n \"board_read\",\n \"list_agents\",\n \"read_skill\",\n \"find_files\",\n \"view_image\",\n \"session_spend\",\n \"project_context\",\n]);\n\n/**\n * PLAN MODE, AS A POLICY OVER THE AGENT'S OWN (§7.5). It only narrows: in plan mode a tool that is\n * neither on `PLAN_READ_ONLY` nor read-only by its own published hint is `deny`, which every\n * delivery path already reads as \"never built, never offered\". Everything else answers to `policy`\n * unchanged, so an agent that denies `web_search` still has none while planning.\n *\n * A FUNCTION, NOT A TOOLSET. A narrowed `Toolset` would be written back into the session's pin\n * (`runtime-do loop.ts` keeps a grant that way) and read off storage by the bridge, so plan mode\n * would outlive itself. Applied at each `permissionOf` site: the pi catalogue, the bridge and\n * `harness-vetta`. `readOnly` is the site's own knowledge of its modules.\n */\nexport function planPolicy(\n mode: SessionMode,\n policy: (name: string) => ToolPermission,\n readOnly: (name: string) => boolean,\n): (name: string) => ToolPermission {\n return (name) => {\n // THE PLAN'S OWN TWO ANSWER TO NO DEFAULT. An agent whose default is `deny` would otherwise plan\n // with no way to write the plan or put it to anyone, and one whose default is `ask` would park a\n // card on every write. They are only offered where a plan applies (`runtime-do plan.ts`).\n if (name === WRITE_PLAN) return \"allow\";\n if (name === PROPOSE_PLAN) return \"ask\";\n if (mode === \"build\") return policy(name);\n return PLAN_READ_ONLY.has(name) || readOnly(name) ? policy(name) : \"deny\";\n };\n}\n\n/**\n * Does this toolset carry an `ask_operator` a harness with no approval seam would have to serve?\n *\n * Read by NAME, and only when the toolset NAMES IT. `permissionOf` collapses `allow` to `ask` for\n * this tool, so a toolset that never mentions it still answers `ask` — and a gate that read the\n * bare answer would refuse every session and every roster on `hermes` and `claude_code` over a\n * capability their loops never publish (`bridge.ts` and `harness-vetta` keep only `allow`).\n *\n * It lives here because two gates ask it — `startSession` before any spend, and roster admission\n * one save earlier — and they were written apart: the roster's asked only about a literal\n * `permission: \"ask\"`, which `ask_operator` never carries, so a member configured with it saved\n * clean and then had the tool silently dropped at delegation instead of being refused. Two gates\n * asking one question is how one of them comes to answer it differently.\n */\nexport const asksOperator = (toolset: Toolset): boolean =>\n [ASK_OPERATOR, REQUEST_TOOLS].some(\n (name) => toolset.configs[name] !== undefined && permissionOf(toolset)(name) !== \"deny\",\n );\n\n/**\n * The `computerId` a session's tools are built against before its sandbox exists. A box is bought\n * by the first tool call that needs one, never at `POST /v1/sessions` (ADR-0099 → `box.ts`), so\n * until then this stands in for the id and the gated compute port swaps it for the real one. A\n * tool that only *records* the id (the browser) must treat it as \"no box yet\", not as a box.\n */\nexport const PENDING_BOX = \"pending\";\n\nexport const BudgetSchema = z.object({\n cap_micro_usd: MicroUsdField.nonnegative(),\n max_task_micro_usd: MicroUsdField.nonnegative(),\n period: z.enum([\"day\", \"week\", \"month\"]),\n});\n\n/**\n * `slug` floats to the latest version at session start; `slug@N` is an immutable pin (§13). A\n * `naive/` prefix addresses the platform's catalogue (§31.9) instead of the organization's skills;\n * `naive/` alone names nothing.\n */\nexport const SkillRefSchema = z.string().regex(/^(naive\\/)?[a-z0-9][a-z0-9-]*(@\\d+)?$/, {\n error: \"expected `slug`, `slug@N`, `naive/slug` or `naive/slug@N`\",\n});\n\nexport const McpServerSchema = z.object({\n name: z.string(),\n url: z.url(),\n headers: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * One roster member of a team (§28). Four forms, and the bare `agt_…` string normalises to the\n * object form **at parse**, so exactly one shape reaches storage, validation and the response —\n * nothing downstream has to ask \"which spelling is this\".\n *\n * `self` is the coordinator delegating to a copy of itself; `advisor` is a bare model with no agent\n * behind it, so it names a `model` instead of an `id`.\n */\nexport const RosterEntrySchema = z.union([\n idOf(\"agt\").transform((id) => ({ type: \"agent\" as const, id })),\n z.object({\n type: z.literal(\"agent\"),\n id: idOf(\"agt\"),\n version: z.number().int().positive().optional(),\n }),\n z.object({ type: z.literal(\"self\") }),\n z.object({ type: z.literal(\"advisor\"), model: z.string().min(1) }),\n]);\nexport type RosterEntry = z.infer<typeof RosterEntrySchema>;\n\n/** A roster names at most one of each of these: they are singletons, not addressable members. */\nconst SINGLETON_ENTRIES = [\"self\", \"advisor\"] as const;\n\n/** The coordinator declaration. `board` opts into the shared board; its columns are fixed (§28). */\nexport const MultiagentSchema = z.object({\n type: z.literal(\"coordinator\"),\n agents: z\n .array(RosterEntrySchema)\n .min(1)\n .max(20)\n .refine(\n (roster) => SINGLETON_ENTRIES.every((t) => roster.filter((e) => e.type === t).length <= 1),\n { error: \"a roster carries at most one `self` and at most one `advisor` entry\" },\n ),\n board: z.boolean().optional(),\n});\nexport type Multiagent = z.infer<typeof MultiagentSchema>;\n\n/**\n * `multiagent` on the wire. `null` is required, not cosmetic: the coordinator echoes\n * `\"multiagent\": null` on every non-coordinator agent, and a `PATCH` of `null` is how a roster is\n * cleared — which `false` cannot say, because `false` is also the create-time default.\n */\nexport const MultiagentField = z.union([z.boolean(), MultiagentSchema, z.null()]);\nexport type MultiagentConfig = z.infer<typeof MultiagentField>;\n\n/** The one reading of the three arms: is there a team here, and what is it? */\nexport function normaliseMultiagent(value: MultiagentConfig): Multiagent | null {\n if (value === true) return { type: \"coordinator\", agents: [], board: false };\n if (value === false || value === null) return null;\n return value;\n}\n\n/**\n * `handoffs` on the wire (§28.12): who this agent may `send_to_agent`. `true` — any agent of\n * the organization; `false` — nobody, and none of the agent tools are offered; `\"team\"` — the agents\n * on its own `multiagent` roster; a list of agent **names** — those. Every policy but `false` also\n * reaches the CEO (`handoffAllows`). The create-time default is `true`, and a version minted before\n * the field existed reads as `true` (`handoffsOf`), so an agent nobody configured can reach anyone.\n */\nexport const HandoffsField = z.union([z.boolean(), z.literal(\"team\"), z.array(z.string().min(1)).max(50)]);\nexport type Handoffs = z.infer<typeof HandoffsField>;\n\n/** The field as every reader takes it: absent is `true`. */\nexport const handoffsOf = (config: { handoffs?: Handoffs | undefined }): Handoffs => config.handoffs ?? true;\n\n/** Whether the agent tools are offered at all: only `false` opts out, since `[]` still reaches the CEO. */\nexport const handoffsEnabled = (handoffs: Handoffs): boolean => handoffs !== false;\n\n/**\n * Whether `name` is a seat this policy lets the agent reach — never itself (§28.15). `team` is the\n * roster as names, which only the caller can resolve; under any other policy it is not read. `ceo`\n * is the name of the org's agent marked `ORCHESTRATOR_ROLE` (or `null` if there is none): every\n * policy but `false` reaches it, named or not (§28.12, ADR-0842).\n */\nexport const handoffAllows = (\n handoffs: Handoffs,\n self: string,\n name: string,\n team: readonly string[],\n ceo: string | null,\n): boolean =>\n name !== self &&\n handoffs !== false &&\n (handoffs === true || name === ceo || (handoffs === \"team\" ? team : handoffs).includes(name));\n\n/** The config carried by an agent and frozen into every version (§12). */\nconst agentConfigShape = {\n model: z.string(),\n window: WindowSchema,\n system: z.string(),\n tools: ToolsetSchema,\n mcp_servers: z.array(McpServerSchema),\n skills: z.array(SkillRefSchema),\n multiagent: MultiagentField,\n /** Optional on the type so a version minted before §28.15 still parses; read it through `handoffsOf`. */\n handoffs: HandoffsField.optional(),\n /** §46.6: when set, every turn picks one of its options and `model` is the default. Absent before it existed. */\n model_selection: ModelSelectionPolicySchema.nullable().optional(),\n budget: BudgetSchema,\n output_schema: JsonSchemaDocument.nullable(),\n structured_output_required: z.boolean(),\n description: z.string().nullable(),\n metadata: Metadata,\n};\n\n/** An immutable agent version. A no-op change mints nothing (§12). */\nexport const AgentVersionSchema = z.object({\n version: z.number().int().positive(),\n created_at: Timestamp,\n created_by: PrincipalSchema,\n ...agentConfigShape,\n});\nexport type AgentVersion = z.infer<typeof AgentVersionSchema>;\n\nexport const AgentSchema = z.object({\n id: idOf(\"agt\"),\n object: z.literal(\"agent\"),\n name: z.string(),\n /** The agent loop this agent runs (§19). Chosen at create; the catalog lives in `harness.ts`. */\n harness: HarnessIdSchema,\n current_version: z.number().int().positive(),\n created_at: Timestamp,\n ...agentConfigShape,\n});\nexport type Agent = z.infer<typeof AgentSchema>;\n","/**\n * core-gaps: contracts — the managed browser's wire objects (`canonical-spec §32`). One option\n * object read by `POST /v1/computers`, the `browser` tool's config and `browser_session`.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\nimport { RoleSchema } from \"./org\";\n\n/** D2: the cap stays 360 minutes. */\nexport const BROWSER_MAX_TIMEOUT_MINUTES = 360;\nexport const BROWSER_REGIONS = [\"us-west\", \"us-east\", \"eu-central\", \"ap-southeast\"] as const;\nexport const BROWSER_OS = [\"windows\", \"mac\", \"linux\", \"mobile\", \"tablet\"] as const;\n/** The `browser` tool's `action` names (§32.7): the §32.4 page actions plus the saved-login flows. */\nexport const BROWSER_TOOL_ACTIONS = [\n \"goto\",\n \"click\",\n \"type\",\n \"extract\",\n \"act\",\n \"observe\",\n \"links\",\n \"screenshot\",\n \"login\",\n \"signup\",\n \"save_context\",\n] as const;\n\n/**\n * `allowed_domains` is a *narrowing* control, not a grant: omit it and the browser reaches the whole\n * public web. It is not what keeps the browser off private infrastructure — `isBlockedHost` bars\n * loopback, private, link-local and cloud-metadata hosts on every action regardless of this list, so\n * the open default widens reach to the public internet only. An explicit `[]` is still refused: a\n * caller who names the field means to bound it, and silently reaching nothing is the trap this\n * default exists to avoid.\n *\n * `proxy: true` with a `\"*\"` allowlist is refused: residential egress needs a bounded destination,\n * and because `\"*\"` is now the default, a proxied browser must name its domains outright.\n * `ask_actions` is read by the `browser` tool alone: with the tool at `allow`, a call whose action is\n * listed pauses for approval and every other one runs (§32.7).\n */\nexport const BrowserOptionsSchema = z\n .object({\n allowed_domains: z.array(z.string().min(1)).min(1).default([\"*\"]),\n timeout_minutes: z.number().int().min(1).max(BROWSER_MAX_TIMEOUT_MINUTES).default(15),\n region: z.enum(BROWSER_REGIONS).default(\"us-west\"),\n keep_alive: z.boolean().default(false),\n viewport: z\n .object({ width: z.number().int().positive(), height: z.number().int().positive() })\n .optional(),\n os: z.enum(BROWSER_OS).optional(),\n block_ads: z.boolean().default(false),\n solve_captchas: z.boolean().default(true),\n stealth: z.boolean().default(false),\n allow_writes: z.boolean().default(false),\n allow_extract: z.boolean().default(false),\n context_name: z.string().min(1).max(64).optional(),\n persist_context: z.boolean().default(false),\n human_login: z.boolean().default(false),\n proxy: z.boolean().default(false),\n ask_actions: z.array(z.enum(BROWSER_TOOL_ACTIONS)).default([\"signup\"]),\n })\n .refine((options) => !(options.proxy && options.allowed_domains.includes(\"*\")), {\n error: \"a proxied browser needs a bounded allow-list, not *\",\n path: [\"proxy\"],\n });\nexport type BrowserOptions = z.infer<typeof BrowserOptionsSchema>;\n// core-gaps: U2-browser-api — what a caller sends: every field may be omitted.\nexport type BrowserOptionsInput = z.input<typeof BrowserOptionsSchema>;\n\nexport const BrowserSessionStatusSchema = z.enum([\"creating\", \"active\", \"closed\", \"error\"]);\n\nexport const BrowserSessionSchema = z.object({\n id: idOf(\"brw\"),\n object: z.literal(\"browser_session\"),\n computer_id: idOf(\"cmp\").nullable(),\n /** The agent session that opened it, if an agent did; a REST caller's browser carries `null`. */\n session_id: idOf(\"ses\").nullable(),\n status: BrowserSessionStatusSchema,\n allowed_domains: z.array(z.string()),\n region: z.enum(BROWSER_REGIONS),\n context_id: idOf(\"bct\").nullable(),\n context_backed: z.boolean(),\n timeout_at: Timestamp,\n opened_at: Timestamp,\n closed_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type BrowserSession = z.infer<typeof BrowserSessionSchema>;\n\n/** A bearer credential for one browser (§32.3): minted for a person, never stored, never in another object. */\nexport const BrowserLiveViewSchema = z.object({\n object: z.literal(\"browser_live_view\"),\n url: z.url(),\n expires_at: Timestamp,\n});\nexport type BrowserLiveView = z.infer<typeof BrowserLiveViewSchema>;\n\n/** A saved login, identity-scoped like a vault (D4). */\nexport const BrowserContextSchema = z.object({\n id: idOf(\"bct\"),\n object: z.literal(\"browser_context\"),\n identity_id: idOf(\"idn\"),\n name: z.string(),\n service: z.string().nullable(),\n created_at: Timestamp,\n last_used_at: Timestamp.nullable(),\n});\nexport type BrowserContext = z.infer<typeof BrowserContextSchema>;\n\nexport const BrowserGranteeTypeSchema = z.enum([\"agent\", \"role\"]);\n\nexport const BrowserGrantSchema = z.object({\n id: idOf(\"bgr\"),\n object: z.literal(\"browser_grant\"),\n context_id: idOf(\"bct\"),\n grantee_type: BrowserGranteeTypeSchema,\n grantee_id: z.union([idOf(\"agt\"), RoleSchema]),\n created_at: Timestamp,\n});\nexport type BrowserGrant = z.infer<typeof BrowserGrantSchema>;\n\nexport const SaveBrowserContextSchema = z.object({\n name: z.string().min(1).max(64),\n identity_id: idOf(\"idn\"),\n service: z.string().min(1).optional(),\n});\n\nexport const CreateBrowserGrantSchema = z.object({\n identity_id: idOf(\"idn\"),\n grantee_type: BrowserGranteeTypeSchema,\n grantee_id: z.union([idOf(\"agt\"), RoleSchema]),\n});\n\nconst Selector = z.string().min(1);\nconst Instruction = z.string().min(1).max(4_096);\n\n/** §32.4 — the discriminant is `action`, the same word the tool uses. */\nexport const BrowserActionRequestSchema = z.discriminatedUnion(\"action\", [\n z.object({ action: z.literal(\"goto\"), url: z.string().url() }),\n z.object({ action: z.literal(\"click\"), selector: Selector }),\n z.object({ action: z.literal(\"type\"), selector: Selector, text: z.string() }),\n z.object({\n action: z.literal(\"extract\"),\n instruction: Instruction.optional(),\n selector: Selector.optional(),\n schema: z.record(z.string(), z.unknown()).optional(),\n }),\n z.object({\n action: z.literal(\"act\"),\n instruction: Instruction,\n variables: z.record(z.string(), z.string()).optional(),\n }),\n z.object({ action: z.literal(\"observe\"), instruction: Instruction }),\n z.object({\n action: z.literal(\"links\"),\n contains: z.string().optional(),\n limit: z.number().int().min(1).max(200).default(50),\n }),\n z.object({ action: z.literal(\"screenshot\") }),\n]);\nexport type BrowserActionRequest = z.infer<typeof BrowserActionRequestSchema>;\nexport const BROWSER_ACTIONS = BrowserActionRequestSchema.options.map(\n (option) => option.shape.action.value,\n);\n\nexport const BrowserActionResultSchema = z.object({\n object: z.literal(\"browser_action\"),\n action: z.enum(BROWSER_ACTIONS),\n url: z.string(),\n text: z.string().nullable(),\n data: z.unknown().nullable(),\n links: z.array(z.object({ href: z.string(), text: z.string() })).nullable(),\n elements: z.array(z.object({ selector: z.string(), description: z.string() })).nullable(),\n file_id: idOf(\"fil\").nullable(),\n performed: z.boolean(),\n});\nexport type BrowserActionResult = z.infer<typeof BrowserActionResultSchema>;\n\n/** `login`/`signup` bodies (§32.3). The password never appears on the wire except in `credentials`. */\nexport const BrowserLoginSchema = z.object({\n service: z.string().min(1),\n url: z.string().url(),\n identity_id: idOf(\"idn\"),\n});\nexport const BrowserSignupSchema = BrowserLoginSchema.extend({ email: z.string().email() });\nexport const BrowserCredentialSchema = z.object({\n identity_id: idOf(\"idn\"),\n service: z.string().min(1),\n email: z.string().email(),\n password: z.string().min(1),\n username: z.string().min(1).optional(),\n});\n\nexport const LiveViewSchema = z.object({ url: z.string().url(), expires_at: Timestamp });\n","/** Org, members, keys, credits ledger, webhooks, audit log (canonical-spec §10, §11, §14, §17). */\n\nimport { z } from \"zod\";\nimport {\n AuditActionSchema,\n Metadata,\n MicroUsdField,\n PrincipalSchema,\n Timestamp,\n LineItemTierSchema,\n idOf,\n} from \"./common\";\n\n/** Where every company starts (the owner's choice, ADR-0904); migration 0088's column default. */\nexport const DEFAULT_ORG_TIMEZONE = \"America/New_York\";\n\n/** The IANA name `Intl` resolves `name` to, or `undefined` when it is not one zone's name. */\nfunction canonicalZone(name: string): string | undefined {\n // `Intl` also takes `EST`, `PST` and `+05:00`: an abbreviation or an offset, not a place's zone.\n if (!name.includes(\"/\") && name !== \"UTC\") return undefined;\n try {\n const zone = new Intl.DateTimeFormat(\"en-US\", { timeZone: name }).resolvedOptions().timeZone;\n // `supportedValuesOf` lists every canonical zone but `UTC`, and none of `Etc/GMT+5`'s kind.\n return zone === \"UTC\" || Intl.supportedValuesOf(\"timeZone\").includes(zone) ? zone : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A company's timezone as written (§20.6, ADR-0904): an IANA name, stored as the canonical one\n * `Intl` resolves, so `US/Eastern` is kept as `America/New_York`. The API's `PATCH` and the agent's\n * `company.set_timezone` both parse through it.\n */\nexport const TimezoneSchema = z.string().transform((name, ctx) => {\n const zone = canonicalZone(name);\n if (zone === undefined) {\n ctx.addIssue({ code: \"custom\", message: \"not a timezone; use an IANA name such as America/Los_Angeles\" });\n return z.NEVER;\n }\n return zone;\n});\n\nexport const OrganizationSchema = z.object({\n id: idOf(\"org\"),\n object: z.literal(\"organization\"),\n name: z.string(),\n balance_micro_usd: MicroUsdField,\n /**\n * The company's timezone, an IANA name (`America/New_York`, §20.6). Times the company chooses or\n * reads are in it: a new routine's zone, when a post goes out. `America/New_York` until changed.\n * Defaulted so a reply from a control plane older than 0088 (or a rolled-back Worker) still parses\n * in a newer SDK/CLI rather than throwing on every `orgs.get/list/update`.\n */\n timezone: z.string().min(1).default(DEFAULT_ORG_TIMEZONE),\n /**\n * The company's logo, an SVG a person or an agent drew (§20.7), passed by `checkLogoSvg`. `null`\n * until one is set. Defaulted so a reply from a control plane older than 0093 still parses.\n */\n logo_svg: z.string().nullable().default(null),\n created_at: Timestamp,\n});\n\nexport type Organization = z.infer<typeof OrganizationSchema>;\n\nexport const RoleSchema = z.enum([\"owner\", \"admin\", \"member\"]);\n\nexport type Role = z.infer<typeof RoleSchema>;\n\n/** Member ids are not in the `canonical-spec.md §2` prefix table; see the owed doc-fix in decisions. */\nexport const MemberSchema = z.object({\n id: z.string(),\n object: z.literal(\"member\"),\n email: z.email(),\n role: RoleSchema,\n invited_by: z.string().nullable(),\n created_at: Timestamp,\n});\n\nexport type Member = z.infer<typeof MemberSchema>;\n\nexport const SCOPES = [\n \"agents:read\",\n \"agents:write\",\n \"sessions:read\",\n \"sessions:write\",\n /**\n * THE MODEL DOOR AND NOTHING ELSE. `/v1/proxy/*` used to take `sessions:write`, which also opens\n * session create and cancel — so a credential handed to a customer's micro-VM, if it leaked, could\n * start sessions for the whole organization. This scope buys exactly one capability, so a sandbox\n * token can be minted with it alone.\n *\n * The proxy routes accept EITHER this or `sessions:write`: narrowing an already-published route\n * would break every key that reaches it today (§17).\n */\n \"proxy:write\",\n \"computers:write\",\n \"files:read\",\n \"files:write\",\n \"billing:read\",\n \"billing:write\",\n \"webhooks:*\",\n \"audit:read\",\n \"admin\",\n] as const;\nexport const ScopeSchema = z.enum(SCOPES);\n\nexport type Scope = z.infer<typeof ScopeSchema>;\n\nexport const ApiKeySchema = z.object({\n id: idOf(\"key\"),\n object: z.literal(\"api_key\"),\n name: z.string(),\n prefix: z.string(),\n scopes: z.array(ScopeSchema),\n created_by: PrincipalSchema,\n last_used_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\n\nexport type ApiKey = z.infer<typeof ApiKeySchema>;\n\n/**\n * Every inference debit records all five token tiers (§11) and its actor (§17). `line_items[].tier`\n * is the **whole** tier enum, not just the token five: a sandbox (`computer`) or a priced tool line\n * is a line item like any other, and narrowing this to the token tiers 500'd the ledger route on\n * every session that ran a box.\n */\nexport const LedgerEntrySchema = z.object({\n id: idOf(\"led\"),\n type: z.enum([\"debit\", \"credit\"]),\n amount_micro_usd: MicroUsdField,\n balance_after_micro_usd: MicroUsdField,\n actor: PrincipalSchema,\n session_id: idOf(\"ses\").nullable(),\n agent_id: idOf(\"agt\").nullable(),\n deployment_id: idOf(\"dep\").nullable(),\n line_items: z.array(z.object({ tier: LineItemTierSchema, amount_micro_usd: MicroUsdField })),\n created_at: Timestamp,\n});\n\nexport type LedgerEntry = z.infer<typeof LedgerEntrySchema>;\n\n/** Top-up ids are not in the `canonical-spec.md §2` prefix table; see the owed doc-fix in decisions. */\nexport const TopupSchema = z.object({\n id: z.string(),\n object: z.literal(\"topup\"),\n amount_micro_usd: MicroUsdField.positive(),\n status: z.enum([\"pending\", \"requires_action\", \"succeeded\", \"failed\"]),\n action_url: z.url().nullable(),\n balance_after_micro_usd: MicroUsdField.nullable(),\n created_at: Timestamp,\n});\n\nexport type Topup = z.infer<typeof TopupSchema>;\n\nexport const WebhookEndpointSchema = z.object({\n id: idOf(\"whk\"),\n object: z.literal(\"webhook_endpoint\"),\n url: z.url(),\n events: z.array(z.string()),\n enabled: z.boolean(),\n created_at: Timestamp,\n});\n\nexport type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;\n\nexport const WebhookDeliverySchema = z.object({\n id: idOf(\"whd\"),\n event_id: idOf(\"evt\"),\n event_type: z.string(),\n status: z.enum([\"pending\", \"succeeded\", \"failed\"]),\n attempts: z.number().int().nonnegative(),\n response_status: z.number().int().nullable(),\n response_snippet: z.string().nullable(),\n delivered_at: Timestamp.nullable(),\n next_retry_at: Timestamp.nullable(),\n});\n\nexport type WebhookDelivery = z.infer<typeof WebhookDeliverySchema>;\n\nexport const AuditEntrySchema = z.object({\n id: idOf(\"aud\"),\n object: z.literal(\"audit_entry\"),\n actor: PrincipalSchema,\n action: AuditActionSchema,\n resource_type: z.string(),\n resource_id: z.string(),\n request_id: z.string(),\n metadata: Metadata,\n created_at: Timestamp,\n});\n","/**\n * Model auto-selection (`canonical-spec §46`, ADR-0722): a caller names a few catalogue ids with a\n * one-line brief each and gets one of them back. Field-shape rules live here; the two rules that\n * need the catalogue (every option key is an exact entry id) or the ledger (the price) belong to\n * the route.\n *\n * The same `options`/`min_confidence` pair is a **policy** (§46.6, ADR-0723) when it rides beside a\n * `model` on a proxy call or an agent — there the sibling `model` is the default.\n *\n * A plain `z.object` with refinements, not a `.transform`/pipe: `parseBody` reads `.shape` to\n * refuse unknown keys under strict bodies.\n */\n\nimport { z } from \"zod\";\n\nexport const MODEL_SELECTION_MIN_OPTIONS = 2;\nexport const MODEL_SELECTION_MAX_OPTIONS = 16;\nexport const MODEL_SELECTION_MAX_MESSAGES = 32;\n/** Summed `content` length across every message — nothing is silently trimmed to fit. */\nexport const MODEL_SELECTION_MAX_CONTENT_CHARS = 32_000;\n\nexport const ModelSelectionMessageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().min(1),\n});\nexport type ModelSelectionMessage = z.infer<typeof ModelSelectionMessageSchema>;\n\nconst OptionsSchema = z\n .record(z.string().min(1), z.string().trim().min(1).max(500))\n .refine((options) => Object.keys(options).length >= MODEL_SELECTION_MIN_OPTIONS, {\n message: `at least ${MODEL_SELECTION_MIN_OPTIONS} options are required`,\n })\n .refine((options) => Object.keys(options).length <= MODEL_SELECTION_MAX_OPTIONS, {\n message: `at most ${MODEL_SELECTION_MAX_OPTIONS} options are allowed`,\n });\n\n/** §46.6: the selector's inputs minus the conversation and the default, which the carrier supplies. */\nexport const ModelSelectionPolicySchema = z.object({\n options: OptionsSchema,\n min_confidence: z.number().gt(0).max(1).optional(),\n});\nexport type ModelSelectionPolicy = z.infer<typeof ModelSelectionPolicySchema>;\n\n/** The one rule a policy cannot check alone: its default (`model`) must be one of its options. */\nexport const policyNamesDefault = (policy: ModelSelectionPolicy, model: string): boolean =>\n Object.hasOwn(policy.options, model);\n\n/**\n * The most recent turns that fit §46.2's caps, oldest first, for a conversation the caller cannot\n * be asked to shorten (§46.6). Every message is kept whole except the newest, which keeps its\n * tail when it alone is over the limit.\n */\nexport function selectionTail(messages: readonly ModelSelectionMessage[]): ModelSelectionMessage[] {\n const out: ModelSelectionMessage[] = [];\n let chars = 0;\n for (const message of [...messages].reverse()) {\n if (out.length === MODEL_SELECTION_MAX_MESSAGES) break;\n if (chars + message.content.length > MODEL_SELECTION_MAX_CONTENT_CHARS) {\n if (out.length === 0) {\n out.push({ role: message.role, content: message.content.slice(-MODEL_SELECTION_MAX_CONTENT_CHARS) });\n }\n break;\n }\n chars += message.content.length;\n out.push(message);\n }\n return out.reverse();\n}\n\nexport const ModelSelectionRequestSchema = z\n .object({\n options: OptionsSchema,\n messages: z.array(ModelSelectionMessageSchema).min(1).max(MODEL_SELECTION_MAX_MESSAGES),\n default: z.string().min(1).optional(),\n min_confidence: z.number().gt(0).max(1).optional(),\n })\n .superRefine((body, ctx) => {\n const total = body.messages.reduce((sum, message) => sum + message.content.length, 0);\n if (total > MODEL_SELECTION_MAX_CONTENT_CHARS) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"messages\"],\n message: `total message content exceeds ${MODEL_SELECTION_MAX_CONTENT_CHARS} characters`,\n });\n }\n if (body.default !== undefined && !Object.hasOwn(body.options, body.default)) {\n ctx.addIssue({ code: \"custom\", path: [\"default\"], message: \"default must be one of the options\" });\n }\n if (body.min_confidence !== undefined && body.default === undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"min_confidence\"],\n message: \"min_confidence requires a default to fall back to\",\n });\n }\n });\nexport type ModelSelectionRequest = z.infer<typeof ModelSelectionRequestSchema>;\n\nexport const ModelSelectionSchema = z.object({\n object: z.literal(\"model_selection\"),\n model: z.string().min(1),\n confidence: z.number().min(0).max(1).nullable(),\n probabilities: z.record(z.string(), z.number()).nullable(),\n defaulted: z.boolean(),\n spent_micro_usd: z.number().int().nonnegative(),\n usage: z.object({ input_tokens: z.number().int().nonnegative() }),\n});\nexport type ModelSelection = z.infer<typeof ModelSelectionSchema>;\n","/** Sessions, the transcript message, and tool results (canonical-spec §5, §7, §10, §16). */\n\nimport { z } from \"zod\";\nimport { SocialPlatformSchema } from \"./social\";\nimport {\n JsonSchemaDocument,\n Metadata,\n MicroUsdField,\n Timestamp,\n TokenUsageSchema,\n WindowSchema,\n idOf,\n} from \"./common\";\n\n/** `idle` = resumable, `completed` = the agent declared done; both are non-`running` (§5). */\nexport const SessionStatusSchema = z.enum([\n \"queued\",\n \"running\",\n \"idle\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\nexport type SessionStatus = z.infer<typeof SessionStatusSchema>;\n\n/**\n * Plan mode (§7.5, ADR-0905). `build` is every session that never entered plan mode. Session state,\n * never agent config: it rides a send and is changed back only by a person.\n */\nexport const SessionModeSchema = z.enum([\"plan\", \"build\"]);\nexport type SessionMode = z.infer<typeof SessionModeSchema>;\n\n/** A plan's words are capped where a board card's body is (`runtime-do board-tools.ts`). */\nexport const PLAN_MAX_CHARS = 20_000;\n\n/**\n * The living plan (§7.5). Kept by the runtime beside the session's state, never in the transcript.\n * `version` 0 is no plan yet, and only then is `by` null.\n */\nexport const PlanSchema = z.object({\n object: z.literal(\"plan\"),\n markdown: z.string().max(PLAN_MAX_CHARS),\n version: z.number().int().nonnegative(),\n by: z.enum([\"agent\", \"owner\"]).nullable(),\n});\nexport type Plan = z.infer<typeof PlanSchema>;\n\n/** `write_plan`'s arguments and `PUT /v1/sessions/{id}/plan`'s body: one compare-and-set (§7.5). */\nexport const PlanWriteSchema = z.object({\n markdown: z.string().max(PLAN_MAX_CHARS),\n base_version: z.number().int().nonnegative(),\n});\nexport type PlanWrite = z.infer<typeof PlanWriteSchema>;\n\n/** `propose_plan`'s arguments (§7.5). `version` is hashed into the card's id, so a denied plan is written again before it is proposed again. */\nexport const ProposePlanSchema = z.object({\n version: z.number().int().positive(),\n spends_or_publishes: z.array(z.string().min(1).max(200)).max(10).optional(),\n});\n\n/** Set whenever a turn yields control — never treat `idle` as success (§5). */\nexport const StopReasonSchema = z.enum([\n \"end_turn\",\n \"awaiting_input\",\n \"awaiting_approval\",\n \"budget_paused\",\n \"interrupted\",\n \"error\",\n \"max_iterations\",\n /** A turn produced no message and no tool call — honest failure, never `end_turn` (entry 4). */\n \"context_exhausted\",\n /**\n * A coordinator yielded because every delegated child it is waiting on is still running (§28).\n * Distinct from `awaiting_input`: nobody is being asked for anything, so no human can unblock it —\n * the child's completion does. Reporting `idle`/`end_turn` here would claim the task was finished.\n */\n \"awaiting_delegation\",\n /**\n * The turn yielded because the agent asked the operator a question and cannot proceed without\n * the answer (§7.1). Distinct from all three neighbours, and none can stand in: `awaiting_input`\n * says only that there is nothing left to do, so a client reading it renders a bare composer\n * where a specific answer is owed; `awaiting_approval` says the block is a tool call to allow or\n * deny, and its route carries a verb and no payload; `awaiting_delegation` says no human can\n * unblock it at all. What is being asked is the parked `pending_actions` row.\n */\n \"awaiting_answer\",\n]);\nexport type StopReason = z.infer<typeof StopReasonSchema>;\n\n/**\n * THE STOPS THAT PARK A TURN ON A PERSON, in one place because four things must agree about them.\n *\n * A question is a `pending_actions` row exactly as an unapproved call is (§7.1); the two differ\n * only in which door the person answers through, and nothing that reads this cares about doors.\n * Everything here keeps the parked rows across the commit, cross-posts a member's rows to its\n * coordinator, renders the card, and — in the sandbox reaper — refuses to TTL the filesystem the\n * question is about out from under a session waiting on a human.\n *\n * This existed as three hand-written copies of `stop === \"awaiting_approval\"`, in\n * `apps/runtime-do/src/loop.ts`, `apps/web/app/lib/events.ts` and the reaper's SQL. Adding\n * `awaiting_answer` reached exactly one of them, and the other two silently answered a session\n * parked on a question as though nobody were waiting. `budget_paused` is deliberately NOT here: a\n * person unblocks it too, but there is no parked row and nothing renders a card.\n */\nexport const PARKED_STOP_REASONS = [\"awaiting_approval\", \"awaiting_answer\"] as const;\n\n/** Is this stop one a person has to clear? `null`/`undefined` — never ran, never parked. */\nexport const isParked = (stop: string | null | undefined): boolean =>\n stop !== null && stop !== undefined && (PARKED_STOP_REASONS as readonly string[]).includes(stop);\n\n/**\n * THE STOP THAT IS NOT A REST. `max_iterations` says a turn ran out of model calls, not that the\n * work stopped: `schedule` (`apps/runtime-do/src/loop.ts`) arms the alarm at once, so the next\n * turn's `session.running` follows that `session.idle` in milliseconds. A reader that treats this\n * idle as the end stops reading, and the answer arrives on a socket nobody is holding — measured on\n * staging as a CEO chat still showing `Working…` 21.7 s after the reply was in the log, with only a\n * reload to reveal it. Nobody is asked for anything either, so it is not a park.\n */\nexport const RESUMING_STOP_REASONS = [\"max_iterations\"] as const;\n\n/** Does the runtime wake itself from this stop? `null`/`undefined` — never ran, never stopped. */\nexport const isResuming = (stop: string | null | undefined): boolean =>\n stop !== null && stop !== undefined && (RESUMING_STOP_REASONS as readonly string[]).includes(stop);\n\n/** Where a session sits in a team (§28). `null` on every ordinary, undelegated session. */\nexport const ThreadRoleSchema = z.enum([\"coordinator\", \"member\"]);\nexport type ThreadRole = z.infer<typeof ThreadRoleSchema>;\n\nexport const MessageSchema = z.object({\n role: z.enum([\"system\", \"user\", \"assistant\", \"tool\"]),\n content: z.string(),\n tool_call_id: z.string().optional(),\n});\nexport type Message = z.infer<typeof MessageSchema>;\n\n/**\n * ONE IMAGE A TOOL HANDS BACK TO THE MODEL (§16.2) — **a link to it, never its bytes.**\n *\n * *** THIS EXISTS BECAUSE EVERY IMAGE THIS PLATFORM MAKES WAS INVISIBLE TO THE AGENT THAT MADE\n * IT. *** `ToolResult.content` is a string, so a tool that produced pixels could only describe\n * them: the browser's `screenshot` stored a PNG and returned the sentence \"screenshot of <url>\n * saved as fil_…\". The model was told a file existed and could never look at it. Measured on the\n * `media` blueprint (ADR-0758): asked to study a reference video it could read the caption,\n * hashtags and transcript of, and never a frame, the crew planned the wrong genre outright.\n *\n * IT CARRIED BASE64 FOR ONE RELEASE, AND THAT WAS THE WRONG SHAPE (ADR-0761). A tool result is not\n * a one-off payload: it lands in session history and is replayed to the provider on *every\n * subsequent turn*. At the shipped bound — 5 MB of base64 each, twelve per result — a single\n * screenshot-heavy turn could park 60 MB in a context that is then re-sent for the rest of the\n * session, and the mitigation ADR-0758 named (pi resizing oversized images as they enter history)\n * is `processImage`, a wasm image backend that does not exist in the session isolate, so it fails\n * open and passes the original block through. Every image a tool returns is already written to\n * storage and already has a `fil_`; the addressable form of it costs ~200 bytes and never grows.\n *\n * `url` is a **short-lived signed §40 read** at this deployment's own origin — the same mint the\n * social publish hands a provider to fetch once (`files.ts` `signedFileUrl`), not a presigned\n * object-store URL, because the Worker holds no S3 credential. It expires; a later turn that needs\n * to look again asks `view_image` again, which is cheaper than what it replaces.\n *\n * `media_type` is the wire's spelling of the same field the providers use, and it is restricted to\n * what they accept — a model cannot look at a PDF or an SVG, and a tool that sends one has made a\n * mistake worth refusing at the boundary rather than at the provider.\n *\n * There is no byte cap here any more because there are no bytes here any more. The one bound left\n * is the COUNT, on `ToolResult.images` below, and it is the only one this contract needs.\n */\nexport const ToolImageSchema = z.object({\n file_id: idOf(\"fil\"),\n url: z.string().url().describe(\"A short-lived signed read for the file's bytes.\"),\n media_type: z.enum([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]),\n});\nexport type ToolImage = z.infer<typeof ToolImageSchema>;\n\n/**\n * Normative tool result — the plugin contract depends on this shape (§16).\n *\n * `images` is OPTIONAL and additive: a result carrying none is byte-identical to one written\n * before the field existed, which is why no tool, plugin or stored row needed changing for it.\n * A tool that returns images SHOULD still set `content`, because the text is what a reader without\n * vision — a transcript, a log, an operator scrolling the session — is left with.\n *\n * At most 12, because this is a tool result and not an album: a turn that needs more frames than\n * that is sampling, and the sampling belongs in the tool. Since ADR-0761 this count is the ONLY\n * bound on the field — each entry is a link of fixed size, so there is no payload left to cap.\n */\nexport const ToolResultSchema = z.object({\n output: z.unknown(),\n is_error: z.boolean().optional(),\n content: z.string().optional(),\n images: z.array(ToolImageSchema).max(12).optional(),\n});\nexport type ToolResult = z.infer<typeof ToolResultSchema>;\n\n/**\n * One field of a parked question (§7.1). `key` is the name the answer comes back under; the rest is\n * how it is asked. The union is discriminated on `type` so a renderer branches on one word rather\n * than sniffing which optional properties happen to be present.\n */\nconst QuestionFieldBase = {\n key: z.string().min(1).max(64),\n label: z.string().min(1).max(200),\n help: z.string().max(500).optional(),\n /**\n * A field that may be left blank, and it defaults to **false** — the rule \"every field must be\n * answered\" (`assertAnswers`) is still the rule, and this is the one documented way out of it.\n *\n * It exists for the question whose answer genuinely improves the work and does not gate it: a\n * template's setup form asking for a reference to imitate, say. Before the flag the only way to\n * ask such a thing was to make it mandatory — which forces an answer out of someone who has none,\n * and an invented answer is worse than an absent one, because the crew cannot tell them apart.\n *\n * Nothing downstream needs an \"if absent\" branch: `projectContextFor` already lists only the\n * questions that were answered, so an unanswered optional key is simply not in the context.\n *\n * ABSENT rather than `false`, which is why it is `.optional()` and not `.default(false)` like the\n * `multiple` and `other` beside it. Those two sit on the `choice` branch, where a renderer has to\n * branch on them and a definite value earns its place; this sits on the base, next to `help`,\n * which is absent-by-default for the same reason. A default here would make `optional: boolean`\n * required on the OUTPUT type — so every hand-written `QuestionField` in the codebase, and every\n * one written after it, would have to spell out the flag it does not use.\n */\n optional: z.boolean().optional(),\n};\n\nexport const QuestionFieldSchema = z.discriminatedUnion(\"type\", [\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"text\"),\n placeholder: z.string().max(200).optional(),\n }),\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"choice\"),\n /**\n * Plain strings: the option is both the value and the label, because the answer is read back by\n * a model, which wants the words and not an id. Fewer than two is not a choice, and more than\n * twelve is a list — which belongs in the prompt.\n */\n options: z.array(z.string().min(1).max(200)).min(2).max(12),\n multiple: z.boolean().default(false),\n /**\n * The free-text escape, and it defaults to **true** on purpose: the agent wrote the options and\n * the agent is the one that does not know the answer, so an operator must always be able to say\n * something it did not think of. A question that truly admits only its list opts out explicitly.\n */\n other: z.boolean().default(true),\n /**\n * A PICTURE OR A LINE FOR AN OPTION (ADR-1103): a template's \"how it looks\" shows its looks, and\n * a niche says what it means in one line. Each names its option by its words; one naming no\n * option is ignored, never refused. With a picture on any option the dashboard draws the choice\n * as a grid of pictures. `image` is `https://`, or a path on the dashboard itself. An array\n * and not a map, because a model's tool schema cannot always take a map. An older reader drops\n * it and draws the plain list.\n */\n details: z\n .array(\n z.object({\n option: z.string().min(1).max(200),\n note: z.string().min(1).max(120).optional(),\n image: z.string().max(500).regex(/^\\/(?!\\/)/, \"an image is a path on the dashboard\").optional(),\n }),\n )\n .max(12)\n .optional(),\n }),\n /**\n * THE PERSON'S OWN MEDIA (ADR-1103): \"show us what you like\". The dashboard offers an upload for\n * images or a video, which land in the organization's files, and a box for a link. The answer is\n * the list: `fil_` ids and `https://` links, which an agent opens with `files_get`, `view_image`\n * or the browser. `placeholder` is the link box's.\n */\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"media\"),\n placeholder: z.string().max(200).optional(),\n }),\n]);\nexport type QuestionField = z.infer<typeof QuestionFieldSchema>;\n\n/** One piece of a `media` answer: a stored file, or a public link. */\nexport const MEDIA_ANSWER = /^(fil_[0-9a-z]+|https:\\/\\/\\S+)$/;\n\n/** The most pieces a `media` answer holds: an answer list's own bound (`answersOf`). */\nexport const MEDIA_MAX = 12;\n\n/**\n * A CONNECT CARD (ADR-1102): the networks an agent needs a person to sign in to. The card draws a\n * row per network with its Connect, and one Not now. The answer is written by the card, never by\n * the person: `connected: YouTube (@handle)` once every network holds an account, or `not now`.\n *\n * An agent's question only, never a template's: a template asks before anything is provisioned,\n * when there is no persona yet to hold the account.\n */\nexport const ConnectFieldSchema = z.object({\n ...QuestionFieldBase,\n type: z.literal(\"connect\"),\n platforms: z.array(SocialPlatformSchema).min(1).max(6),\n});\n\n/** A field of an agent's question (§7.1): a template's kinds, and the connect card. */\nexport const AskFieldSchema = z.discriminatedUnion(\"type\", [...QuestionFieldSchema.options, ConnectFieldSchema]);\nexport type AskField = z.infer<typeof AskFieldSchema>;\n\n/**\n * A field as a client pinned before `QUESTION_KINDS_VERSION` reads it (ADR-1105): `text` and\n * `choice` as they are, and a connect card or a media field as a text field that says how to answer\n * it. The answer is still checked against the real field (`answerProblems`).\n */\nexport function legacyField(field: AskField): AskField {\n if (field.type !== \"connect\" && field.type !== \"media\") return field;\n const { key, label, help, optional } = field;\n const placeholder =\n field.type === \"connect\"\n ? `connect ${field.platforms.join(\", \")} on the dashboard, then answer \"connected\", or \"not now\"`\n : \"links or fil_ ids, separated by spaces\";\n return { key, label, type: \"text\", placeholder, ...(help === undefined ? {} : { help }), ...(optional === undefined ? {} : { optional }) };\n}\n\n/**\n * The whole question (§7.1). Exported rather than left inline in `PendingActionSchema` because it\n * is the `ask_operator` tool's argument schema *and* the parked row's `question` branch, and those\n * two have to be the same shape: the row is built by parsing the call's arguments, and the tool\n * call is replayed from the row. Two spellings of the bounds is how they come to disagree.\n */\n/**\n * The most a person answers in one sitting. It is three and not a template's four (ADR-0965): the\n * published SDK parses `pending_actions[].question.fields` with `.max(3)`, so one four-field\n * question made every `sessions.get` and `sessions.list` of an older client throw. A template with\n * four setup questions is asked as two questions.\n */\nexport const QUESTION_FIELDS_MAX = 3;\n\nexport const QuestionSchema = z.object({\n prompt: z.string().min(1).max(1000),\n fields: z.array(AskFieldSchema).min(1).max(QUESTION_FIELDS_MAX, {\n message: `a question has at most ${QUESTION_FIELDS_MAX} fields — ask the rest in a second question once these are answered`,\n }),\n}).refine((question) => question.fields.length === 1 || question.fields.every((field) => field.type !== \"connect\"), {\n // A connect card answers itself when the accounts land (ADR-1102); a field beside it would need\n // a Send the card does not have.\n message: \"a connect field is a question of its own: ask anything else in a separate question\",\n path: [\"fields\"],\n});\nexport type Question = z.infer<typeof QuestionSchema>;\n\n/**\n * What comes back (§7.1). Keyed by `QuestionField.key`; an array is a `multiple: true` choice, and\n * a string covers text, a single choice and whatever `other: true` let the person type instead.\n *\n * It is deliberately NOT validated against the question it answers. The agent wrote the question\n * and the agent reads the answer, so the only party that can judge \"that is not one of my options\"\n * is the model — and it can, because `other` means a free-text value was always legal. A schema\n * that rejected the operator's own words would be enforcing a rule §7.1 does not have.\n */\nconst answersOf = (max: number, message: string) =>\n z\n .record(\n z.string().min(1).max(64),\n z.union([z.string().max(2000), z.array(z.string().max(2000)).min(1).max(12)]),\n )\n .refine((answers) => Object.keys(answers).length <= max, { message });\n\nexport const AnswersSchema = answersOf(\n QUESTION_FIELDS_MAX,\n `a question has at most ${QUESTION_FIELDS_MAX} fields, so an answer has at most ${QUESTION_FIELDS_MAX} keys`,\n);\nexport type Answers = z.infer<typeof AnswersSchema>;\n\n/**\n * The most questions a template asks before anything is provisioned (ADR-0757). Four, one more than\n * a question holds (ADR-0965): the fourth is asked as a second question, but the install carries all\n * four answers at once.\n */\nexport const TEMPLATE_QUESTIONS_MAX = 4;\n\n/**\n * A template install's answers, as a person edits them on approval (ADR-1030). The same values as\n * `AnswersSchema`, capped at the template's questions and not at one question's fields, so a\n * four-question template's edit is not refused before `assertAnswers` checks its keys.\n */\nexport const InstallAnswersSchema = answersOf(\n TEMPLATE_QUESTIONS_MAX,\n `a template asks at most ${TEMPLATE_QUESTIONS_MAX} questions, so an install has at most ${TEMPLATE_QUESTIONS_MAX} answers`,\n);\n\n/** What is wrong with a `media` answer's pieces, or `null`: at most twelve files and https links. */\nfunction mediaProblem(key: string, values: readonly string[]): string | null {\n if (values.length > MEDIA_MAX) return `\\`${key}\\` takes at most ${MEDIA_MAX} files and links`;\n const odd = values.find((value) => !MEDIA_ANSWER.test(value));\n return odd === undefined ? null : `\\`${key}\\` takes \\`fil_\\` ids and https links, and \\`${odd}\\` is neither`;\n}\n\n/**\n * EVERYTHING WRONG WITH AN ANSWER SET, against the fields it answers (§7.1) — one rule, read by the\n * control plane before it files answers (`assertAnswers`) and by the studio before it puts an\n * install in front of a person (`InstallPlan`), so a card never offers to run what the control\n * plane will refuse. Empty means the answers stand.\n *\n * Every field must be answered unless it is `optional`, and an optional key that IS present is\n * checked like any other. A key the fields do not ask is wrong. A `choice` without `other` admits\n * only its options.\n */\nexport function answerProblems(\n fields: readonly AskField[],\n answers: Readonly<Record<string, unknown>>,\n): { key: string; message: string }[] {\n const problems: { key: string; message: string }[] = [];\n const asked = new Set(fields.map((field) => field.key));\n for (const key of Object.keys(answers)) {\n if (!asked.has(key)) problems.push({ key, message: `the question does not ask \\`${key}\\`` });\n }\n for (const field of fields) {\n const given = answers[field.key];\n if (given === undefined && field.optional) continue;\n const values = typeof given === \"string\" ? [given] : Array.isArray(given) ? given : [];\n if (values.length === 0 || values.some((value) => typeof value !== \"string\" || value.trim() === \"\")) {\n // A blank optional answer is refused too (an answer given is meant), but the fix is to leave\n // it out: measured, the CEO sent `reference: \"\"` for a question the person skipped.\n const message = field.optional ? `\\`${field.key}\\` was skipped, so leave it out rather than send it blank` : `\\`${field.key}\\` is unanswered`;\n problems.push({ key: field.key, message });\n continue;\n }\n if (field.type === \"text\" || field.type === \"connect\") {\n if (Array.isArray(given)) problems.push({ key: field.key, message: `\\`${field.key}\\` takes one string` });\n continue;\n }\n if (field.type === \"media\") {\n const problem = mediaProblem(field.key, values as string[]);\n if (problem !== null) problems.push({ key: field.key, message: problem });\n continue;\n }\n if (field.multiple !== Array.isArray(given)) {\n const shape = field.multiple ? \"an array of the options chosen\" : \"one option, as a string\";\n problems.push({ key: field.key, message: `\\`${field.key}\\` takes ${shape}` });\n continue;\n }\n // `other` is the free-text escape and defaults to true, so the closed check runs only on a\n // question that opted out of it — the one case where an unlisted answer is genuinely wrong.\n if (field.other) continue;\n const unlisted = (values as string[]).filter((value) => !field.options.includes(value));\n if (unlisted.length > 0) {\n problems.push({\n key: field.key,\n message: `\\`${field.key}\\` admits only the options it listed, and \\`${unlisted[0]}\\` is not one of them`,\n });\n }\n }\n return problems;\n}\n\n/**\n * What a parked session is blocked on (§6 `ask` permission, §7.1). Historically this was only the\n * tool calls an `ask` permission stopped; a question the agent asked the operator is now the second\n * kind, and it is **a row in this same array** rather than a new object, table or list — the park,\n * the sleep, the inbox wake, the transcript fold and the replay are all reused unmodified.\n *\n * `kind` defaults to `\"tool\"`, which is what makes the widening free: every row already sitting in\n * the `pending_actions` jsonb column predates the tag and keeps parsing, so there is no data\n * migration. Carrying an optional tag on this shape has precedent — `ThreadAction`\n * (`apps/runtime-do/src/team.ts`) already extends it with a DO-local `thread_id`.\n */\nexport const PendingActionSchema = z.object({\n kind: z.enum([\"tool\", \"question\"]).default(\"tool\"),\n tool_call_id: z.string(),\n name: z.string(),\n args: z.record(z.string(), z.unknown()),\n /**\n * Present iff `kind` is `\"question\"`, and it is the parse of `args` rather than a second source\n * of truth: `args` is what the model called and therefore what replays byte-identically, while\n * `question` is what a renderer reads without having to know that `ask_operator`'s arguments\n * happen to be the question. Same content, two jobs.\n */\n question: QuestionSchema.optional(),\n /**\n * The helper's thread a coordinator adopted this call from (§28, B-3; ADR-1101): the dashboard\n * marks that helper as waiting on you. Absent on the session's own calls.\n */\n thread_id: idOf(\"ses\").optional(),\n});\nexport type PendingAction = z.infer<typeof PendingActionSchema>;\n\nexport const SessionSchema = z.object({\n id: idOf(\"ses\"),\n object: z.literal(\"session\"),\n agent_id: idOf(\"agt\"),\n agent_version: z.number().int().positive(),\n deployment_id: idOf(\"dep\").nullable(),\n /**\n * The persona this session acts as (`canonical-spec §22`). Chosen per task from the personas the\n * agent holds a grant to, and `null` when the caller named none — an agent with several\n * identities is not silently given one.\n */\n identity_id: idOf(\"idn\").nullable(),\n /**\n * The sandbox this session provisioned, or `null` when its toolset needs none. It is a real\n * `Computer`: it lists under `GET /v1/computers`, takes `exec`/`snapshot`, and is destroyed when\n * the session can no longer run a turn (ADR-0160).\n */\n computer_id: idOf(\"cmp\").nullable(),\n /**\n * The delegation lineage (§28). `parent_session_id` is the thread that delegated this one and\n * `root_session_id` the coordinator at the top of the tree; both `null` on a session a customer\n * started. A child is addressable on its own but is excluded from the default `GET /v1/sessions`\n * listing, so a team of ten does not bury the ten tasks the customer actually asked for.\n */\n parent_session_id: idOf(\"ses\").nullable(),\n root_session_id: idOf(\"ses\").nullable(),\n thread_role: ThreadRoleSchema.nullable(),\n /**\n * The model the latest send picked (§7 `model`), or `null` when none has and the session runs its\n * pinned version's model (§10, ADR-0832). Defaulted so a reply from an older control plane parses.\n */\n model: z.string().nullable().default(null),\n /** Plan mode (§7.5, §10): defaulted so a reply from an older control plane parses as `build`. */\n mode: SessionModeSchema.default(\"build\"),\n status: SessionStatusSchema,\n stop_reason: StopReasonSchema.nullable(),\n window: WindowSchema,\n budget_micro_usd: MicroUsdField.nonnegative(),\n consumed_micro_usd: MicroUsdField.nonnegative(),\n token_usage: TokenUsageSchema,\n pending_actions: z.array(PendingActionSchema),\n output_schema: JsonSchemaDocument.nullable(),\n structured_output: z.record(z.string(), z.unknown()).nullable(),\n last_seq: z.number().int().nonnegative(),\n metadata: Metadata,\n started_at: Timestamp.nullable(),\n ended_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\n/**\n * `POST /v1/sessions/{id}/messages` — one send contract (§7). `queue:true` holds the message in\n * the inbox of a `running` session for the turn after this one; `interrupt:true` stops this one.\n * Both at once is refused: the two name opposite answers to the same question.\n */\nexport const SendMessageSchema = z\n .object({\n message: z.string(),\n interrupt: z.boolean().optional(),\n queue: z.boolean().optional(),\n /** A catalogue id: this session runs on it from this message's turn on (§7, ADR-0832). */\n model: z.string().min(1).optional(),\n /** Plan mode from this message's turn on (§7.5, ADR-0905). */\n mode: SessionModeSchema.optional(),\n idempotency_key: z.string().optional(),\n })\n .refine((body) => !(body.interrupt === true && body.queue === true), {\n message: \"a send is either an interrupt or queued, not both\",\n path: [\"queue\"],\n });\n\n/**\n * `POST /v1/sessions/{id}/messages` → `202` (§7). The reply is the **acceptance**, not a session\n * snapshot: the turn has not run yet, so a snapshot could only report the state before the send.\n * `accepted_seq` is the event high-water mark at acceptance — every event this send produces has\n * `seq > accepted_seq`, which is what makes \"wait for my turn\" expressible (ADR-0108).\n */\nexport const SendAcceptedSchema = z.object({\n session_id: z.string(),\n status: SessionStatusSchema,\n accepted_seq: z.number().int().nonnegative(),\n});\nexport type SendAccepted = z.infer<typeof SendAcceptedSchema>;\n\n/**\n * `POST /v1/sessions/{id}/tool_confirmations` (§7).\n *\n * `scope` is HOW FAR THE ALLOW REACHES, and it is the one thing this body could not say. An\n * approval id is `tc_` + SHA-256 over the tool name and its canonical arguments\n * (`harness-pi/approvals.ts`), deliberately, so a decision survives the session sleeping — but that\n * makes every decision exactly one call, and a person setting an agent up answers the same tool\n * five times with different arguments, one model turn apart each. `scope: \"session\"` says \"this\n * TOOL, for the rest of THIS chat\": subsequent calls to that name run without a card.\n *\n * The bounds are the whole design and they are narrow on purpose. One session — it lives in that\n * session's transcript and nowhere else, so it cannot outlive the chat, cannot be read by another\n * session and is never written onto the agent. One tool NAME — never \"approve everything\", and\n * never a second tool. Opt-in per grant, so the default is still one card, one call. And it only\n * widens `allow`: a session-wide *deny* is a different feature nobody has asked for, and the route\n * refuses the pairing rather than inventing semantics for it.\n *\n * WHY THIS BODY AND NOT A SIBLING ROUTE, given `SessionAnswerSchema` below is a sibling for\n * looking like a widening: the objection there is that an optional `answers` would make the\n * REQUIRED field `decision` conditionally required, so neither body would be total any more.\n * `scope` does nothing of the kind. `tool_call_id` and `decision` stay required and mean exactly\n * what they meant; `scope` is a modifier on the verb, with a default that is today's behaviour, so\n * an omitted `scope` is byte-for-byte the request every existing client already sends.\n */\nexport const ToolConfirmationSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().optional(),\n scope: z.enum([\"call\", \"session\"]).default(\"call\"),\n /**\n * THE PERSON'S OWN ANSWERS for a template install they approve (ADR-1030): the call runs with\n * these in place of the `answers` the agent proposed, and with nothing else changed. A modifier on\n * `allow`, like `scope`: absent is the call as proposed. The route refuses it on a deny, on a session\n * grant, on any other tool, and on answers the template's questions refuse (`answerProblems`).\n */\n answers: InstallAnswersSchema.optional(),\n});\n\n/**\n * `POST /v1/sessions/{id}/answers` (§7.2) — a **sibling** of `ToolConfirmationSchema`, and\n * deliberately not a widening of it.\n *\n * The obvious-looking alternative is one route: add an optional `answers` to the confirmation body\n * and let `decision` go absent when it is present. That reads fine as a schema and badly as a\n * contract — `decision` becomes conditionally required, so every client has to know a rule the\n * type cannot state, and every server has to reject the two nonsense pairings (`decision` with\n * `answers`, neither with either) by hand. A second route costs one line in the route table and\n * one method on the client, and in exchange both bodies stay honest: each has exactly the fields\n * it always has, and each is required.\n *\n * `answers` is keyed by `QuestionField.key`. An array is a `choice` field with `multiple: true`;\n * everything else is a string, including the free text an `other: true` field admits. The values\n * are read back by a model, so they are the words a person chose and not an index into `options`.\n */\nexport const SessionAnswerSchema = z.object({\n tool_call_id: z.string(),\n answers: z.record(z.string(), z.union([z.string(), z.array(z.string())])),\n});\nexport type SessionAnswer = z.infer<typeof SessionAnswerSchema>;\n","/** Identity-owned social publishing (`canonical-spec.md §27`). */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const SOCIAL_PLATFORMS = [\n \"bluesky\",\n \"facebook\",\n \"instagram\",\n \"linkedin\",\n \"mastodon\",\n \"pinterest\",\n \"reddit\",\n \"threads\",\n \"tiktok\",\n \"x\",\n \"youtube\",\n] as const;\n\n/** The networks the social layer connects (§27); the catalogue's own id for X is `twitter`. */\nexport const SOCIAL_APPS: ReadonlySet<string> = new Set([...SOCIAL_PLATFORMS, \"twitter\"]);\nexport const isSocialApp = (connector: string): boolean =>\n SOCIAL_APPS.has(connector.trim().toLowerCase());\n\n/** Platforms whose provider contract accepts a text-only post. */\nexport const SOCIAL_TEXT_PLATFORMS = [\n \"bluesky\",\n \"facebook\",\n \"linkedin\",\n \"mastodon\",\n \"threads\",\n \"x\",\n] as const;\n\n/**\n * Platforms whose provider contract accepts a post of media plus a caption, and nothing\n * per-destination beyond it. Naming one is legal exactly when the post carries `media_urls` or\n * `file_ids` — a text-only post to a video network is one the provider would refuse.\n *\n * `pinterest` and `reddit` are in neither list on purpose: the provider requires a board name and\n * a subreddit respectively, per-post destinations `CreatePost` has no field for, so a post naming\n * one is refused here with that reason rather than at the provider (`canonical-spec.md §27`).\n */\nexport const SOCIAL_MEDIA_PLATFORMS = [\"instagram\", \"tiktok\", \"youtube\"] as const;\n\n/** Who may see a published post. Three words, because three is what the networks that have the\n * concept at all actually spell. */\nexport const SOCIAL_VISIBILITIES = [\"public\", \"unlisted\", \"private\"] as const;\n\n/**\n * Platforms whose provider contract carries a per-post visibility with all three of those\n * meanings. `linkedin` and `tiktok` have a privacy field too, but neither spells `unlisted` — a\n * post-to-connections and a post-to-self-only are a different axis — so mapping ours onto theirs\n * would be inventing a meaning. They are refused by name instead, like the media rule below.\n */\nexport const SOCIAL_VISIBILITY_PLATFORMS = [\"mastodon\", \"youtube\"] as const;\n\nexport const SocialVisibilitySchema = z.enum(SOCIAL_VISIBILITIES);\nexport type SocialVisibility = z.infer<typeof SocialVisibilitySchema>;\n\nexport const acceptsVisibility = (platform: string): boolean =>\n (SOCIAL_VISIBILITY_PLATFORMS as readonly string[]).includes(platform);\n\n/** What a caller is told about visibility, in the tool description and the field's own text. */\nexport const SOCIAL_VISIBILITY_RULE =\n `visibility is ${SOCIAL_VISIBILITIES.join(\", \")} and only ` +\n `${SOCIAL_VISIBILITY_PLATFORMS.join(\" and \")} accept it; omit it and the post publishes at ` +\n \"the account's own default, which on a video channel is normally public\";\n\n/**\n * The outcome metrics the platform measures on a published post (§27, ADR-0768). `follower_delta`\n * is derived by the sweep from two `followers` readings; every other name is parsed from the\n * provider's analytics by the adapter. The only writer of these rows is the platform's own sweep.\n */\nexport const SOCIAL_METRICS = [\n \"views\",\n \"impressions\",\n \"likes\",\n \"comments\",\n \"shares\",\n \"watch_through_rate\",\n \"followers\",\n \"follower_delta\",\n] as const;\nexport type SocialMetric = (typeof SOCIAL_METRICS)[number];\n\nexport const SocialPlatformSchema = z.enum(SOCIAL_PLATFORMS);\nexport type SocialPlatform = z.infer<typeof SocialPlatformSchema>;\n\nexport const SocialTextPlatformSchema = z.enum(SOCIAL_TEXT_PLATFORMS);\nexport type SocialTextPlatform = z.infer<typeof SocialTextPlatformSchema>;\n\nconst isText = (platform: string): boolean =>\n (SOCIAL_TEXT_PLATFORMS as readonly string[]).includes(platform);\nconst isMedia = (platform: string): boolean =>\n (SOCIAL_MEDIA_PLATFORMS as readonly string[]).includes(platform);\n\n/** What a caller is told about the lists, in the tool description and the field's own text. */\nexport const SOCIAL_PLATFORM_RULE =\n `${SOCIAL_TEXT_PLATFORMS.join(\", \")} take a text-only post; ` +\n `${SOCIAL_MEDIA_PLATFORMS.join(\", \")} may be named only when the post carries media_urls or ` +\n `file_ids; ${SOCIAL_PLATFORMS.filter((platform) => !isText(platform) && !isMedia(platform)).join(\", \")} ` +\n \"cannot be posted to\";\n\n/**\n * The create-post rule, shared verbatim by the REST route and the agent tool so the two doors\n * cannot drift. Both halves are relationships between `platforms` and another field — the two\n * media fields, and `visibility` — so they live on the object rather than on any one field, and\n * each refusal names the platform it is about.\n */\nexport function checkPostTargets(\n value: {\n platforms: readonly string[];\n media_urls?: readonly unknown[] | undefined;\n file_ids?: readonly unknown[] | undefined;\n visibility?: string | undefined;\n },\n ctx: z.RefinementCtx,\n): void {\n const named = [...new Set(value.platforms)];\n const unsupported = named.filter((platform) => !isText(platform) && !isMedia(platform));\n if (unsupported.length > 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"platforms\"],\n message:\n `${unsupported.join(\", \")} cannot be a post target: each needs a per-destination field ` +\n \"(a board, a subreddit) this post has no way to carry\",\n });\n return;\n }\n const needMedia = named.filter(isMedia);\n if (needMedia.length > 0 && (value.media_urls?.length ?? 0) + (value.file_ids?.length ?? 0) === 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"platforms\"],\n message:\n `${needMedia.join(\", \")} publishes media, not text: attach at least one media_urls or ` +\n \"file_ids entry, or drop the platform\",\n });\n }\n if (value.visibility === undefined) return;\n const deaf = named.filter((platform) => !acceptsVisibility(platform));\n if (deaf.length === 0) return;\n ctx.addIssue({\n code: \"custom\",\n path: [\"visibility\"],\n message:\n `${deaf.join(\", \")} has no per-post visibility to publish under: only ` +\n `${SOCIAL_VISIBILITY_PLATFORMS.join(\" and \")} accept one, so drop visibility or send those ` +\n \"targets as their own post\",\n });\n}\n\nexport const SocialAccountSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_account\"),\n identity_id: idOf(\"idn\"),\n platform: SocialPlatformSchema,\n username: z.string().nullable(),\n display_name: z.string().nullable(),\n avatar_url: z.url().nullable(),\n connected_at: Timestamp.nullable(),\n});\nexport type SocialAccount = z.infer<typeof SocialAccountSchema>;\n\nexport const SocialPostStatusSchema = z.enum([\n \"draft\",\n \"scheduled\",\n \"processing\",\n \"posted\",\n \"failed\",\n \"deleted\",\n]);\nexport type SocialPostStatus = z.infer<typeof SocialPostStatusSchema>;\n\nexport const SocialPostSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_post\"),\n identity_id: idOf(\"idn\"),\n title: z.string(),\n platforms: z.array(SocialPlatformSchema),\n status: SocialPostStatusSchema,\n scheduled_at: Timestamp.nullable(),\n posted_at: Timestamp.nullable(),\n error: z.string().nullable(),\n});\nexport type SocialPost = z.infer<typeof SocialPostSchema>;\n\nexport const SocialUploadSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_upload\"),\n identity_id: idOf(\"idn\"),\n type: z.enum([\"image\", \"video\", \"document\"]),\n url: z.url().nullable(),\n});\nexport type SocialUpload = z.infer<typeof SocialUploadSchema>;\n\nexport const SocialAnalyticsSchema = z.object({\n object: z.literal(\"social_analytics\"),\n identity_id: idOf(\"idn\"),\n resource_id: z.string().min(1),\n platform: SocialPlatformSchema.nullable(),\n data: z.unknown(),\n});\nexport type SocialAnalytics = z.infer<typeof SocialAnalyticsSchema>;\n\nexport const SocialCommentSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_comment\"),\n identity_id: idOf(\"idn\"),\n post_id: z.string().min(1),\n platforms: z.array(SocialPlatformSchema),\n status: SocialPostStatusSchema,\n posted_at: Timestamp.nullable(),\n data: z.unknown(),\n});\nexport type SocialComment = z.infer<typeof SocialCommentSchema>;\n\n/** Where a post stands in `GET /v1/posts` (§27.1): waiting on a person, due, out, or refused. */\nexport const POST_STATUSES = [\"pending\", \"scheduled\", \"posted\", \"failed\"] as const;\nexport const PostStatusSchema = z.enum(POST_STATUSES);\nexport type PostStatus = z.infer<typeof PostStatusSchema>;\n\n/**\n * One post as the posts view lists it (§27.1, ADR-0890): a parked `social.post` call (`pending`) or\n * a `social_post` row. A pending post has no provider id yet, so its `id` is\n * `<session_id>:<tool_call_id>`, the address a decision is posted to.\n */\nexport const PostSchema = z.object({\n object: z.literal(\"post\"),\n id: z.string().min(1),\n status: PostStatusSchema,\n identity_id: z.string().nullable(),\n agent_id: z.string().nullable(),\n session_id: z.string().nullable(),\n tool_call_id: z.string().nullable(),\n content: z.string().nullable(),\n platforms: z.array(z.string()),\n file_ids: z.array(z.string()),\n media_urls: z.array(z.string()),\n visibility: SocialVisibilitySchema.nullable(),\n scheduled_at: Timestamp.nullable(),\n posted_at: Timestamp.nullable(),\n url: z.string().nullable(),\n error: z.string().nullable(),\n /** The latest stored reading, `{metric: value}`; `null` before `social.post_metrics` read any. */\n metrics: z.record(z.string(), z.number()).nullable(),\n measured_at: Timestamp.nullable(),\n /** Pending only: the earlier post this call would repeat — same identity, network and file. */\n duplicate_of: z\n .object({\n id: z.string(),\n status: PostStatusSchema,\n platform: z.string(),\n at: Timestamp.nullable(),\n agent_id: z.string().nullable(),\n session_id: z.string().nullable(),\n })\n .nullable(),\n created_at: Timestamp,\n});\nexport type Post = z.infer<typeof PostSchema>;\n","/** Events — `{domain}.{action}` types on a gap-free `seq` (canonical-spec §8, §10, §15). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, TokenUsageSchema, idOf } from \"./common\";\nimport { AnswersSchema } from \"./session\";\n\nexport const EventTypeSchema = z.enum([\n \"message.delta\",\n /**\n * The agent's answer (no `role`), or a user row `{ role: \"user\", content, client_message_id? }` (§8).\n * A user row the runtime wrote itself — a media job's result, a tool grant — carries\n * `from: \"platform\"` and is the platform's notice, not a caller's words (§8, ADR-0870).\n */\n \"message.completed\",\n /** A caller's message, durable in the inbox and not yet admitted to a turn (§7, §8): `{ client_message_id, content }`. */\n \"message.accepted\",\n /** A person's fan-out, on the sender's log without waking it (§8, §28.16): `{ client_message_id, content, handoffs, refusals }`. */\n \"handoff.sent\",\n \"tool.started\",\n \"tool.completed\",\n \"tool.confirm\",\n /** A person's decision on a parked call, stamped with the inbox write that delivers it (§8, ADR-0764). */\n \"tool.confirm.resolved\",\n /** A person's answer to a parked question, stamped the same way (§7.1, §8, ADR-1049). */\n \"tool.confirm.answered\",\n \"session.running\",\n \"session.usage\",\n \"session.idle\",\n /** A failed attempt the loop will retry (§8): `{ attempt, in_ms, code }`. */\n \"session.retrying\",\n /** The session's mode changed (§7.5): `{ mode: \"plan\" | \"build\" }`. */\n \"session.mode\",\n /** A write to the session's plan, by the agent or its owner (§7.5): the plan object. */\n \"plan.updated\",\n /**\n * The turn ran, but without something it needed (§8): `{ reason, detail? }`.\n *\n * Emitted for a turn whose sandbox could not be woken. That turn used to be indistinguishable\n * from a success — the model was handed the failure as a tool result, answered around it from the\n * transcript, and the session ended `idle`/`end_turn` with no field anywhere saying the\n * filesystem had been unavailable. This is the field. `reason` is open on purpose; today it is\n * `\"sandbox_unavailable\"`, `\"vendor_resume_unavailable\"`, or `\"app_tools_unavailable\"` — an app the\n * agent's toolset names gave no tools this turn (§29.5, `runtime-do app-mcp-tools.ts`).\n *\n * `detail` is the boot failure's own message, and it is here because `reason` alone reads the\n * same for a vendor outage and for a fault of ours. Staging round 3 spent its whole budget\n * establishing with raw Connect RPC that the vendor was refusing every `ResumeSession` on the\n * account — a question the adapter could have answered, since its give-up names the vendor state\n * it last saw and how long it waited (`compute-tenki index.ts`). It is diagnostic prose, not a\n * contract: never parse it, and it may be absent.\n */\n \"session.degraded\",\n /**\n * The session let go of a sandbox that would not resume and will run the next turn on a fresh\n * one: `{ from, reason, failures, replacements }`.\n *\n * *** THE ONE TURN WHERE A FILESYSTEM ACTUALLY GOES MISSING USED TO BE THE SILENT ONE. ***\n * `session.degraded` marks the turns whose resume FAILED, and those turns lose nothing — the box\n * is still there and the next turn may still get it back. The turn that swaps the box is the\n * damaging one, and it has no failure to report: it provisions a replacement and runs normally.\n * Staging watched a session answer `cat: … No such file or directory` with nothing in its event\n * log to tell that apart from the file never having been written, and support could not tell\n * either. `from` is the box that was let go of, so a customer can still reach it through\n * `GET /v1/computers/:id` while it lives.\n *\n * `reason` is open like `session.degraded`'s, and it carries the one distinction an operator\n * cannot make any other way: `\"resume_refused\"` is the FIRST swap, where everything knowable here\n * says the fault is that box's, and `\"vendor_resume_unavailable\"` is a swap that follows one — a\n * fault that already outlived a fresh machine, so it is the account and not the box.\n * `replacements` counts them. There is no third swap: past `box.ts MAX_BOX_REPLACEMENTS` the\n * session keeps the box it holds and reports `session.degraded` under that same\n * `vendor_resume_unavailable` reason, rather than abandoning one more live micro-VM every cycle\n * for a fault a fresh one demonstrably does not fix.\n */\n \"session.computer_replaced\",\n \"budget.exceeded\",\n \"span.model_request.start\",\n \"span.model_request.end\",\n // Pre-model spans (§15): what the gap before the first model request was spent on.\n \"span.transcript_load.start\",\n \"span.transcript_load.end\",\n \"span.harness_load.start\",\n \"span.harness_load.end\",\n \"span.harness_build.start\",\n \"span.harness_build.end\",\n \"span.box_resume.start\",\n \"span.box_resume.end\",\n /**\n * A delegated thread's lifecycle, on the **coordinator's** stream (§28). The child's own\n * `ses_…` rides inside `data.thread_id` — the event schema gains no field and `vetta.event` gains\n * no column, so one reader of `{session_id, seq}` still sees every event in one order.\n */\n \"thread.created\",\n \"thread.running\",\n \"thread.idle\",\n \"thread.terminated\",\n // core-gaps: contracts (`canonical-spec §32.8`, §33.5, §36.3, §37.3, §38.3)\n \"browser.session.opened\",\n \"browser.session.closed\",\n \"browser.context.saved\",\n \"browser.context.granted\",\n \"browser.context.revoked\",\n \"media.job.queued\",\n \"media.job.completed\",\n \"media.job.failed\",\n \"file.imported\",\n \"app.db.migrated\",\n \"app.storage.bucket.created\",\n \"app.storage.bucket.deleted\",\n // identity money (`canonical-spec §44.3`, §45.3). Every one of these is driven over REST, which\n // has no session stream, so the org's webhook subscriptions are the only push a customer gets.\n \"wallet.created\",\n \"wallet.policy.updated\",\n \"wallet.transaction.confirmed\",\n \"wallet.swept\",\n \"card.issued\",\n \"card.failed\",\n \"card.cancelled\",\n \"card.refunded\",\n \"card.credentials_revealed\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\nexport const EventSchema = z.object({\n id: idOf(\"evt\"),\n seq: z.number().int().positive(),\n type: EventTypeSchema,\n session_id: idOf(\"ses\"),\n data: z.record(z.string(), z.unknown()),\n created_at: Timestamp,\n});\nexport type Event = z.infer<typeof EventSchema>;\n\n/**\n * `thread.*` data. Loose on purpose: `thread_id` is the whole added contract, and each event is\n * free to carry more (which member, why it stopped) without a schema change per field.\n */\nexport const ThreadEventDataSchema = z.looseObject({ thread_id: idOf(\"ses\") });\n\n/**\n * `tool.confirm.resolved` data (§8, ADR-0764). `decision` and `scope` are the `tool_confirmations`\n * vocabulary (§7). `actor` is `null` only for a decision queued by a caller that predates it;\n * `proposed_args` is `null` when no parked row matched; `final_args` is what runs — the person's\n * edit of a template install's answers (ADR-1030), otherwise equal to `proposed_args`.\n */\nexport const ToolConfirmResolvedDataSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().nullable(),\n scope: z.enum([\"call\", \"session\"]),\n actor: PrincipalSchema.nullable(),\n decided_at: Timestamp,\n proposed_args: z.record(z.string(), z.unknown()).nullable(),\n final_args: z.record(z.string(), z.unknown()).nullable(),\n});\nexport type ToolConfirmResolvedData = z.infer<typeof ToolConfirmResolvedDataSchema>;\n\n/**\n * `tool.confirm.answered` data (§8, ADR-1049): the answers exactly as `POST …/answers` took them.\n * Without it an answer reached only the model's transcript, and no reader of the log could say what\n * the person had said.\n */\nexport const ToolConfirmAnsweredDataSchema = z.object({\n tool_call_id: z.string(),\n answers: AnswersSchema,\n answered_at: Timestamp,\n});\nexport type ToolConfirmAnsweredData = z.infer<typeof ToolConfirmAnsweredDataSchema>;\n\n/** `session.usage` data — emitted before every idle/terminal transition (§10, §15). */\nexport const SessionUsageDataSchema = z.object({\n token_usage: TokenUsageSchema,\n consumed_micro_usd: MicroUsdField.nonnegative(),\n active_seconds: z.number().nonnegative(),\n tool_calls: z.number().int().nonnegative(),\n});\n","/**\n * The team board — the shared, durable coordination surface a coordinator session and every thread\n * it delegates to read and write (canonical-spec §28).\n *\n * The statuses are **fixed**, not configurable columns. A per-team column list would make every\n * board tool's contract depend on the agent's config: `board_write` could not name a legal status\n * without first reading the board, and no two teams' transcripts would be comparable. Four states\n * cover the thing a board is for — what is queued, what is being worked, what is stuck, what is\n * finished — and `blocked_by` carries the *reason* a card is stuck as data rather than as a lane.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const BOARD_STATUSES = [\"todo\", \"doing\", \"blocked\", \"done\"] as const;\nexport const BoardStatusSchema = z.enum(BOARD_STATUSES);\nexport type BoardStatus = z.infer<typeof BoardStatusSchema>;\n\n/**\n * How many cards stand in each column. Written out as four fields rather than a record keyed by\n * `BoardStatusSchema` for the same reason the statuses are fixed: a reader is owed all four keys\n * even when a column is empty, and a partial record would make `0` and \"absent\" the same answer.\n */\nexport const BoardCountsSchema = z.object({\n todo: z.number().int().nonnegative(),\n doing: z.number().int().nonnegative(),\n blocked: z.number().int().nonnegative(),\n done: z.number().int().nonnegative(),\n});\nexport type BoardCounts = z.infer<typeof BoardCountsSchema>;\n\n/**\n * One board per **agent** — `unique (org_id, agent_id)`, migration 0024 — so a team's cards outlive\n * the coordinator session that opened them. This said `session_id` until the board object reached\n * the wire, which was a description of a board nothing had ever stored.\n *\n * The counts are the whole reason the object is worth serving. Everything else on a board is\n * already on its cards; how many stand in each column is the one fact a page of cards cannot state,\n * because a page is truncated and a count is not.\n */\nexport const BoardSchema = z.object({\n id: idOf(\"brd\"),\n object: z.literal(\"board\"),\n agent_id: idOf(\"agt\"),\n cards: BoardCountsSchema,\n created_at: Timestamp,\n});\nexport type Board = z.infer<typeof BoardSchema>;\n\n/**\n * A unit of work. `assignee` is an agent's name — not an id — because that is what a coordinator\n * writes in a tool call and what a member recognises as itself; `null` is unclaimed.\n *\n * Assignment is the wake (§28.18): `woken_session_id` is the session the board started for the\n * assignee, `null` until it has — which is what makes the card *due*. `reported_status` is the\n * `done`/`blocked` the board's owner was last told about. Neither is writable by a client.\n */\nexport const BoardCardSchema = z.object({\n id: idOf(\"crd\"),\n object: z.literal(\"board_card\"),\n board_id: idOf(\"brd\"),\n title: z.string().min(1),\n /** The brief — what was asked. */\n body: z.string(),\n /** What the holder wrote back; a `done` carries one. */\n note: z.string().nullable().default(null),\n status: BoardStatusSchema,\n assignee: z.string().nullable(),\n /** The cards this one waits on. A `blocked` card with an empty list is stuck on the world. */\n blocked_by: z.array(idOf(\"crd\")),\n // The wake fields default on read: a reader whose API predates one still gets the card (§28.11).\n woken_session_id: idOf(\"ses\").nullable().default(null),\n reported_status: BoardStatusSchema.nullable().default(null),\n /** Sessions the board has started for this card; the third is its last (§28.18). */\n wake_count: z.number().int().nonnegative().default(0),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type BoardCard = z.infer<typeof BoardCardSchema>;\n\n/** The team's channel on a card: any thread can add one, the whole team reads it. */\nexport const BoardCommentSchema = z.object({\n id: idOf(\"bcm\"),\n object: z.literal(\"board_comment\"),\n card_id: idOf(\"crd\"),\n /**\n * Who wrote it, as an id the server derived — never a name the caller supplied. A member's\n * comment carries the `ses_` id of the thread that wrote it; a person's carries their `usr_` or\n * `key_` principal. The prefix is what lets a reader tell an agent's comment from a person's,\n * which is the distinction a free-text author field could not make and could be used to forge.\n */\n author: z.string(),\n body: z.string(),\n created_at: Timestamp,\n});\nexport type BoardComment = z.infer<typeof BoardCommentSchema>;\n","/**\n * Identities — the named personas an agent acts as (`canonical-spec §22`).\n *\n * An identity is a small durable record: a `name` and a `description` the model reads so it knows\n * *who it is being*, plus the concrete endpoints that persona owns. The endpoints are deliberately\n * **specific strings, never booleans** — an identity does not \"have email\", it owns\n * `ava@acme-mail.com` — because routing, policy scoping and inbound matching all key off the exact\n * address (`docs/identity/personas.mdx`).\n *\n * The four endpoint arrays are denormalised reads of four sub-resources this build does not serve:\n * domains, inboxes, numbers and connections each need a vendor credential that does not exist yet\n * (see `progress.md`). They are on the object because the wire contract publishes them and a caller\n * must be able to read `[]` and know the answer is \"none\", rather than have the field vanish and\n * not know whether it asked the wrong question. Nothing writes them today.\n */\n\nimport { z } from \"zod\";\nimport { Metadata, Timestamp, idOf } from \"./common\";\n\n/** Bounded because it is surfaced to the model verbatim, and an unbounded name is a prompt. */\nexport const IDENTITY_NAME_MAX = 128;\nexport const IDENTITY_DESCRIPTION_MAX = 1024;\n\nexport const IdentitySchema = z.object({\n id: idOf(\"idn\"),\n object: z.literal(\"identity\"),\n /** Human-facing persona name. Surfaced to the model so it acts in character. */\n name: z.string().min(1).max(IDENTITY_NAME_MAX),\n /** What the persona is for. The model reads it to choose tone, scope and endpoint. */\n description: z.string().max(IDENTITY_DESCRIPTION_MAX).nullable(),\n /** Inbox addresses (`localpart@domain`) this identity owns. */\n emails: z.array(z.string()),\n /** Provisioned numbers in E.164. */\n phones: z.array(z.string()),\n /** Verified web domains reachable through this identity's inboxes. */\n domains: z.array(z.string()),\n /** `conn_` ids of authorized third-party connections. */\n connections: z.array(z.string()),\n metadata: Metadata,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Identity = z.infer<typeof IdentitySchema>;\n","/** Computers, snapshots, volumes, skills, files, deployments (canonical-spec §2, §12, §13). */\n\nimport { z } from \"zod\";\nimport { BrowserOptionsSchema } from \"./browser\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, WindowSchema, idOf } from \"./common\";\nimport { FileLibraryFieldsSchema } from \"./files-library\";\nimport { SessionStatusSchema } from \"./session\";\n\nexport const ComputerStatusSchema = z.enum([\"creating\", \"running\", \"paused\", \"failed\", \"destroyed\"]);\nexport type ComputerStatus = z.infer<typeof ComputerStatusSchema>;\n\nexport const VolumeSchema = z.object({\n id: idOf(\"vol\"),\n size_gb: z.number().int().positive(),\n mount_path: z.string(),\n});\n\nexport const ComputerSchema = z.object({\n id: idOf(\"cmp\"),\n object: z.literal(\"computer\"),\n name: z.string(),\n vcpu: z.number().int().positive(),\n memory_mb: z.number().int().positive(),\n disk_gb: z.number().int().positive(),\n status: ComputerStatusSchema,\n // core-gaps: U2-browser-api — the whole option object (§32.2); `{ allowed_domains }` still parses.\n browser: BrowserOptionsSchema.nullable(),\n volume: VolumeSchema.nullable(),\n snapshot_id: idOf(\"snp\").nullable(),\n /**\n * The agent this computer belongs to (§41.8, ADR-0849); `null` for one made by `POST /v1/computers`.\n * Defaulted so a reply from an older control plane parses.\n */\n agent_id: idOf(\"agt\").nullable().default(null),\n created_at: Timestamp,\n});\nexport type Computer = z.infer<typeof ComputerSchema>;\n\nexport const SnapshotSchema = z.object({\n snapshot_id: idOf(\"snp\"),\n computer_id: idOf(\"cmp\"),\n created_at: Timestamp,\n});\n\n/** Computer workspace (§41): what a box is doing, what ran on it, what is on it, what browsed from it. */\n\n/** One in-VM sample (§41.1). `null` on the inspect of anything but a `running` box — a read never wakes one. */\nexport const ComputerProbeSchema = z.object({\n sampled_at: Timestamp,\n uptime_seconds: z.number().int().nonnegative(),\n processes: z.number().int().nonnegative(),\n load_1m: z.number().nonnegative(),\n memory_used_mb: z.number().int().nonnegative(),\n memory_total_mb: z.number().int().positive(),\n disk_used_gb: z.number().nonnegative(),\n disk_total_gb: z.number().positive(),\n});\nexport type ComputerProbe = z.infer<typeof ComputerProbeSchema>;\n\nexport const ComputerInspectSchema = z.object({\n object: z.literal(\"computer_inspect\"),\n id: idOf(\"cmp\"),\n status: ComputerStatusSchema,\n last_active_at: Timestamp.nullable(),\n /** Where the provider's file API is rooted (§41.1); `null` when it does not say. */\n home: z.string().min(1).nullable(),\n probe: ComputerProbeSchema.nullable(),\n});\nexport type ComputerInspect = z.infer<typeof ComputerInspectSchema>;\n\n/** Output cap per stream on a recorded command (§41.3); a cut sets `truncated`. */\nexport const COMMAND_OUTPUT_CAP = 65_536;\n\nexport const ComputerCommandSchema = z.object({\n id: idOf(\"cmd\"),\n object: z.literal(\"computer_command\"),\n computer_id: idOf(\"cmp\"),\n command: z.string(),\n exit_code: z.number().int().nullable(),\n timed_out: z.boolean(),\n duration_ms: z.number().int().nonnegative(),\n stdout: z.string().max(COMMAND_OUTPUT_CAP),\n stderr: z.string().max(COMMAND_OUTPUT_CAP),\n truncated: z.boolean(),\n actor: PrincipalSchema,\n created_at: Timestamp,\n});\nexport type ComputerCommand = z.infer<typeof ComputerCommandSchema>;\n\n/** One `data:` frame of `POST …/exec/stream` (§41.2): output as it arrives, then exactly one `exit`. */\nexport const ExecStreamFrameSchema = z.union([\n z.object({ stdout: z.string() }),\n z.object({ stderr: z.string() }),\n z.object({\n exit: z.object({\n exit_code: z.number().int().nullable(),\n timed_out: z.boolean(),\n duration_ms: z.number().int().nonnegative(),\n command_id: idOf(\"cmd\"),\n }),\n }),\n]);\nexport type ExecStreamFrame = z.infer<typeof ExecStreamFrameSchema>;\n\nexport const FileEntryTypeSchema = z.enum([\"file\", \"directory\", \"symlink\", \"other\"]);\nexport const FileEntrySchema = z.object({\n name: z.string().min(1),\n path: z.string().min(1),\n type: FileEntryTypeSchema,\n size_bytes: z.number().int().nonnegative(),\n /** POSIX `st_mode`. */\n mode: z.number().int().nonnegative(),\n modified_at: Timestamp.nullable(),\n});\nexport type FileEntry = z.infer<typeof FileEntrySchema>;\n\nexport const ComputerUpdateSchema = z.strictObject({ name: z.string().min(1).max(200) });\nexport type ComputerUpdate = z.infer<typeof ComputerUpdateSchema>;\n\nexport const SkillSchema = z.object({\n id: idOf(\"skl\"),\n object: z.literal(\"skill\"),\n name: z.string(),\n description: z.string().nullable(),\n latest_version: z.number().int().positive(),\n created_at: Timestamp,\n});\n\n/**\n * One of an agent's `skills[]` entries, resolved at session start (§13): `slug` took the latest\n * version *then*, `slug@N` is frozen at `N`, and neither moves for the life of the session.\n *\n * It travels API → session runtime because that is where the two things that need it live: the\n * harness advertises `name`/`description` to the model and serves the body from `storage_key` on\n * demand (ADR-0106.4), and `read_skill` reads the same key. Resolving again inside the runtime\n * would re-resolve a floating `slug` mid-session, which §13 forbids.\n */\nexport const ResolvedSkillRefSchema = z.object({\n /** The reference exactly as the agent version wrote it: `slug` or `slug@N`. */\n ref: z.string().min(1),\n slug: z.string().min(1),\n version: z.number().int().positive(),\n description: z.string(),\n storage_key: z.string().min(1),\n});\n\nexport type ResolvedSkillRef = z.infer<typeof ResolvedSkillRefSchema>;\n\n/** Skill versions are immutable and content-addressed (§13). */\nexport const SkillVersionSchema = z.object({\n version: z.number().int().positive(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n size_bytes: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\n\n/**\n * One version of a skill the PLATFORM ships (§31.9) — the `naive/slug` half of §13's grammar. No\n * `id` and no organization: the catalogue is identical for every tenant and is addressed by\n * `(slug, version)` and nothing else. `content_hash` is the same lowercase sha-256 an organization\n * skill version carries as `sha256`; identical bytes never mint a version.\n *\n * The list (`GET /v1/skills/catalog`) returns this, newest version per slug, WITHOUT the body — the\n * body is the expensive half and is read on the version route (§13's progressive disclosure).\n */\nexport const SkillCatalogEntrySchema = z.object({\n object: z.literal(\"skill_catalog_entry\"),\n slug: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),\n version: z.number().int().positive(),\n name: z.string().min(1),\n description: z.string(),\n tags: z.array(z.string().min(1)),\n content_hash: z.string().regex(/^[0-9a-f]{64}$/),\n published_at: Timestamp,\n});\nexport type SkillCatalogEntry = z.infer<typeof SkillCatalogEntrySchema>;\n\n/** `GET /v1/skills/catalog/{slug}/versions/{n}` — the entry with its `SKILL.md` body. */\nexport const SkillCatalogVersionSchema = SkillCatalogEntrySchema.extend({ content: z.string() });\nexport type SkillCatalogVersion = z.infer<typeof SkillCatalogVersionSchema>;\n\nexport const FileSchema = z.object({\n id: idOf(\"fil\"),\n object: z.literal(\"file\"),\n name: z.string(),\n content_type: z.string(),\n size_bytes: z.number().int().nonnegative(),\n scope: z.enum([\"session\", \"published\"]),\n session_id: idOf(\"ses\").nullable(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n created_at: Timestamp,\n // The asset-library fields (`canonical-spec §36.1`), all nullable or defaulted.\n ...FileLibraryFieldsSchema.shape,\n /** The agent of `session_id`, joined at read (§36.1, ADR-0887); a writer never sets it. */\n agent_id: idOf(\"agt\").nullable().optional(),\n});\n/** `File` is a DOM global on a Worker, so the wire object is `FileObject` in TypeScript. */\nexport type FileObject = z.infer<typeof FileSchema>;\n\n/**\n * Whether a schedule will actually fire, which `enabled` alone cannot say (ADR-0104):\n * `paused` is `enabled: false`, and `unscheduled` is an enabled schedule on a deploy that runs no\n * clock — its `next_run_at` is `null`, because a date no tick will ever honour is worse than none.\n */\nexport const ScheduleStatusSchema = z.enum([\"scheduled\", \"paused\", \"unscheduled\"]);\nexport type ScheduleStatus = z.infer<typeof ScheduleStatusSchema>;\n\n/** A cron deployment. `agent_version` pins the exact version that fires (§12). */\nexport const DeploymentSchema = z.object({\n id: idOf(\"dep\"),\n object: z.literal(\"deployment\"),\n agent_id: idOf(\"agt\"),\n /** A pin. `null` tracks the agent's `current_version` on every fire (§12). */\n agent_version: z.number().int().positive().nullable(),\n cron: z.string(),\n /** IANA zone the `cron` is read in. \"0 9 * * 1\" means 09:00 *here*, across DST (ADR-0074). */\n timezone: z.string(),\n input_template: z.string(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n window: WindowSchema,\n /**\n * URL POSTed with the `session.idle` envelope when a fire goes idle; `null` pushes nothing.\n *\n * `https` for the same reason `POST /v1/webhooks` requires it — setting this materialises one of\n * those endpoints, and a signed delivery over cleartext is not a delivery. Until the push was\n * wired this field went nowhere, so nothing can be relying on an `http://` value (ADR-0161).\n */\n on_idle: z.url().startsWith(\"https://\", { error: \"a webhook URL must be https\" }).nullable(),\n /**\n * The persona every fire speaks as, or `null` to run as nobody (§22). Written as an `idn_` id\n * **or** the persona's name, the way a session names one, and always echoed as the id: a fire at\n * 3am must not be silenced by someone renaming the persona at noon.\n */\n identity: idOf(\"idn\").nullable(),\n enabled: z.boolean(),\n /** Derived per deploy, never stored — the row cannot know whether a clock is watching it. */\n schedule_status: ScheduleStatusSchema,\n /** The next fire, or `null` when nothing will fire it (`schedule_status` says which). */\n next_run_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Deployment = z.infer<typeof DeploymentSchema>;\n\n/** The persisted half: everything but the derived `schedule_status` (ADR-0104). */\nexport type StoredDeployment = Omit<Deployment, \"schedule_status\">;\n\nexport const DeploymentRunSchema = z.object({\n id: idOf(\"run\"),\n session_id: idOf(\"ses\"),\n status: SessionStatusSchema,\n started_at: Timestamp.nullable(),\n});\nexport type DeploymentRun = z.infer<typeof DeploymentRunSchema>;\n","/**\n * core-gaps: contracts — the library fields a file gains (`canonical-spec §36`). U7 composes them\n * into `FileSchema` with `FileSchema.extend(FileLibraryFieldsSchema.shape)`; every field is\n * nullable or defaulted so each existing row and writer stays valid.\n */\n\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\n\nexport const FILE_KINDS = [\"image\", \"video\", \"audio\", \"document\", \"other\"] as const;\nexport const FileKindSchema = z.enum(FILE_KINDS);\nexport type FileKind = z.infer<typeof FileKindSchema>;\n\nexport const FILE_SOURCE_TYPES = [\n \"upload\",\n \"url_import\",\n \"image_generation\",\n \"video_generation\",\n \"video_clipping\",\n \"screenshot\",\n \"speech_generation\",\n] as const;\nexport const FileSourceTypeSchema = z.enum(FILE_SOURCE_TYPES);\nexport type FileSourceType = z.infer<typeof FileSourceTypeSchema>;\n\nexport const FileSourceSchema = z.object({\n type: FileSourceTypeSchema,\n job_id: z.union([idOf(\"med\"), idOf(\"clj\")]).nullable(),\n url: z.string().url().nullable(),\n /** What a generator was asked with (§36.1, ADR-0886); absent on every other writer's row. */\n model: z.string().nullable().optional(),\n prompt: z.string().nullable().optional(),\n});\nexport type FileSource = z.infer<typeof FileSourceSchema>;\n\nexport const FileTagsSchema = z.array(z.string().min(1).max(64)).max(32);\n\nexport const FileLibraryFieldsSchema = z.object({\n title: z.string().max(256).nullable().default(null),\n description: z.string().max(4_096).nullable().default(null),\n tags: FileTagsSchema.default([]),\n kind: FileKindSchema.default(\"other\"),\n source: FileSourceSchema.nullable().default(null),\n thumbnail_file_id: idOf(\"fil\").nullable().default(null),\n width: z.number().int().positive().nullable().default(null),\n height: z.number().int().positive().nullable().default(null),\n duration_seconds: z.number().nonnegative().nullable().default(null),\n});\nexport type FileLibraryFields = z.infer<typeof FileLibraryFieldsSchema>;\n\n/** `PATCH /v1/files/{id}` — the three fields a customer edits. */\nexport const UpdateFileSchema = z.object({\n title: z.string().max(256).nullable().optional(),\n description: z.string().max(4_096).nullable().optional(),\n tags: FileTagsSchema.optional(),\n});\n\n/** `POST /v1/files/imports` — the route refuses private hosts and bodies over the upload cap. */\nexport const ImportFileSchema = z.object({\n url: z.string().url().startsWith(\"http\"),\n title: z.string().max(256).optional(),\n description: z.string().max(4_096).optional(),\n tags: FileTagsSchema.optional(),\n});\n\n/** `content_type` → `kind`, decided once at write and stored. */\nexport function fileKindOf(contentType: string): FileKind {\n const lower = contentType.toLowerCase();\n const [type] = lower.split(\"/\");\n if (type === \"image\" || type === \"video\" || type === \"audio\") return type;\n if (type === \"text\" || lower.includes(\"pdf\") || lower.includes(\"document\")) {\n return \"document\";\n }\n return \"other\";\n}\n","/**\n * The three identity primitives that touch the outside world — a **web domain**, an **email\n * inbox** on it, and a **phone number** — plus the normalised **inbound message** that arrives at\n * either endpoint and the **outbound message** one sent (`canonical-spec §24`,\n * `docs/identity/{domains,email,phone,inbound}.mdx`).\n *\n * The gates at the bottom are the whole point of this file. A domain carries four independent\n * readiness tracks and each capability hangs off exactly one of them; a number cannot text until a\n * carrier has approved its campaign. Those rules are pure functions here, tested here, and called\n * from the routes — so \"deliverable\" is a computed fact and never an assumption. Sending mail from\n * a domain whose SPF/DKIM is not published is the worst outcome available to us: it does not fail,\n * it silently lands in spam.\n */\n\nimport { z } from \"zod\";\nimport { VettaError } from \"../errors\";\nimport { PrincipalSchema, Timestamp, idOf } from \"./common\";\n\n// ── Domain ────────────────────────────────────────────────────────────────────\n\n/**\n * Where the domain lives. A purchased domain uses the same mail/DNS readiness tracks, but its\n * creation is separately gated by `billing:write` and an explicit live-price ceiling.\n */\nexport const DomainKindSchema = z.enum([\"system\", \"external\", \"purchased\"]);\nexport type DomainKind = z.infer<typeof DomainKindSchema>;\n\n/** Email/company track. `failed` is ours: the docs give no terminal state and one is needed. */\nexport const DomainStatusSchema = z.enum([\"pending_dns\", \"active\", \"failed\"]);\n/** Mail DNS (SPF/DKIM) track — what **sending** hangs on. */\nexport const DomainDnsStatusSchema = z.enum([\"pending_verification\", \"provisioned\", \"failed\"]);\n/**\n * Inbound (MX) track — what **receiving** hangs on. Not in `docs/identity/domains.mdx`, which\n * gates receive on \"verified for inbound at the email layer\" in two tables and then exposes no\n * field for it, leaving the gate unqueryable. Doc-fix owed (ADR-0119).\n */\nexport const DomainInboundStatusSchema = z.enum([\"pending\", \"verified\", \"failed\"]);\n/** App/HTTP track, entirely independent of the three above. */\nexport const DomainAppConnectStatusSchema = z.enum([\"pending\", \"connected\", \"failed\"]);\n\nexport const DnsRecordSchema = z.object({\n type: z.enum([\"TXT\", \"CNAME\", \"MX\"]),\n host: z.string(),\n value: z.string(),\n priority: z.number().int().nullable(),\n /** Vetta owns this record: `_dmarc`, DKIM, inbound MX. The agent may read it, never write it. */\n managed: z.boolean(),\n});\nexport type DnsRecord = z.infer<typeof DnsRecordSchema>;\n\nexport const DomainSchema = z.object({\n id: idOf(\"dom\"),\n object: z.literal(\"domain\"),\n /** A domain belongs to the **organization**, not to one identity: two identities share one. */\n name: z.string(),\n kind: DomainKindSchema,\n status: DomainStatusSchema,\n dns_status: DomainDnsStatusSchema,\n inbound_status: DomainInboundStatusSchema,\n app_connect_status: DomainAppConnectStatusSchema,\n records: z.array(DnsRecordSchema),\n last_verified_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Domain = z.infer<typeof DomainSchema>;\n\n/** A fully-qualified domain name, lowercase, no trailing dot. */\nexport const FQDN = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/;\n\n/**\n * Records the agent may never edit — DKIM, DMARC and the inbound MX keep mail working at all.\n *\n * Matched **label by label**, not by suffix: an email layer asked for a subdomain returns its\n * records relative to the registrable zone, so DKIM for `sub.example.com` arrives as the host\n * `sel._domainkey.sub`. A suffix test calls that editable and invites an agent to delete the key\n * that signs its own mail (observed live, 2026-08-22).\n */\nexport function isManagedHost(host: string): boolean {\n const h = host.toLowerCase().replace(/\\.$/, \"\");\n if (h === \"@\") return true;\n return h.split(\".\").some((label) => label === \"_dmarc\" || label === \"_domainkey\");\n}\n\n// ── Email inbox ───────────────────────────────────────────────────────────────\n\n/** Manual localparts: the documented character class, floored at 2 and capped at RFC 5321's 64. */\nexport const LOCALPART = /^[a-z0-9._-]{2,64}$/;\n/** Auto-provisioned localparts are derived from the agent name and capped at 32. */\nexport const AUTO_LOCALPART_MAX = 32;\n\nexport const EmailInboxSchema = z.object({\n id: idOf(\"eml\"),\n object: z.literal(\"email_inbox\"),\n identity_id: idOf(\"idn\"),\n domain_id: idOf(\"dom\"),\n address: z.string(),\n localpart: z.string(),\n /** Inbound routing keys off this: mail to the address wakes exactly this agent. */\n owning_agent_id: idOf(\"agt\"),\n status: z.enum([\"active\", \"disabled\"]),\n created_at: Timestamp,\n});\nexport type EmailInbox = z.infer<typeof EmailInboxSchema>;\n\n/** `\"Ava Sales\"` → `ava-sales`, then `ava-sales-2`, `ava-sales-3` … against what is already taken. */\nexport function autoLocalpart(agentName: string, taken: ReadonlySet<string>): string {\n const base =\n agentName\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, AUTO_LOCALPART_MAX)\n .replace(/-+$/, \"\") || \"agent\";\n if (!taken.has(base)) return base;\n for (let n = 2; ; n += 1) {\n const suffix = `-${n}`;\n const candidate = `${base.slice(0, AUTO_LOCALPART_MAX - suffix.length)}${suffix}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n\n// ── Phone number ──────────────────────────────────────────────────────────────\n\n/** `sole_prop`, not the docs' CLI `sole-prop`: every other enum on the wire is snake_case. */\nexport const PhoneTierSchema = z.enum([\"sole_prop\", \"standard\"]);\nexport const BrandStatusSchema = z.enum([\"none\", \"pending_verification\", \"verified\", \"rejected\"]);\nexport const CampaignStatusSchema = z.enum([\"none\", \"pending\", \"approved\", \"rejected\"]);\n\nexport const PhoneNumberSchema = z.object({\n id: idOf(\"pho\"),\n object: z.literal(\"phone_number\"),\n identity_id: idOf(\"idn\"),\n e164: z.string(),\n country: z.string(),\n capabilities: z.object({\n /** Live the moment the number is bought — inbound never waits on carrier registration. */\n sms_inbound: z.boolean(),\n /** True **iff** `campaign_status === \"approved\"`. Nothing else may set it. */\n sms_outbound: z.boolean(),\n /** Voice is not a P2 capability; the field exists so its absence is explicit. */\n voice: z.literal(false),\n }),\n tier: PhoneTierSchema,\n brand_status: BrandStatusSchema,\n campaign_status: CampaignStatusSchema,\n provisioned_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type PhoneNumber = z.infer<typeof PhoneNumberSchema>;\n\nexport const E164 = /^\\+[1-9]\\d{6,14}$/;\n\n// ── Inbound message ───────────────────────────────────────────────────────────\n\nexport const InboundMessageSchema = z.object({\n id: idOf(\"inb\"),\n object: z.literal(\"inbound_message\"),\n channel: z.enum([\"email\", \"sms\"]),\n identity_id: idOf(\"idn\"),\n /** The `eml_`/`pho_` endpoint it arrived at — the persona is decided by *where*, not by *who*. */\n endpoint_id: z.string(),\n from: z.string(),\n to: z.string(),\n subject: z.string().nullable(),\n text: z.string(),\n /** SPF/DKIM/DMARC for mail, carrier origin for SMS. Kept for the audit of why it was accepted. */\n auth: z.record(z.string(), z.string()),\n /** The session this message woke. Null until the wake seam lands (see ADR-0120). */\n session_id: idOf(\"ses\").nullable(),\n received_at: Timestamp,\n /**\n * When a person marked it read (`POST …/messages/{mid}/read`); `null` is unread. Defaulted so a\n * reply from an older control plane parses (ADR-1076).\n */\n read_at: Timestamp.nullable().default(null),\n});\nexport type InboundMessage = z.infer<typeof InboundMessageSchema>;\n\n// ── Outbound message ──────────────────────────────────────────────────────────\n\n/**\n * A message the persona sent, kept by us after the provider accepted it (ADR-1076). Written by\n * both doors that send: the API route (`actor` names the key or person) and the `email.send` tool\n * (`sent_by_agent_id` names the agent). Only mail is recorded today; `channel` is the inbound\n * enum because a text is the same kind of row.\n */\nexport const OutboundMessageSchema = z.object({\n id: idOf(\"out\"),\n object: z.literal(\"outbound_message\"),\n channel: InboundMessageSchema.shape.channel,\n identity_id: idOf(\"idn\"),\n /** The `eml_` endpoint it was sent from. */\n endpoint_id: z.string(),\n from: z.string(),\n to: z.array(z.string()),\n subject: z.string().nullable(),\n text: z.string(),\n sent_by_agent_id: idOf(\"agt\").nullable(),\n actor: PrincipalSchema.nullable(),\n sent_at: Timestamp,\n});\nexport type OutboundMessage = z.infer<typeof OutboundMessageSchema>;\n\n// ── The gates ─────────────────────────────────────────────────────────────────\n\n/**\n * Creating an inbox needs the company track cleared. `job_not_ready` and not `validation_failed`:\n * the caller did nothing wrong and the call will succeed once DNS propagates, so a durable runtime\n * must retry rather than give up (ADR-0118).\n */\nexport function assertInboxCreatable(domain: Domain): void {\n if (domain.status === \"active\") return;\n throw new VettaError(\n \"job_not_ready\",\n `domain ${domain.name} is ${domain.status}; an inbox needs status \"active\"`,\n \"domain_id\",\n );\n}\n\n/** Sending needs SPF/DKIM published and verified. Un-gated, mail silently lands in spam. */\nexport function assertSendable(domain: Domain): void {\n if (domain.dns_status === \"provisioned\") return;\n throw new VettaError(\n \"job_not_ready\",\n `domain ${domain.name} is not deliverable: dns_status is ${domain.dns_status}, sending needs \"provisioned\"`,\n );\n}\n\n/**\n * Receiving needs MX in place. Not an assert: an inbound message for a domain that cannot receive\n * is **dropped**, never bounced back at the sender and never turned into a wake.\n */\nexport function canReceive(domain: Domain): boolean {\n return domain.inbound_status === \"verified\";\n}\n\n/** Outbound SMS is refused until the carrier campaign is approved — this is a legal gate, not ours. */\nexport function assertSmsSendable(phone: PhoneNumber): void {\n if (phone.campaign_status === \"approved\") return;\n throw new VettaError(\n \"compliance_pending\",\n `outbound messaging for ${phone.e164} is not registered yet: campaign is ${phone.campaign_status}`,\n );\n}\n\n/** The one invariant tying the two together — nothing else may write `sms_outbound`. */\nexport function smsCapabilities(campaign: z.infer<typeof CampaignStatusSchema>): {\n sms_inbound: boolean;\n sms_outbound: boolean;\n voice: false;\n} {\n return { sms_inbound: true, sms_outbound: campaign === \"approved\", voice: false };\n}\n","/**\n * Hosted web applications (`canonical-spec §29`). An app is an **organization-level** resource —\n * a deployed site with, for `fullstack`, a managed backend provisioned per app. It is never owned\n * by an agent: agents are immutable versioned config, an app is production infrastructure that\n * outlives any agent or session. Provenance lives in the audit log (§17).\n *\n * Nothing provider-shaped appears here: the hosting and backend project handles are server\n * columns, and the wire object carries only what a customer may see.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\nimport type { Scope } from \"./org\";\n\nexport const AppTypeSchema = z.enum([\"frontend_only\", \"fullstack\"]);\nexport type AppType = z.infer<typeof AppTypeSchema>;\n\n/** `deleted` is computed off the soft-delete column, never stored in the status column. */\nexport const AppStatusSchema = z.enum([\"provisioning\", \"active\", \"error\"]);\nexport type AppStatus = z.infer<typeof AppStatusSchema>;\n\n/**\n * The path of the MCP endpoint an app serves (`§29.1`) — an absolute path, so the runtime can\n * resolve it as `url + mcp` whatever the app's current canonical URL is. Shared by the API and IaC.\n */\nexport const AppMcpPathSchema = z.string().regex(/^\\/\\S*$/, \"must be an absolute path beginning with /\").max(128);\n\nexport const AppSchema = z.object({\n id: idOf(\"app\"),\n object: z.literal(\"app\"),\n name: z.string(),\n description: z.string().nullable(),\n type: AppTypeSchema,\n /**\n * The customer's own project name that made this app, or `null` for one made outside a project\n * (ADR-0375). Customer-visible, unlike the provider handles: it is the word the customer typed,\n * and the refusal that guards a name quotes it.\n */\n project: z.string().nullable(),\n status: AppStatusSchema,\n /** The address the app answers on — platform hostname until a custom domain connects. */\n url: z.string().nullable(),\n /** White-label words when `status` is `error`; never the provider's. */\n error: z.string().nullable(),\n /** Where the app serves MCP, or `null`. The bearer token for it is a server column. */\n mcp: AppMcpPathSchema.nullable(),\n /**\n * Is this a gated blueprint dashboard — one the Studio opens through `/apps/{id}/open` rather\n * than linking its `url` (`§29.1`)? True when the platform holds the app's `DASHBOARD_TOKEN`\n * or a secret of that name exists on the app; derived on read, never stored.\n */\n dashboard: z.boolean(),\n created_at: Timestamp,\n});\nexport type App = z.infer<typeof AppSchema>;\n\nexport const AppDeploymentStatusSchema = z.enum([\"queued\", \"building\", \"ready\", \"error\"]);\nexport type AppDeploymentStatus = z.infer<typeof AppDeploymentStatusSchema>;\n\nexport const AppDeploymentSchema = z.object({\n id: idOf(\"apd\"),\n object: z.literal(\"app_deployment\"),\n app_id: idOf(\"app\"),\n status: AppDeploymentStatusSchema,\n url: z.string().nullable(),\n error: z.string().nullable(),\n /** The client's opaque digest of the files, echoed verbatim so it can skip an unchanged deploy. */\n content_hash: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type AppDeployment = z.infer<typeof AppDeploymentSchema>;\n\n/** The file-map a deployment was posted with, kept so an agent can open and re-ship it (§29.2). */\nexport const AppDeploymentFilesSchema = z.object({\n object: z.literal(\"app_deployment_files\"),\n deployment_id: idOf(\"apd\"),\n files: z.record(z.string().min(1), z.string()),\n});\nexport type AppDeploymentFiles = z.infer<typeof AppDeploymentFilesSchema>;\n\n/** Metadata only — the value goes to the host project's environment and is never readable back. */\nexport const AppSecretSchema = z.object({\n object: z.literal(\"app_secret\"),\n name: z.string(),\n /** The client's opaque digest of the value, echoed verbatim so it can skip an unchanged write. */\n value_hash: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type AppSecret = z.infer<typeof AppSecretSchema>;\n\n/**\n * A one-click way into an app that gates itself with a platform-generated bearer (`§29.7`).\n *\n * `ticket` is a short-lived, signed statement of who is opening the app — an HMAC keyed by the\n * app's `DASHBOARD_TOKEN`, never the value (§29.10) — and `url` is the app's own endpoint that trades one for a session\n * cookie. It is posted, not linked: a credential in a query string lands in the app's server logs,\n * the browser's history and every later `Referer`.\n */\nexport const AppEntrySchema = z.object({\n object: z.literal(\"app_entry\"),\n url: z.string(),\n ticket: z.string(),\n});\nexport type AppEntry = z.infer<typeof AppEntrySchema>;\n\n/**\n * How a person gets into an app's dashboard without the Studio (`§29.2`, `§29.7`): the app's\n * address and its platform-generated `DASHBOARD_PASSWORD`, `null` until one is provisioned. The\n * one audited reveal of an app secret — the password exists to be typed by a human (ADR-0656).\n */\nexport const AppAccessSchema = z.object({\n object: z.literal(\"app_access\"),\n url: z.string().nullable(),\n password: z.string().nullable(),\n});\nexport type AppAccess = z.infer<typeof AppAccessSchema>;\n\nexport const AppDomainStatusSchema = z.enum([\"pending\", \"connected\", \"failed\"]);\n\nexport const AppDomainSchema = z.object({\n object: z.literal(\"app_domain\"),\n app_id: idOf(\"app\"),\n domain_id: idOf(\"dom\"),\n domain: z.string(),\n status: AppDomainStatusSchema,\n created_at: Timestamp,\n});\nexport type AppDomain = z.infer<typeof AppDomainSchema>;\n\n/** `A-Z0-9_`, not starting with a digit — what every runtime accepts as an env name. */\nexport const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;\n\n/**\n * App names become provider project names and platform hostnames, so the grammar is the\n * DNS-label one: lowercase alphanumerics and hyphens, no edge hyphens, 63 max.\n */\nexport const APP_NAME = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/**\n * WHAT AN APP'S OWN KEY MAY HOLD (`§29.10`, ADR-1004, ADR-1009). An app asks, the owner approves\n * on a card, and the key carries exactly the approved subset. Reads are the default ask.\n * `files:read` is the whole company library, not the app's own files; the card says so.\n *\n * THE AGENT THAT WRITES THE APP CAN READ ITS KEY: it writes the server code that holds it. So no\n * scope here may reach past what that agent already has. `sessions:write` answers approval cards\n * (`POST /v1/sessions/{id}/tool_confirmations`) and `agents:write` rewrites any agent's tool\n * policy and every app's secrets and entry tickets: either one lets the agent approve itself. Only\n * `files:write` is left to ask for. Never `admin`, `billing:write`, `webhooks:*`, `audit:read`,\n * `computers:write` or `proxy:write` either: a key baked into an app must not mint keys, spend,\n * redirect traffic or run code.\n */\nexport const APP_READ_SCOPES = [\"agents:read\", \"sessions:read\", \"billing:read\", \"files:read\"] as const satisfies readonly Scope[];\nexport const APP_WRITE_SCOPES = [\"files:write\"] as const satisfies readonly Scope[];\nexport type AppScope = (typeof APP_READ_SCOPES)[number] | (typeof APP_WRITE_SCOPES)[number];\n\n/**\n * WHAT AN APP'S OWN KEY LETS IT DO (`§29.10`, ADR-1048): the union of the scopes of every live key\n * linked to the app (`api_key.app_id`), in every mode — never a key id, a prefix or a name. Empty\n * when no linked key is live. A key set by hand, or minted before keys named their app, is not here:\n * the Studio reads the app's `NAIVE_API_KEY` secret to say so rather than claim \"no access\".\n */\nexport const AppPermissionsSchema = z.object({\n object: z.literal(\"app_permissions\"),\n app_id: idOf(\"app\"),\n scopes: z.array(z.string()),\n});\nexport type AppPermissions = z.infer<typeof AppPermissionsSchema>;\n\n/**\n * THE APP ENGINEER'S MARKER (`§29.8`). The engineer is an ordinary agent that *points at* one app\n * through `metadata.role`/`metadata.app_id`; the dashboard hides it from every roster it draws, so\n * the marker is the only thing that can find it — and the only thing that can reap it when its app\n * goes. It lives here rather than in the studio because the delete route is the other reader.\n */\nexport const APP_ENGINEER_MARKER = \"app-engineer\" as const;\n\n/** Is this agent the engineer of that app? Metadata only: the marker is the whole relationship. */\nexport const isAppEngineerOf =\n (appId: string) =>\n (agent: { metadata: Record<string, unknown> }): boolean =>\n agent.metadata[\"role\"] === APP_ENGINEER_MARKER && agent.metadata[\"app_id\"] === appId;\n","/**\n * The blueprint install (`canonical-spec §29.6`) — one applied declaration per\n * (organization, project), and the drift a `revision_conflict` names.\n *\n * `naive up` needed no server-side state while the only writer was a person with a clone: its\n * working tree was the manifest. The studio applying the same declaration makes two writers on one\n * organization, and neither can see the other. This row is what they share.\n *\n * It is not a second source of truth for what is provisioned — apps, agents, skills, identities and\n * vaults stay keyed by name on their own routes. It records *that* an apply happened, with what, by\n * whom, and against which revision.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\n/** Which of the two writers applied a revision. */\nexport const BlueprintInstallSourceSchema = z.enum([\"studio\", \"cli\"]);\nexport type BlueprintInstallSource = z.infer<typeof BlueprintInstallSourceSchema>;\n\n/**\n * Whether one revision's reconcile is finished (§29.6). `report: null` alone cannot say: an apply\n * that only recorded and a hosted apply that has not run yet look the same without it. A hosted apply\n * a signed-in person makes answers `pending` and runs after the response; the row moves to `applied`\n * when the report is stamped, or to `failed` with `failure` set when the run threw.\n */\nexport const BlueprintInstallStatusSchema = z.enum([\"pending\", \"applied\", \"failed\"]);\nexport type BlueprintInstallStatus = z.infer<typeof BlueprintInstallStatusSchema>;\n\n/**\n * What one apply did to one resource. This is the vocabulary `naive up` has printed since it\n * existed; it is written HERE, and imported by `@usenaive-sdk/blueprints`, for the reason\n * `CLAUDE.md §2` gives: the hosted apply publishes the engine's report on the install (below), so\n * it is a wire shape, and a wire shape has exactly one definition. The engine re-exports these two\n * names unchanged, so nothing downstream of it learns a second word for the same thing.\n */\nexport const ResourceActionSchema = z.enum([\"created\", \"updated\", \"unchanged\", \"deleted\", \"refused\"]);\nexport type ResourceAction = z.infer<typeof ResourceActionSchema>;\n\n/** One line of an apply: what was named, what happened to it, and — for a refusal — why. */\nexport const ResourceReportSchema = z.object({\n name: z.string().min(1),\n action: ResourceActionSchema,\n /** The `agt_`/`app_`/`ses_`… the line resolved to. Absent on a refusal that never got an id. */\n id: z.string().optional(),\n /** An app's hostname once its build went live; `null` while it has none. Apps only. */\n url: z.string().nullable().optional(),\n /**\n * What a TASK is called and who owes it. `name` is the declaration key (`first-render`), which is\n * how a re-apply finds the same card and is not a sentence anybody wants read to them. The\n * dashboard's opening message lists the team's work, so it needs the title the board shows and the\n * seat that holds it. Tasks only.\n */\n title: z.string().optional(),\n assignee: z.string().optional(),\n /**\n * A SCHEDULE'S brief, in one short line — the opening sentence of its `input_template`. A\n * schedules line is named `<agent> @ <cron>`, which says when something runs and nothing at all\n * about what it does, so a roadmap built from these lines could only ever have been a timetable.\n * Written here rather than read back from the deployment so the receipt stays the one read the\n * welcome needs. Schedules only.\n */\n summary: z.string().optional(),\n reason: z.string().optional(),\n});\nexport type ResourceReportLine = z.infer<typeof ResourceReportSchema>;\n\n/**\n * What an apply DID — the engine's own `UpReport`, minus the two fields that are answers to a\n * question nobody asks a stored row (`dry_run`, and the pair naming the crew, which the install\n * already carries in `blueprint`/`template`).\n *\n * `intake` is its own list rather than a line under `agents` because an intake line's `id` is a\n * `ses_`: folding it in would put a session id in the field a reader uses to find an agent\n * (ADR-0410). `skipped` names live rows the engine could not parse and stepped over. `deselected`\n * names the agents and apps the operator's `selection` left out (§31.2) — a choice, kept apart from\n * `skipped` (a failure to read) and `refused` (a failure to do). Defaulted, because every report\n * stored before it was written without it and means \"nothing was left out\".\n */\nexport const BlueprintReportSchema = z.object({\n skills: z.array(ResourceReportSchema),\n identities: z.array(ResourceReportSchema),\n vaults: z.array(ResourceReportSchema),\n apps: z.array(ResourceReportSchema),\n agents: z.array(ResourceReportSchema),\n schedules: z.array(ResourceReportSchema),\n intake: z.array(ResourceReportSchema),\n /** One line per declared task (§31.11), `id` the card's `crd_`. Defaulted so older rows parse. */\n tasks: z.array(ResourceReportSchema).default([]),\n skipped: z.array(z.string()),\n deselected: z.array(z.string()).default([]),\n});\nexport type BlueprintReport = z.infer<typeof BlueprintReportSchema>;\n\n/**\n * Which of the declared crew an apply takes (§31.2), by declared name. Omitting it from the apply\n * body means everything; a selection missing a `required` agent or app is `validation_failed`.\n */\nexport const BlueprintSelectionSchema = z.object({\n agents: z.array(z.string().min(1)),\n apps: z.array(z.string().min(1)),\n});\nexport type BlueprintSelection = z.infer<typeof BlueprintSelectionSchema>;\n\nexport const BlueprintInstallSchema = z.object({\n id: idOf(\"bpi\"),\n object: z.literal(\"blueprint_install\"),\n /** The customer's own `defineProject({ name })` — the same word `app.project` stamps (§29.2). */\n project: z.string().min(1),\n /** The pair the declaration resolved to; `null` for a declaration that names no blueprint. */\n blueprint: z.string().nullable(),\n template: z.string().nullable(),\n /**\n * Applies, not versions of anything: 1 on the first apply, +1 on each one after, whichever writer\n * made it. It is not an agent version and it never rolls back.\n */\n revision: z.number().int().positive(),\n /**\n * The blueprint artifact version this came from, or `null` when it was applied from a working\n * tree — an operator editing a clone has no version to name.\n */\n artifact_version: z.string().nullable(),\n /**\n * The setup answers this project was configured with (§7.1 fields, keyed by their `key`), so a\n * re-apply does not re-ask and both writers configure from the same answers. Configuration only:\n * a secret is a vault credential (§23) or an app secret (§29.2), and neither is ever an answer.\n */\n answers: z.record(z.string(), z.unknown()),\n /**\n * NO `declaration` ON THE WIRE, and that is the reconciliation of §29.6 with §31.1.\n *\n * The applied bytes are stored — a `revision_conflict` names the paths two writers disagree at,\n * and it can only do that by holding what was applied. They are not published. An apply that\n * names a published `blueprint` and `template` sends no declaration: the server reads the\n * catalog's, which §31.1 says never leaves it. Echoing it back on the 201 (and again on every\n * later list) would hand any organization that can sign up the whole private config of a\n * blueprint it has installed nothing of — every agent's system prompt, its `mcp_servers`, its\n * vault credential declarations and its app `env` keys. A caller that sent a declaration already\n * has it, so nothing is lost by not saying it twice.\n */\n source: BlueprintInstallSourceSchema,\n /**\n * WHAT THE APPLY DID, or `null` when it did nothing but record.\n *\n * An apply that sends its own `declaration` has already reconciled it — that is what `naive up`\n * is — so the row it writes is a record and this is `null`. An apply that names a **published**\n * pair has reconciled nothing: it was never given the bytes (§31.1), so the server reads them\n * from the catalog and runs the same engine over them, and this is what that run reported.\n *\n * It is stored rather than only returned because a refusal inside a successful apply — an app\n * whose `env` reads a variable no hosted run has, a session refused for credit — is the one fact\n * a person needs after the screen that showed it is gone.\n */\n report: BlueprintReportSchema.nullable(),\n status: BlueprintInstallStatusSchema,\n /**\n * Why a `failed` run threw, in one sentence — or, on an `applied` row, which `required` agent or\n * app the apply refused and why (§29.6). `null` otherwise. Never a stack or a key.\n */\n failure: z.string().nullable(),\n /**\n * The `selection` the apply carried, or `null` — every row written before §31.2 and every apply\n * that omitted it, both meaning \"everything\". Defaulted so those rows parse unchanged.\n */\n selection: BlueprintSelectionSchema.nullable().default(null),\n /** When the answers were last edited through `PATCH …/installs/{id}` (§31.8); `null` if never. */\n context_updated_at: Timestamp.nullable().default(null),\n /**\n * What this install's agent, app, identity and vault names start with (§29.6, ADR-1104): `\"\"`\n * when its template's names were free in the organization, `\"<project>-\"` when any was already\n * another project's. Decided once, by the apply that created the row, and never again. `null` is\n * an install from before that rule, or one a working tree recorded: its names are the template's.\n * Optional only so a Worker from before the field still parses; this API always sends it.\n */\n name_prefix: z.string().nullable().optional(),\n applied_at: Timestamp,\n created_at: Timestamp,\n});\nexport type BlueprintInstall = z.infer<typeof BlueprintInstallSchema>;\n\n/** One answered setup question, as the crew reads it: the question's `label`, not just its `key`. */\nexport const ProjectContextAnswerSchema = z.object({\n key: z.string().min(1),\n label: z.string(),\n value: z.union([z.string(), z.array(z.string())]),\n});\nexport type ProjectContextAnswer = z.infer<typeof ProjectContextAnswerSchema>;\n\n/**\n * What a template's crew knows about the business it runs (§31.8): the install row's answers joined\n * to the artifact's questions, the report's apps with their URLs, and the crew with its roles.\n * Derived from the latest `applied` install and its report — only an edit to `answers` is stored.\n * `GET /v1/blueprints/installs/{id}/context`, the built-in `project_context` tool, and the\n * orchestrator's `vetta.blueprints_get_context` all return this one object.\n */\nexport const ProjectContextSchema = z.object({\n object: z.literal(\"project_context\"),\n project: z.string().min(1),\n blueprint: z.string().nullable(),\n template: z.string().nullable(),\n artifact_version: z.string().nullable(),\n answers: z.array(ProjectContextAnswerSchema),\n apps: z.array(z.object({ name: z.string().min(1), url: z.string().nullable() })),\n agents: z.array(z.object({ name: z.string().min(1), role: z.string().nullable() })),\n /** `context_updated_at` once the answers have been edited, `applied_at` until then. */\n updated_at: Timestamp,\n});\nexport type ProjectContext = z.infer<typeof ProjectContextSchema>;\n\n/**\n * How many drifted paths a `revision_conflict` message names before it says \"and N more\". A\n * declaration can disagree in hundreds of places and an unbounded refusal is unreadable; a bounded\n * one plus a count still tells the operator whether the other writer touched anything they own.\n */\nexport const DRIFT_PATHS_IN_MESSAGE = 20;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction walk(stored: unknown, incoming: unknown, at: string, into: string[]): void {\n if (isRecord(stored) && isRecord(incoming)) {\n for (const key of new Set([...Object.keys(stored), ...Object.keys(incoming)])) {\n walk(stored[key], incoming[key], at === \"\" ? key : `${at}.${key}`, into);\n }\n return;\n }\n if (Array.isArray(stored) && Array.isArray(incoming)) {\n for (let i = 0; i < Math.max(stored.length, incoming.length); i++) {\n walk(stored[i], incoming[i], `${at}.${i}`, into);\n }\n return;\n }\n if (JSON.stringify(stored ?? null) !== JSON.stringify(incoming ?? null)) into.push(at || \"(root)\");\n}\n\n/**\n * The paths at which a stored declaration and the one being applied disagree — `agents.2.model`,\n * `apps.0.mcp` — sorted, so two runs of the same conflict read the same.\n *\n * This is the canonical, key-sorted comparison `packages/blueprints/src/report.ts` already uses,\n * obtained structurally: the walk visits the union of an object's keys, so key ORDER is never a\n * change, while array order is meaning and is compared position by position. A key present on one\n * side and absent on the other is drift at that path — unlike `report.ts`'s `changed`, which is\n * asked about one declared field at a time and treats absence as \"not declared\". Here both sides\n * are whole declarations, so an added or dropped resource is exactly what an operator needs named.\n *\n * Computable server-side only because the declaration is stored, which is why storing it is not\n * redundancy (§29.6).\n */\nexport function driftedPaths(stored: unknown, incoming: unknown): string[] {\n const found: string[] = [];\n walk(stored, incoming, \"\", found);\n return found.sort();\n}\n","/**\n * The blueprint catalog (`canonical-spec §31`) — the built output of one blueprint × template ×\n * released version, published once and shared by every organization.\n *\n * A hosted run does not fork a blueprint into per-customer storage: the repository is\n * byte-identical for every operator, the template choice is one line out of a closed set, and the\n * answers, posts and accounts are runtime rows. So the build runs once per pair per release and\n * this is the row it produces.\n *\n * Nothing tenant-shaped appears here, and that is not an omission — the row has no `org_id` at all\n * (§31.1). Two of the things behind it never reach the wire either: each tree's `files_ref` is the\n * object-store key of that app's built bytes (the `provider_ref` posture, §29.1) and `declaration`\n * is the config only the reconciler reads. `questions`, `schedules`, `agents`, `apps` and\n * `identities` are the halves lifted out of it that a client genuinely needs — the crew because the\n * screen that asks a person to run a company has to show them the company first (§31.5), the\n * personas because it asks for their accounts before the crew exists (§31.10).\n */\n\nimport { z } from \"zod\";\nimport { SkillRefSchema } from \"./agent\";\nimport { AppTypeSchema } from \"./app\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { QuestionFieldSchema } from \"./session\";\nimport { SocialPlatformSchema } from \"./social\";\n\n/**\n * One timer this template's crew runs, flattened out of the declaration's `agents[].schedules[]`\n * so the landing page can print what a crew does before anyone has signed up (§31.3).\n *\n * `agent` is the declared agent's **name**, not an `agt_` id: at the moment this is printed no\n * agent exists to have one.\n */\nexport const BlueprintScheduleSchema = z.object({\n agent: z.string().min(1),\n cron: z.string().min(1),\n timezone: z.string().nullable(),\n /** The message each fire opens its session with — the sentence worth printing. */\n input: z.string().min(1),\n budget_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type BlueprintSchedule = z.infer<typeof BlueprintScheduleSchema>;\n\n/**\n * One timer's cap as the operator set it on the apply (§29.6 `budgets`), naming the timer by the\n * same `(agent, cron)` the published `schedules` row carries — the only key a schedule has before it\n * is a deployment. The published `budget_micro_usd` is the recommendation this replaces.\n */\nexport const BlueprintBudgetSchema = BlueprintScheduleSchema.pick({ agent: true, cron: true, budget_micro_usd: true });\nexport type BlueprintBudget = z.infer<typeof BlueprintBudgetSchema>;\n\n/**\n * One agent this template provisions, flattened out of the declaration's `agents[]` (§31.5).\n *\n * A third half lifted out of `declaration` for the same reason the first two were: somebody outside\n * the reconciler needs it. Nobody should be asked to provision a company without being shown who is\n * in it, and the crew cannot be read off `schedules` — an agent with no timer would simply not\n * appear, which is exactly the coordinator a template is usually built around.\n *\n * `name` is the declared name, not an `agt_` id, for the reason it is on a schedule: at the moment\n * this is printed no agent exists to have one. `briefed` is whether the declaration gives this\n * agent an `intake` (§31.4) — the difference between a crew that is provisioned and a crew that has\n * started working, and the sentence a person is entitled to read before they pay for it. `intake`\n * is that first message's text, null when the declaration briefs nobody — and ABSENT on a row\n * published before this release, which is why it is optional (see `BlueprintAppSchema` below).\n *\n * `role` (two or three words beside the name), `skills` (§13 refs, verbatim), `tools` (the built-in\n * and `<app>.<tool>` names the declaration allows this agent, sorted) and `required` (whether an\n * install may leave it out, §31.2) are the WS12 v2 half of the same reading, optional for the same\n * reason: rows published before them lack them.\n */\nexport const BlueprintCrewSchema = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n model: z.string().min(1),\n briefed: z.boolean(),\n intake: z.string().nullable().optional(),\n /** What the first session may spend: the intake's own cap, else the agent's (§31.4). Set iff `briefed`. */\n intake_micro_usd: MicroUsdField.nonnegative().optional(),\n role: z.string().min(1).optional(),\n skills: z.array(SkillRefSchema).optional(),\n tools: z.array(z.string().min(1)).optional(),\n required: z.boolean().optional(),\n});\nexport type BlueprintCrew = z.infer<typeof BlueprintCrewSchema>;\n\n/**\n * One app this template deploys, flattened out of the declaration's `apps[]` (§31.5). `mcp` is the\n * path it serves MCP on (§29.5) or null; `tools` is the tool names (no `<app>.` prefix) any agent's\n * `tools.configs` names under it, sorted.\n *\n * *** THESE TWO AND `BlueprintCrewSchema.intake` ARE OPTIONAL, AND THAT IS THE ROLLOUT. ***\n *\n * A deploy does not rebuild the catalog: every published row was written by whichever release was\n * current when its blueprint released, and not one row live today carries any of the three. Making\n * them required makes the artifact a client cannot read the artifact the platform is serving —\n * and `apps/naive-lp-v2` parses that live catalog at build time and fails the build by design on a\n * row it cannot read, so every landing-page build between this deploy and the republish of every\n * artifact would hard-fail. Absent means \"the release that published this row did not carry it\";\n * every screen that reads them already draws that as an app with no MCP path and no tools.\n */\nexport const BlueprintAppSchema = z.object({\n name: z.string().min(1),\n type: AppTypeSchema,\n description: z.string().nullable(),\n mcp: z.string().nullable().optional(),\n tools: z.array(z.string().min(1)).optional(),\n /** Whether an install may deselect it (§31.2). Optional: the rollout argument above. */\n required: z.boolean().optional(),\n});\nexport type BlueprintApp = z.infer<typeof BlueprintAppSchema>;\n\n/**\n * One persona this template's crew acts as, flattened out of the declaration's `identities[]`\n * (§31.10). `name` is the declared name — the same name the apply's `upsertIdentity` finds it by.\n * Its accounts are connected after the apply, and they are where the crew posts (ADR-0922).\n */\nexport const BlueprintIdentitySchema = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n});\nexport type BlueprintIdentity = z.infer<typeof BlueprintIdentitySchema>;\n\n/**\n * Lowercase sha-256 hex — exactly what `contentHash()` in `@usenaive-sdk/blueprints`\n * (`src/files.ts`) returns over a deployment's file map.\n *\n * §29.2's `content_hash` is a free string the server stores and never checks, because a *customer*\n * supplies it. This one is ours: an install skips the upload when it equals the newest deployment's\n * hash, so the two must be the same digest of the same bytes. Pinning the shape here is what turns\n * a drift into a failing parse instead of a silent re-upload on every install.\n */\nexport const ContentHashSchema = z.string().regex(/^[0-9a-f]{64}$/, \"a lowercase sha-256 hex digest\");\n\n/**\n * One app's built tree (§31.1). A blueprint ships as many as it declares with a `deploy_dir` —\n * `media` one, `agency` two (`dashboard` and `site`) — so the artifact addresses a tree PER APP,\n * keyed by the name the declaration gives it.\n *\n * The digest is per app because the skip is per app: §29.2 compares against a *deployment*, and a\n * deployment belongs to one app, so one hash over every tree would move whenever any single app\n * changed and send every other app's unchanged bytes up again on every install.\n *\n * The row's own entry also carries `files_ref`, the object-store key of these bytes. It is a\n * provider handle and stays server-side (§29.1) — and it stays there BY THIS SCHEMA: the store\n * parses stored trees through it on the way out, and zod's default strip is what removes the key.\n * A field added here reaches the wire; that is the thing to know before adding one.\n */\nexport const BlueprintTreeSchema = z.object({\n /** `apps[].name` in the declaration — the same name §31.5 prints and the install ensures by. */\n app: z.string().min(1),\n content_hash: ContentHashSchema,\n});\nexport type BlueprintTree = z.infer<typeof BlueprintTreeSchema>;\n\nexport const BlueprintArtifactSchema = z.object({\n id: idOf(\"bpa\"),\n object: z.literal(\"blueprint_artifact\"),\n /** The machine — its repository, screens and `/api/*`. */\n blueprint: z.string().min(1),\n /** Which of that blueprint's templates provides the crew. */\n template: z.string().min(1),\n /** The blueprint repository's own released version. Stored, never parsed (ADR-0401). */\n version: z.string().min(1),\n /**\n * What a person calls the template, one line on what its crew does, and the networks it publishes\n * to — printed, never provisioned (§31.5, ADR-0921). `platforms` is decoration: where the crew\n * posts is the accounts connected to its persona. Optional for the §31.5 rollout reason.\n */\n title: z.string().min(1).optional(),\n description: z.string().min(1).optional(),\n platforms: z.array(SocialPlatformSchema).optional(),\n /**\n * The built trees, one per deployable app, ordered as the declaration orders its apps. Empty for\n * a data-only blueprint: it declares no app, builds nothing, and still ships a crew (ADR-0900).\n */\n trees: z.array(BlueprintTreeSchema),\n /**\n * The setup questions, asked by the studio **before** provisioning. `QuestionField` (§7.1) is\n * reused rather than restated: a setup question and a question a parked agent asks are the same\n * object at different times, so one component renders both.\n */\n questions: z.array(QuestionFieldSchema),\n schedules: z.array(BlueprintScheduleSchema),\n /** Who the crew is, and what it deploys — §31.5. Derived from `declaration`, never stored twice. */\n agents: z.array(BlueprintCrewSchema),\n apps: z.array(BlueprintAppSchema),\n /**\n * The agents a template creates per client the operator signs — printed, never provisioned by an\n * apply (§31.1). Absent on rows published before WS12 v2, hence optional.\n */\n crew_per_client: z.array(BlueprintCrewSchema).optional(),\n /**\n * The personas the crew posts from, and which accounts to connect to each before the crew\n * exists (§31.10). Derived from `declaration` like `agents`; optional for the §31.5 rollout reason.\n */\n identities: z.array(BlueprintIdentitySchema).optional(),\n /**\n * The creator template a row was published from (§42.8), `null` on every first-party row.\n * `creator_name` is the public display name the landing page credits. The API sends all three\n * on every row; they are optional here only so an artifact typed before §42 still reads.\n */\n creator_template_id: idOf(\"ctp\").nullish(),\n creator_template_version: z.number().int().positive().nullish(),\n creator_name: z.string().min(1).nullish(),\n published_at: Timestamp,\n});\nexport type BlueprintArtifact = z.infer<typeof BlueprintArtifactSchema>;\n","/**\n * The credential vault (`canonical-spec.md §23`, `docs/identity/vault.mdx`, `docs/api/vaults.mdx`).\n *\n * One property defines this object and every field below serves it: **the value is write-only.**\n * It is accepted on create, sealed, and never returned by any endpoint — there is no reveal route,\n * no `value` on any read schema, and no update route (rotation is create-new + delete-old, so\n * `last_injected_at` stays attributable to exactly one secret).\n *\n * Note what is *absent* on purpose: `VaultCredentialSchema` has no `value`, so a handler that\n * parsed a row through it could not emit one even by accident. That is the guarantee expressed as\n * a type rather than as a convention.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\n/**\n * The three kinds `docs/identity/vault.mdx` publishes.\n *\n * · `static_bearer` / `mcp_oauth` are injected **server-side, in our own isolate**, when the MCP\n * client connects to `mcp_server_url`. The token never enters the sandbox, so the guarantee holds\n * with no vendor capability we do not have.\n * · `env_var` promises substitution at an egress proxy on the sandbox's network path. No such\n * boundary exists (`memory/vendor-tenki.md §5`: no egress allowlist, no per-domain policy, no\n * proxy hook), so the route refuses it with `feature_not_configured` rather than storing a secret\n * whose central safety property we cannot deliver (ADR-0117).\n */\nexport const VaultCredentialKindSchema = z.enum([\"env_var\", \"static_bearer\", \"mcp_oauth\"]);\nexport type VaultCredentialKind = z.infer<typeof VaultCredentialKindSchema>;\n\n/** A vault belongs to exactly one identity; `null` until the identity stream lands the object. */\nexport const VaultSchema = z.object({\n id: idOf(\"vlt\"),\n object: z.literal(\"vault\"),\n identity_id: idOf(\"idn\").nullable(),\n display_name: z.string().min(1).max(128),\n credential_count: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\nexport type Vault = z.infer<typeof VaultSchema>;\n\n/**\n * Credential **metadata**. Every read surface returns this and only this.\n *\n * `placeholder_ref` is not a secret and is returned deliberately: a caller needs it to write the\n * reference into a script. It names a credential; it authenticates nothing.\n */\nexport const VaultCredentialSchema = z.object({\n id: idOf(\"vcr\"),\n object: z.literal(\"vault_credential\"),\n vault_id: idOf(\"vlt\"),\n kind: VaultCredentialKindSchema,\n /** For `env_var`, the environment variable name. For the MCP kinds, a display label. */\n key: z.string().min(1).max(128),\n /** The exact destination host an `env_var` credential is bound to. Never a wildcard. */\n host: z.string().nullable(),\n /** The exact MCP server URL an `mcp_*` token is matched to. */\n mcp_server_url: z.url().nullable(),\n /**\n * The one agent this credential may be injected into (ADR-1097). `null` is any agent that\n * declares `mcp_server_url` — except the platform's own `/v1/mcp`, whose key is never injected\n * unbound. Set at create, by `admin`, and immutable like the rest. Defaults to `null` so a\n * client reading a control plane older than the field still parses the row.\n */\n agent_id: idOf(\"agt\").nullable().default(null),\n placeholder_ref: z.string(),\n expires_at: Timestamp.nullable(),\n last_injected_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type VaultCredential = z.infer<typeof VaultCredentialSchema>;\n","/**\n * Handoffs — `send_to_agent` with `wait: false` (canonical-spec §28.12, §28.15): an agent starts a\n * top-level session on another agent of its organization and carries on. Who it may reach is the\n * agent's `handoffs` field (`schema/agent.ts`), the same field that governs a `wait: true` thread.\n *\n * The body the door takes, the answer it returns and the mark the receiver's row carries are one\n * shape each, here, so the runtime, the API and a blueprint cannot drift apart on any of them.\n */\n\nimport { z } from \"zod\";\nimport { isId } from \"../id\";\nimport { idOf, type Metadata } from \"./common\";\n\n/** The most targets one human send may fan out to (§28.16): a room seats a coordinator and up to six. */\nexport const MAX_HANDOFF_TARGETS = 6;\n\n/** A sender at this depth is refused: a chain — or a cycle — ends in five sessions at most (§28.15). */\nexport const MAX_HANDOFF_DEPTH = 4;\nexport const MAX_HANDOFFS_PER_SESSION = 8;\n\nexport const HandoffRequestSchema = z.object({\n agent: z.string().min(1),\n message: z.string().min(1),\n handoff_key: z.string().min(1).max(128).optional(),\n budget_micro_usd: z.number().int().positive().optional(),\n});\nexport type HandoffRequest = z.infer<typeof HandoffRequestSchema>;\n\nexport const HandoffSchema = z.object({\n object: z.literal(\"handoff\"),\n session_id: idOf(\"ses\"),\n status: z.enum([\"queued\", \"already_running\"]),\n handoff_key: z.string().nullable(),\n});\nexport type Handoff = z.infer<typeof HandoffSchema>;\n\n/**\n * `POST /v1/sessions/{id}/handoffs` (§28.16): a person hands `{id}`'s work to several agents in one\n * call. Each target is an `agt_` id or a name; the sender is the session in the path.\n */\nexport const SessionHandoffRequestSchema = z.object({\n agents: z.array(z.string().min(1)).min(1).max(MAX_HANDOFF_TARGETS),\n message: z.string().min(1),\n handoff_key: z.string().min(1).max(128).optional(),\n budget_micro_usd: z.number().int().positive().optional(),\n});\nexport type SessionHandoffRequest = z.infer<typeof SessionHandoffRequestSchema>;\n\n/** One target the door would not start: a row of the batch, never the whole answer (§28.16). */\nexport const HandoffRefusalSchema = z.object({\n object: z.literal(\"handoff_refusal\"),\n agent: z.string(),\n code: z.string(),\n message: z.string(),\n});\nexport type HandoffRefusal = z.infer<typeof HandoffRefusalSchema>;\n\n/** The human door's answer: §28.15's `Handoff` per admitted target, plus the seat it landed on. */\nexport const HandoffBatchSchema = z.object({\n object: z.literal(\"handoff_batch\"),\n handoffs: z.array(HandoffSchema.extend({ agent_id: idOf(\"agt\") })),\n refusals: z.array(HandoffRefusalSchema),\n});\nexport type HandoffBatch = z.infer<typeof HandoffBatchSchema>;\n\n/** `metadata.handoff` on the receiver's session row (§28.15). */\nexport const SessionHandoffSchema = z.object({\n from_session: idOf(\"ses\"),\n from_agent: idOf(\"agt\"),\n key: z.string().nullable(),\n depth: z.number().int().positive(),\n});\nexport type SessionHandoff = z.infer<typeof SessionHandoffSchema>;\n\n/** The mark a row carries, or `null` for a session nobody handed off. Lenient: metadata is the customer's. */\nexport function handoffOf(metadata: z.infer<typeof Metadata>): SessionHandoff | null {\n const parsed = SessionHandoffSchema.safeParse(metadata[\"handoff\"]);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * `metadata.role` of the one standing agent the dashboard calls the CEO. It is also the mark the\n * **company board** is found by (§28.18): the CEO owns that board and every live agent sits on it,\n * which is a fact the database reads (`@vetta/db` `seatFor`) and the runtime reads, so the string\n * lives here rather than once per reader.\n */\nexport const ORCHESTRATOR_ROLE = \"orchestrator\" as const;\n\n/** A room (§28.16) is a coordinator whose `metadata.role` is `\"group\"` or `\"orchestrator\"`; read off a pinned version. */\nexport const isRoom = (version: { metadata: z.infer<typeof Metadata> }): boolean =>\n version.metadata[\"role\"] === \"group\" || version.metadata[\"role\"] === ORCHESTRATOR_ROLE;\n\n/**\n * WHEN THE CHANNEL MARK BEGAN — the boundary one-time adoption may reach back over, and no further.\n *\n * From this instant a channel's session is MARKED at creation (`metadata.room`), so nothing created\n * from here on ever needs adopting. Adoption exists only for the channels that predate the mark, and\n * bounding it here is what keeps it from being a live rule: without the bound it considers every\n * unmarked top-level session of the coordinator forever, which includes the private 1:1 chat a\n * person starts from the agent page tomorrow — one dashboard read and the channel owns that chat's\n * transcript, permanently, with nothing in the product to undo it.\n *\n * It is NOT the cutoff that was tried and rejected on this branch. That one adopted only sessions\n * created AFTER a date, which strands exactly the legacy channels adoption is for. This is the\n * opposite bound: legacy sessions are eligible, new ones never are. It needs no migration and no\n * backfill, and it stops mattering once every channel that predates it has been read once.\n */\nexport const ROOM_ADOPTION_BEFORE = \"2026-09-19T00:00:00.000Z\";\n\n/** A room's `handoff_key` (§28.16), minted from the root session it names; `roomOfKey` reads it back. */\nexport const roomKey = (rootId: string): string => `room:${rootId}`;\n\n/** A room's `handoff_key` is `room:<root session id>` (§28.16); this reads the root off one, or `null` for any other key. */\nexport function roomOfKey(key: string | null | undefined): string | null {\n const root = key?.startsWith(\"room:\") ? key.slice(\"room:\".length) : \"\";\n return isId(\"ses\", root) ? root : null;\n}\n\n/**\n * A SEAT is a member's session in a room (§28.16): top-level and handed off under `room:<root>`.\n * It answers into the room, so it is the room's plumbing, never one of its agent's own chats; a\n * person reads it from the room and does not type into it. This reads the root it sits in, or `null`.\n */\nexport const seatOf = (session: { parent_session_id: string | null; metadata: z.infer<typeof Metadata> }): string | null =>\n session.parent_session_id === null ? roomOfKey(handoffOf(session.metadata)?.key) : null;\n\n/**\n * What a receiver handed off under a room's key is told about the room (§28.15 `channel`): the\n * root it may post into, the room agent's name, and the roster less itself. `null` outside a room.\n */\nexport const ChannelBriefSchema = z.object({\n root_session_id: idOf(\"ses\"),\n name: z.string().min(1),\n members: z.array(z.string().min(1)),\n /**\n * The receiver's own name, so it can tell the part of a post addressed to it from a teammate's\n * (ADR-1099). Optional: a brief pinned before it existed still parses.\n */\n you: z.string().min(1).optional(),\n});\nexport type ChannelBrief = z.infer<typeof ChannelBriefSchema>;\n\n/** `POST /v1/sandbox/channel/messages` (§28.16): a member's words for its room, and the door's answer. */\nexport const ChannelPostRequestSchema = z.object({\n message: z.string().min(1).max(20_000),\n});\nexport type ChannelPostRequest = z.infer<typeof ChannelPostRequestSchema>;\n\nexport const ChannelPostSchema = z.object({\n object: z.literal(\"channel_post\"),\n root_session_id: idOf(\"ses\"),\n queued: z.boolean(),\n});\nexport type ChannelPost = z.infer<typeof ChannelPostSchema>;\n","/**\n * `show` — a view of the company the chat draws (canonical-spec §48). The model names a source;\n * code reads the data and writes the view, title included, so no number on the figure was typed\n * by the model. The same schema is the tool's argument parser, its result, and the web's reader.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { BoardStatusSchema } from \"./board\";\n\nexport const SHOW_SOURCES = [\"spend_by_day\", \"post_views\", \"roadmap\", \"schedule\"] as const;\nexport const ShowSourceSchema = z.enum(SHOW_SOURCES);\n\n/**\n * FLAT, ON PURPOSE. A discriminated union of per-source arguments becomes a root `oneOf`, which\n * providers refuse and which `defineTool`'s key repair cannot read (it only knows an object's\n * keys). `days` is read by `spend_by_day` alone.\n */\nexport const ShowArgsSchema = z.object({\n source: ShowSourceSchema.describe(\n \"What to show: spend_by_day (company spend per day, a line), post_views (views per recent post, bars), \" +\n \"roadmap (the board's work by status), schedule (routines and scheduled posts over the next 7 days).\",\n ),\n days: z.number().int().min(2).max(30).optional().describe(\"spend_by_day only: days back, today included. Default 14.\"),\n});\nexport type ShowArgs = z.infer<typeof ShowArgsSchema>;\n\n/** A calendar day on the company's clock (§20.6). */\nconst Day = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\nconst Count = z.number().int().nonnegative();\n\n/** What every view carries: its title (written by code), when it was read, and the company's clock. */\nconst head = { title: z.string().min(1), as_of: Timestamp, timezone: z.string().min(1) };\n\nexport const SpendByDayViewSchema = z.object({\n source: z.literal(\"spend_by_day\"),\n ...head,\n days: z.array(z.object({ day: Day, micro_usd: Count })).min(2).max(30),\n});\n\nexport const PostViewsViewSchema = z.object({\n source: z.literal(\"post_views\"),\n ...head,\n posts: z\n .array(z.object({ post_id: z.string().min(1), label: z.string(), networks: z.array(z.string()), posted_at: Timestamp, views: Count }))\n .max(12),\n});\n\nexport const RoadmapViewSchema = z.object({\n source: z.literal(\"roadmap\"),\n ...head,\n groups: z.array(\n z.object({\n status: BoardStatusSchema,\n count: Count,\n cards: z.array(z.object({ title: z.string(), assignee: z.string().nullable(), waits_on: z.array(z.string()) })).max(5),\n }),\n ),\n});\n\nexport const ScheduleViewSchema = z.object({\n source: z.literal(\"schedule\"),\n ...head,\n days: z\n .array(\n z.object({\n day: Day,\n count: Count,\n items: z\n .array(\n z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"routine\"), at: Timestamp, agent: z.string(), text: z.string(), runs: z.number().int().min(1).max(100) }),\n z.object({ kind: z.literal(\"post\"), at: Timestamp, networks: z.array(z.string()), text: z.string() }),\n ]),\n )\n .max(8),\n }),\n )\n .max(7),\n});\n\nexport const ShowViewSchema = z.discriminatedUnion(\"source\", [\n SpendByDayViewSchema,\n PostViewsViewSchema,\n RoadmapViewSchema,\n ScheduleViewSchema,\n]);\nexport type ShowView = z.infer<typeof ShowViewSchema>;\nexport type ScheduleItem = z.infer<typeof ScheduleViewSchema>[\"days\"][number][\"items\"][number];\n","/**\n * `compose` — a card the model lays out and code fills (canonical-spec §49, ADR-0955–0957). The\n * model writes a json-render spec: a flat map of elements under one `root`. It chooses the\n * components, their order and their words. It never writes a number: every value, series or\n * percentage on the card is a BINDING, `{ \"$source\": \"views_total\", \"days\": 7 }`, that code resolves\n * from Postgres when the tool runs. The tool's result is the same spec with each binding filled in.\n *\n * One catalog, written once (`catalog`), is built twice: with bindings for the model's argument\n * (`ComposeSpecSchema`), and with resolved values for the frozen result the chat draws\n * (`ComposedSpecSchema`). The two cannot drift apart, because they are the same components.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { Bound, catalog, Resolved, spec, unknownComponent } from \"./catalog\";\n\nexport const COMPOSE_COMPONENTS = [\"Card\", \"Stack\", \"Grid\", \"Metric\", \"LineChart\", \"BarList\", \"Progress\", \"Roadmap\", \"Schedule\", \"Media\", \"Text\"] as const;\nexport const MAX_COMPOSE_ELEMENTS = 24;\n\n/** The model's spec: bindings where the numbers go. */\nconst BoundComponents = catalog(Bound);\n/*\n * The union is spelled out for each side. A helper generic over the catalog loses every slot's type\n * to `unknown`, as `catalog`'s own parameters did before they were split.\n */\nexport const ComposeSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [\n BoundComponents.Card, BoundComponents.Stack, BoundComponents.Grid, BoundComponents.Metric, BoundComponents.LineChart, BoundComponents.BarList,\n BoundComponents.Progress, BoundComponents.Roadmap, BoundComponents.Schedule, BoundComponents.Media, BoundComponents.Text,\n ],\n unknownComponent(COMPOSE_COMPONENTS),\n ),\n \"Card\",\n MAX_COMPOSE_ELEMENTS,\n);\nexport type ComposeSpec = z.infer<typeof ComposeSpecSchema>;\nexport type ComposeElement = ComposeSpec[\"elements\"][string];\n\n/** FLAT, like `show`'s (ADR-0945): the spec sits inside one property of a plain object. */\nexport const ComposeArgsSchema = z.object({\n spec: ComposeSpecSchema.describe(\n 'A json-render spec: { \"root\": key, \"elements\": { key: { \"type\", \"props\", \"children\"? } } }. The root is one Card.',\n ),\n});\n\n/** Each component with its values resolved: the props the chat's renderer is typed by. */\nexport const ComposedComponents = catalog(Resolved);\n\n/** The frozen result: the spec with every binding resolved, as read at `as_of` on the company's clock. */\nexport const ComposedSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [\n ComposedComponents.Card, ComposedComponents.Stack, ComposedComponents.Grid, ComposedComponents.Metric, ComposedComponents.LineChart,\n ComposedComponents.BarList, ComposedComponents.Progress, ComposedComponents.Roadmap, ComposedComponents.Schedule, ComposedComponents.Media,\n ComposedComponents.Text,\n ],\n unknownComponent(COMPOSE_COMPONENTS),\n ),\n \"Card\",\n MAX_COMPOSE_ELEMENTS,\n);\nexport const ComposedSchema = z.object({ as_of: Timestamp, timezone: z.string().min(1), spec: ComposedSpecSchema });\nexport type Composed = z.infer<typeof ComposedSchema>;\nexport type ComposedElement = Composed[\"spec\"][\"elements\"][string];\n/** One component's resolved props: what a block in the studio is typed by. */\nexport type ComposedProps<T extends ComposedElement[\"type\"]> = Extract<ComposedElement, { type: T }>[\"props\"];\n","/**\n * The block catalog shared by `compose` (§49) and mini apps (§50): the components, the rule that a\n * number is a binding code resolves, and the tree check. One catalog, built with different slots:\n * with bindings for what an author writes, with resolved values for what a renderer draws.\n * Internal to `schema/`: `compose.ts` and `mini-app.ts` export what the wire needs.\n */\n\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\nimport { PostViewsViewSchema, RoadmapViewSchema, ScheduleViewSchema } from \"./show\";\n\nexport const Key = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,39}$/, \"an element key is a short name: a letter, then letters, digits, - or _\");\nexport const Count = z.number().int().nonnegative();\n\n/**\n * WORDS ARE THE MODEL'S; DIGITS ARE NOT. A title or a note that says \"up 18%\" would put a number on\n * the card that no code read. The window a value covers is written by the chat from its binding\n * (\"Last 7 days\"), so the model never needs a digit. The ASCII regex is what the JSON Schema the\n * model is shown carries (a `\\p{…}` pattern is one some providers' validators cannot compile); the\n * refine closes every other script's digits, fractions and numeral signs (`١٢`, `18`, `½`, `Ⅻ`).\n * Number WORDS (\"twelve thousand\") no pattern can close: that is the model's words, unchecked for\n * meaning like any label (ADR-0955).\n */\nconst DIGIT = \"words only: a digit is refused, because every number on the card is read by code from a $source binding\";\nexport const words = (max: number) =>\n z\n .string()\n .trim()\n .min(1)\n .max(max)\n .regex(/^[^0-9]*$/, DIGIT)\n .refine((text) => !/\\p{N}/u.test(text), DIGIT);\n\nexport const Days = z.number().int().min(1).max(30).default(7).describe(\"The window: today and the days before it, on the company's clock. Default 7.\");\n\n/** A binding to one of `sources`. A literal where one belongs is refused with the fix. */\nexport function bound<const S extends readonly [string, ...string[]], T extends z.ZodRawShape>(sources: S, shape: T) {\n const example = JSON.stringify({ $source: sources[0] });\n return z.strictObject(\n { $source: z.enum(sources), ...shape },\n { error: (issue) => (issue.code === \"invalid_type\" ? `must be a binding such as ${example}: a literal value is refused, code reads every number` : undefined) },\n );\n}\n\n/** The model's side: every data slot is a binding (or, for media, the ids of the company's files). */\nexport const Bound = {\n value: bound([\"views_total\", \"spend_total\"], { days: Days }).describe(\n \"views_total: the latest views of the posts published in the window. spend_total: the company's spend in the window (the CEO only).\",\n ),\n delta: bound([\"views_change\"], {}).describe(\n \"views_change: the value's views_total against the same number of days before it, as a percentage. Its window is the value's.\",\n ),\n series: bound([\"spend_by_day\"], { days: z.number().int().min(2).max(30).default(14) }).describe(\"spend_by_day: the company's spend per day (the CEO only).\"),\n bars: bound([\"post_views\"], { limit: z.number().int().min(1).max(12).default(5).describe(\"How many posts, newest first. Default 5.\") }).describe(\n \"post_views: each recent post's latest views, newest first.\",\n ),\n progress: bound([\"posts_this_week\"], {}).describe(\"posts_this_week: posts published since Monday against the weekly cadence from the company's setup.\"),\n board: bound([\"roadmap\"], {}).describe(\"roadmap: the board's work by status.\"),\n week: bound([\"schedule\"], {}).describe(\"schedule: routines and scheduled posts over the next 7 days.\"),\n media: z\n .union([bound([\"latest_media\"], { count: z.number().int().min(1).max(4).default(1) }), z.array(idOf(\"fil\")).min(1).max(4)])\n .describe('{\"$source\":\"latest_media\",\"count\":1} for the newest posted pictures or clips, or up to 4 fil_ ids.'),\n};\n\nexport const SpendDay = z.strictObject({ day: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/), micro_usd: Count });\n\n/** The result's side: each binding as it was asked, with what code read for it. */\nexport const Resolved = {\n value: z.discriminatedUnion(\"$source\", [\n z.strictObject({ $source: z.literal(\"views_total\"), days: z.number().int(), value: Count, posts: Count }),\n z.strictObject({ $source: z.literal(\"spend_total\"), days: z.number().int(), value: Count }),\n ]),\n delta: z.strictObject({ $source: z.literal(\"views_change\"), days: z.number().int(), current: Count, previous: Count }),\n series: z.strictObject({ $source: z.literal(\"spend_by_day\"), days: z.number().int(), points: z.array(SpendDay).min(2).max(30) }),\n bars: z.strictObject({ $source: z.literal(\"post_views\"), limit: z.number().int(), posts: PostViewsViewSchema.shape.posts }),\n progress: z.strictObject({ $source: z.literal(\"posts_this_week\"), value: Count, max: z.number().int().positive(), cadence: z.string() }),\n board: z.strictObject({ $source: z.literal(\"roadmap\"), groups: RoadmapViewSchema.shape.groups }),\n week: z.strictObject({ $source: z.literal(\"schedule\"), days: ScheduleViewSchema.shape.days }),\n media: z.array(z.strictObject({ id: idOf(\"fil\"), kind: z.enum([\"image\", \"video\"]) })).min(1).max(4),\n};\n\n/** An element that holds children, and one that holds none. */\nexport const box = { children: z.array(Key).min(1).max(12) };\nexport const leaf = { children: z.array(Key).max(0).optional() };\nexport const label = words(40).optional();\nexport const element = <T extends string, P extends z.ZodRawShape, C extends z.ZodRawShape>(type: T, props: P, children: C, about: string) =>\n z.strictObject({ type: z.literal(type), props: z.strictObject(props), ...children }).describe(about);\n\n/**\n * The components, once. `box` elements hold children; every other element is a leaf. One type\n * parameter per slot: a single `S extends Record<…, ZodType>` loses each slot's type to `unknown`.\n */\nexport function catalog<\n Value extends z.ZodType,\n Delta extends z.ZodType,\n Series extends z.ZodType,\n Bars extends z.ZodType,\n Goal extends z.ZodType,\n Board extends z.ZodType,\n Week extends z.ZodType,\n Files extends z.ZodType,\n>(slot: { value: Value; delta: Delta; series: Series; bars: Bars; progress: Goal; board: Board; week: Week; media: Files }) {\n return {\n Card: element(\"Card\", { title: words(60) }, box, \"The card, with a short title. It is the root, and only the root.\"),\n Stack: element(\"Stack\", {}, box, \"Children one under another.\"),\n Grid: element(\"Grid\", { columns: z.literal([1, 2, 3]) }, box, \"Children side by side, 1 to 3 columns.\"),\n Metric: element(\"Metric\", { label: words(40), value: slot.value, delta: slot.delta.optional() }, leaf, \"One big number with a label, and optionally its change.\"),\n LineChart: element(\"LineChart\", { label, series: slot.series }, leaf, \"A line over days.\"),\n BarList: element(\"BarList\", { label, bars: slot.bars }, leaf, \"One bar per post.\"),\n Progress: element(\"Progress\", { label: words(40), progress: slot.progress }, leaf, \"A value against its goal, as a bar.\"),\n Roadmap: element(\"Roadmap\", { label, board: slot.board }, leaf, \"The board grouped by status.\"),\n Schedule: element(\"Schedule\", { label, week: slot.week }, leaf, \"The week ahead, day by day.\"),\n Media: element(\"Media\", { label, files: slot.media }, leaf, \"Pictures or clips the company holds.\"),\n Text: element(\"Text\", { text: words(240) }, leaf, \"A short note in words.\"),\n };\n}\n\n/** An element outside the catalog is refused with the list. */\nexport const unknownComponent = (names: readonly string[]) => ({\n error: (issue: { code?: string }) => (issue.code === \"invalid_union\" ? `unknown component: use one of ${names.join(\", \")}` : undefined),\n});\n\n/**\n * THE TREE, CHECKED IN CODE. json-render draws whatever the map names and silently skips a child it\n * cannot find; here a missing child, a second parent, an orphan, a nested root or a root of the wrong\n * type is refused, so what the chat draws is exactly what the model sent.\n */\nfunction tree(rootType: string, max: number, spec: { root: string; elements: Record<string, { type: string; children?: string[] | undefined }> }, ctx: z.RefinementCtx): void {\n const refuse = (message: string, path: (string | number)[] = []) => ctx.addIssue({ code: \"custom\", message, path });\n const keys = Object.keys(spec.elements);\n // Own keys only: `toString` and `constructor` answer on every object, and are not elements.\n const has = (key: string): boolean => Object.hasOwn(spec.elements, key);\n if (keys.length > max) return refuse(`at most ${max} elements`, [\"elements\"]);\n const root = has(spec.root) ? spec.elements[spec.root] : undefined;\n if (!root) return refuse(`root names \"${spec.root}\", which is not in elements`, [\"root\"]);\n if (root.type !== rootType) return refuse(`the root must be a ${rootType}`, [\"root\"]);\n const parent = new Map<string, string>();\n for (const key of keys) {\n for (const child of spec.elements[key]!.children ?? []) {\n if (!has(child)) return refuse(`\"${child}\" is not in elements`, [\"elements\", key, \"children\"]);\n if (child === spec.root || parent.has(child)) return refuse(`\"${child}\" has more than one parent`, [\"elements\", key, \"children\"]);\n if (spec.elements[child]!.type === rootType) return refuse(`a ${rootType} is the root only; group with Stack or Grid`, [\"elements\", child, \"type\"]);\n parent.set(child, key);\n }\n }\n // One parent each and none for the root, so a walk down from the root ends; what it misses is\n // an orphan or a loop of its own.\n const reached = new Set([spec.root]);\n for (const key of reached) for (const child of spec.elements[key]!.children ?? []) reached.add(child);\n const lost = keys.find((key) => !reached.has(key));\n if (lost) refuse(`\"${lost}\" is not under the root`, [\"elements\", lost]);\n}\n\n/** A flat element map under one `root` of `rootType`, at most `max` elements, checked as a tree. */\nexport const spec = <E extends z.ZodType<{ type: string; children?: string[] | undefined }>>(element: E, rootType: string, max: number) =>\n z.strictObject({ root: Key, elements: z.record(Key, element) }).superRefine((value, ctx) => tree(rootType, max, value, ctx));\n","/**\n * core-gaps: contracts — media as REST (`canonical-spec §33–§35`): the `med_` job that every\n * async kind shares (D5), and the request/result shapes of images, videos, clips and audio.\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { FileSchema } from \"./resource\";\n\n/**\n * The catalogue's `kind` (`§33.3`, `§35.1`): what `GET /v1/media/models?kind=` and the CLI's\n * `--kind` select. Distinct from the job kinds below — a catalogue row is a capability, a job is\n * work in flight.\n */\nexport const MEDIA_MODEL_KINDS = [\"image\", \"video\", \"stt\", \"tts\", \"s2s\"] as const;\nexport type MediaModelKind = (typeof MEDIA_MODEL_KINDS)[number];\nexport const isMediaModelKind = (value: string): value is MediaModelKind =>\n MEDIA_MODEL_KINDS.some((kind) => kind === value);\n\n/** `image` is synchronous (a `fil_` straight back), so it is not a job kind. */\nexport const MEDIA_JOB_KINDS = [\"video\", \"clip\", \"transcription\"] as const;\nexport const MediaJobKindSchema = z.enum(MEDIA_JOB_KINDS);\nexport const MediaJobStatusSchema = z.enum([\"queued\", \"processing\", \"completed\", \"failed\"]);\n\nconst PublicUrl = z.string().url().startsWith(\"http\");\nconst Score = z.number().int().min(0).max(100);\nconst Seconds = z.number().nonnegative();\n\nexport const VideoResultSchema = z.object({\n files: z.array(\n z.object({\n file_id: idOf(\"fil\"),\n content_type: z.string(),\n width: z.number().int().positive().nullable(),\n height: z.number().int().positive().nullable(),\n duration_seconds: Seconds.nullable(),\n }),\n ),\n});\n\nexport const ViralityScoreSchema = z.object({\n total: Score,\n shareability: Score,\n hook_strength: Score,\n story_quality: Score,\n emotional_impact: Score,\n});\n\nexport const ClipResultSchema = z.object({\n clips: z.array(\n z.object({\n file_id: idOf(\"fil\"),\n title: z.string(),\n start_seconds: Seconds,\n end_seconds: Seconds,\n duration_seconds: Seconds,\n virality: ViralityScoreSchema,\n }),\n ),\n});\n\nexport const TranscriptSchema = z.object({\n text: z.string(),\n language: z.string().nullable(),\n duration_seconds: Seconds.nullable(),\n segments: z.array(z.object({ start_seconds: Seconds, end_seconds: Seconds, text: z.string() })),\n});\n\nexport const MediaJobResultSchema = z.union([VideoResultSchema, ClipResultSchema, TranscriptSchema]);\n\nexport const MediaJobSchema = z.object({\n id: idOf(\"med\"),\n object: z.literal(\"media_job\"),\n kind: MediaJobKindSchema,\n status: MediaJobStatusSchema,\n model: z.string().nullable(),\n input: z.record(z.string(), z.unknown()),\n result: MediaJobResultSchema.nullable(),\n error: z.object({ code: z.string(), message: z.string() }).nullable(),\n cost_micro_usd: MicroUsdField.nullable(),\n session_id: idOf(\"ses\").nullable(),\n created_at: Timestamp,\n completed_at: Timestamp.nullable(),\n});\nexport type MediaJob = z.infer<typeof MediaJobSchema>;\n\nexport const ImageRequestSchema = z.object({\n model: z.string().min(1).optional(),\n prompt: z.string().min(1),\n image_urls: z.array(PublicUrl).max(4).optional(),\n aspect_ratio: z.string().optional(),\n seed: z.number().int().optional(),\n n: z.number().int().min(1).max(4).default(1),\n});\n\nexport const VideoRequestSchema = z.object({\n /** Omitted: the platform's video default while the catalogue publishes it (`resolveModel`, §33.2). */\n model: z.string().min(1).optional(),\n prompt: z.string().min(1),\n image_urls: z.array(PublicUrl).max(1).optional(),\n /** The source clip of a video-to-video edit (ADR-0814). */\n video_url: PublicUrl.optional(),\n aspect_ratio: z.string().optional(),\n seed: z.number().int().optional(),\n seconds: z.number().int().min(1).max(60).optional(),\n});\n\nexport const ImageGenerationSchema = z.object({\n object: z.literal(\"image_generation\"),\n model: z.string(),\n files: z.array(FileSchema),\n cost_micro_usd: MicroUsdField,\n});\n\nconst ClipLength = z.number().int().min(5).max(180);\nexport const ClipRequestSchema = z.object({\n video_url: PublicUrl,\n aspect_ratio: z.enum([\"9:16\", \"16:9\"]).default(\"9:16\"),\n remove_silence: z.boolean().default(false),\n caption_preset: z.enum([\"none\", \"clean\", \"bold\", \"karaoke\"]).default(\"none\"),\n language: z.string().min(2).optional(),\n min_seconds: ClipLength.default(15),\n max_seconds: ClipLength.default(60),\n title: z.string().min(1).optional(),\n});\nexport type ClipRequest = z.infer<typeof ClipRequestSchema>;\n\nexport const AudioFormatSchema = z.enum([\"mp3\", \"wav\", \"ogg\"]);\n\n/** Exactly one source — a library file or a public URL. */\nexport const TranscriptionRequestSchema = z\n .object({\n model: z.string().min(1).optional(),\n file_id: idOf(\"fil\").optional(),\n url: PublicUrl.optional(),\n language: z.string().min(2).optional(),\n timestamps: z.boolean().default(true),\n })\n .refine((request) => (request.file_id === undefined) !== (request.url === undefined), {\n error: \"exactly one of file_id or url\",\n path: [\"file_id\"],\n });\n\nexport const SpeechRequestSchema = z.object({\n model: z.string().min(1).optional(),\n text: z.string().min(1).max(4_096),\n voice: z.string().min(1).optional(),\n format: AudioFormatSchema.default(\"mp3\"),\n speed: z.number().min(0.5).max(2).optional(),\n});\n\nexport const SpeechToSpeechRequestSchema = z.object({\n model: z.string().min(1).optional(),\n file_id: idOf(\"fil\"),\n voice: z.string().min(1).optional(),\n format: AudioFormatSchema.default(\"mp3\"),\n});\n\nexport const SpeechGenerationSchema = z.object({\n object: z.literal(\"speech_generation\"),\n model: z.string(),\n file: FileSchema,\n duration_seconds: Seconds.nullable(),\n cost_micro_usd: MicroUsdField,\n});\n","/**\n * core-gaps: contracts — an app backend's database and object storage on the wire\n * (`canonical-spec §37`, §38). Buckets and objects are customer-named and carry no id prefix.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const DbTableSchema = z.object({\n object: z.literal(\"db_table\"),\n name: z.string(),\n schema: z.string().default(\"public\"),\n rows: z.number().int().nonnegative().nullable(),\n size_bytes: z.number().int().nonnegative().nullable(),\n});\nexport type DbTable = z.infer<typeof DbTableSchema>;\n\nexport const DbMigrationSchema = z.object({\n id: idOf(\"dbm\"),\n object: z.literal(\"db_migration\"),\n name: z.string(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n applied_at: Timestamp,\n statements: z.number().int().nonnegative(),\n});\nexport type DbMigration = z.infer<typeof DbMigrationSchema>;\n\nexport const ApplyDbMigrationSchema = z.object({\n name: z.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9_-]*$/),\n sql: z.string().min(1),\n});\n\nexport const DB_REST_METHODS = [\"GET\", \"POST\", \"PATCH\", \"PUT\", \"DELETE\", \"HEAD\"] as const;\nexport const DbRestMethodSchema = z.enum(DB_REST_METHODS);\n\nexport const BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;\n\nexport const BucketSchema = z.object({\n object: z.literal(\"bucket\"),\n name: z.string().regex(BUCKET_NAME),\n public: z.boolean(),\n created_at: Timestamp,\n});\nexport type Bucket = z.infer<typeof BucketSchema>;\n\nexport const CreateBucketSchema = z.object({\n name: z.string().regex(BUCKET_NAME, { error: \"3–63 lowercase letters, digits and hyphens\" }),\n public: z.boolean().default(false),\n});\n\nexport const StorageObjectSchema = z.object({\n object: z.literal(\"storage_object\"),\n bucket: z.string(),\n key: z.string().min(1),\n size_bytes: z.number().int().nonnegative(),\n content_type: z.string(),\n etag: z.string().nullable(),\n updated_at: Timestamp,\n});\nexport type StorageObject = z.infer<typeof StorageObjectSchema>;\n\nexport const SignedUrlMethodSchema = z.enum([\"PUT\", \"GET\"]);\nexport const SignedUrlSchema = z.object({\n object: z.literal(\"signed_url\"),\n url: z.string().url(),\n method: SignedUrlMethodSchema,\n expires_at: Timestamp,\n});\nexport type SignedUrl = z.infer<typeof SignedUrlSchema>;\n\n/** `POST …/objects/{key}/upload-url` — a PUT the caller streams the bytes to. */\nexport const CreateUploadUrlSchema = z.object({\n content_type: z.string().min(1),\n expires_seconds: z.number().int().min(60).max(3_600).default(900),\n});\n","/**\n * core-gaps: contracts — stock photo search (`canonical-spec §39`, D6). The `id` is the\n * provider's, opaque and unprefixed; `attribution_url` is the one field allowed to point at the\n * provider's domain, because the licence requires it.\n */\n\nimport { z } from \"zod\";\n\nexport const STOCK_PHOTO_ORIENTATIONS = [\"landscape\", \"portrait\", \"square\"] as const;\nexport const STOCK_PHOTO_SIZES = [\"small\", \"medium\", \"large\"] as const;\n\nexport const StockPhotoQuerySchema = z.object({\n query: z.string().min(1).max(200),\n count: z.coerce.number().int().min(1).max(30).default(10),\n orientation: z.enum(STOCK_PHOTO_ORIENTATIONS).optional(),\n color: z.string().min(1).max(32).optional(),\n size: z.enum(STOCK_PHOTO_SIZES).optional(),\n});\nexport type StockPhotoQuery = z.infer<typeof StockPhotoQuerySchema>;\n\nexport const StockPhotoSchema = z.object({\n object: z.literal(\"stock_photo\"),\n id: z.string().min(1),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n url: z.string().url(),\n preview_url: z.string().url(),\n alt: z.string().nullable(),\n photographer: z.string().nullable(),\n attribution_url: z.string().url().nullable(),\n dominant_color: z.string().nullable(),\n});\nexport type StockPhoto = z.infer<typeof StockPhotoSchema>;\n","/**\n * The creator program (`canonical-spec §42`) — creators, their applications, referrals,\n * commissions, payouts and creator templates.\n *\n * None of these objects belongs to an organization (§42.12): a creator is a person keyed by email,\n * and a referral or a commission *points at* an organization's rows without living in the tenant.\n * Money is integer micro-USD, `floor`ed, USD only (§1).\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\n/** The referral code, and the namespace of every template the creator publishes: `c-<code>-<slug>`. */\nexport const CreatorCodeSchema = z\n .string()\n .regex(/^[a-z0-9]{3,24}$/, \"3 to 24 lowercase letters or digits\");\n\n/** `POST …/payouts` copies these onto the payout, so a later change never rewrites where money went. */\nexport const PayoutMethodSchema = z.enum([\"wise\", \"paypal\"]);\nexport type PayoutMethod = z.infer<typeof PayoutMethodSchema>;\n\nexport const PayoutDetailsSchema = z.object({\n method: PayoutMethodSchema,\n account: z.string().min(1).max(320),\n});\n\nexport const CreatorStatusSchema = z.enum([\"active\", \"suspended\"]);\nexport type CreatorStatus = z.infer<typeof CreatorStatusSchema>;\n\nexport const CreatorSchema = z.object({\n id: idOf(\"crt\"),\n object: z.literal(\"creator\"),\n email: z.email(),\n display_name: z.string().min(1).max(80),\n code: CreatorCodeSchema,\n status: CreatorStatusSchema,\n payout: PayoutDetailsSchema.nullable(),\n clicks: z.number().int().nonnegative(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Creator = z.infer<typeof CreatorSchema>;\n\n/** What `GET /v1/me` carries for a signed-in person (§20.1, §42.3). */\nexport const IdentityCreatorSchema = CreatorSchema.pick({\n id: true,\n status: true,\n});\nexport type IdentityCreator = z.infer<typeof IdentityCreatorSchema>;\n\nexport const CreatorApplicationStatusSchema = z.enum([\n \"pending\",\n \"approved\",\n \"rejected\",\n]);\nexport type CreatorApplicationStatus = z.infer<\n typeof CreatorApplicationStatusSchema\n>;\n\nexport const CreatorApplicationSchema = z.object({\n id: idOf(\"cra\"),\n object: z.literal(\"creator_application\"),\n email: z.email(),\n display_name: z.string().min(1).max(80),\n pitch: z.string().min(1).max(2000),\n links: z.array(z.url({ protocol: /^https$/ })).max(5),\n status: CreatorApplicationStatusSchema,\n note: z.string().nullable(),\n creator_id: idOf(\"crt\").nullable(),\n created_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type CreatorApplication = z.infer<typeof CreatorApplicationSchema>;\n\n/** Derived: `pending` until the first paid invoice, `active` for 12 months from it, `expired` after (§42.1). */\nexport const ReferralStatusSchema = z.enum([\"pending\", \"active\", \"expired\"]);\nexport type ReferralStatus = z.infer<typeof ReferralStatusSchema>;\n\nexport const ReferralSchema = z.object({\n id: idOf(\"crf\"),\n object: z.literal(\"referral\"),\n creator_id: idOf(\"crt\"),\n organization_id: idOf(\"org\"),\n status: ReferralStatusSchema,\n attributed_at: Timestamp,\n first_paid_at: Timestamp.nullable(),\n commission_until: Timestamp.nullable(),\n});\nexport type Referral = z.infer<typeof ReferralSchema>;\n\nexport const CommissionKindSchema = z.enum([\"referral\", \"template\"]);\nexport type CommissionKind = z.infer<typeof CommissionKindSchema>;\n\n/** Derived from `available_at` and the payout the row is claimed by, never stored (§42.1). */\nexport const CommissionStatusSchema = z.enum([\n \"pending\",\n \"available\",\n \"claimed\",\n \"paid\",\n]);\nexport type CommissionStatus = z.infer<typeof CommissionStatusSchema>;\n\nexport const CommissionSchema = z.object({\n id: idOf(\"crc\"),\n object: z.literal(\"commission\"),\n creator_id: idOf(\"crt\"),\n kind: CommissionKindSchema,\n referral_id: idOf(\"crf\").nullable(),\n install_id: idOf(\"bpi\").nullable(),\n creator_template_id: idOf(\"ctp\").nullable(),\n base_micro_usd: MicroUsdField.nonnegative(),\n amount_micro_usd: MicroUsdField.nonnegative(),\n status: CommissionStatusSchema,\n accrued_at: Timestamp,\n available_at: Timestamp,\n payout_id: idOf(\"crp\").nullable(),\n});\nexport type Commission = z.infer<typeof CommissionSchema>;\n\nexport const PayoutStatusSchema = z.enum([\"requested\", \"paid\", \"rejected\"]);\nexport type PayoutStatus = z.infer<typeof PayoutStatusSchema>;\n\nexport const PayoutSchema = z.object({\n id: idOf(\"crp\"),\n object: z.literal(\"payout\"),\n creator_id: idOf(\"crt\"),\n amount_micro_usd: MicroUsdField.positive(),\n currency: z.literal(\"USD\"),\n method: PayoutMethodSchema,\n account: z.string().min(1),\n status: PayoutStatusSchema,\n reference: z.string().nullable(),\n note: z.string().nullable(),\n requested_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type Payout = z.infer<typeof PayoutSchema>;\n\n/** The percentages and thresholds of §42.7, §42.9 and §42.10, in one place so no route restates them. */\nexport const CREATOR_PROGRAM = {\n referral_percent: 20,\n template_percent: 5,\n commission_months: 12,\n hold_days: 30,\n attribution_days: 30,\n minimum_payout_micro_usd: 20_000_000,\n} as const;\n\n/** The creator's own part of the catalog key; `template` is `c-<code>-<slug>` (§42.8). */\nexport const CreatorTemplateSlugSchema = z\n .string()\n .max(32)\n .regex(\n /^[a-z0-9]+(-[a-z0-9]+)*$/,\n \"lowercase letters, digits and single dashes\",\n );\n\n/** The namespaced catalog key: what `POST /v1/blueprints/installs` receives as `template`. */\nexport const creatorTemplateName = (code: string, slug: string): string =>\n `c-${code}-${slug}`;\n\n/** One `SKILL.md` travelling with the declaration — a creator has no checkout for the engine's `file`. */\nexport const CreatorSkillSchema = z.object({\n slug: z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"lowercase letters, digits and dashes\"),\n body: z\n .string()\n .min(1)\n .max(64 * 1024),\n});\nexport type CreatorSkill = z.infer<typeof CreatorSkillSchema>;\n\n/**\n * The version `declaration` (§42.2). `agents[]` is exactly `AgentDeclSchema` and `questions[]`\n * exactly `QuestionFieldSchema`, but `AgentDeclSchema` lives in `@usenaive-sdk/blueprints`, which\n * depends on core — so core types those two arrays as `unknown` and the API validates a submission\n * by composing the artifact declaration and running the engine's `parseProject` over it. The draft\n * is checked for this shape only; a half-written crew may be saved.\n */\nexport const CreatorDeclarationSchema = z.object({\n agents: z.array(z.unknown()),\n questions: z.array(z.unknown()),\n skills: z.array(CreatorSkillSchema).max(16),\n});\nexport type CreatorDeclaration = z.infer<typeof CreatorDeclarationSchema>;\n\nexport const CreatorTemplateVersionStatusSchema = z.enum([\n \"in_review\",\n \"approved\",\n \"changes_requested\",\n]);\nexport type CreatorTemplateVersionStatus = z.infer<\n typeof CreatorTemplateVersionStatusSchema\n>;\n\nconst VersionNumber = z.number().int().positive();\n\nexport const CreatorTemplateSchema = z.object({\n id: idOf(\"ctp\"),\n object: z.literal(\"creator_template\"),\n creator_id: idOf(\"crt\"),\n blueprint: z.string().min(1),\n base_template: z.string().min(1),\n slug: CreatorTemplateSlugSchema,\n template: z.string().min(1).max(64),\n name: z.string().min(1).max(80),\n description: z.string().max(2000),\n declaration: CreatorDeclarationSchema,\n published_version: VersionNumber.nullable(),\n latest_version: z\n .object({\n version: VersionNumber,\n status: CreatorTemplateVersionStatusSchema,\n })\n .nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type CreatorTemplate = z.infer<typeof CreatorTemplateSchema>;\n\n/** Keyed `(template_id, version)`; immutable but for `status`, `note`, `decided_at`, `artifact_id`. */\nexport const CreatorTemplateVersionSchema = z.object({\n object: z.literal(\"creator_template_version\"),\n template_id: idOf(\"ctp\"),\n version: VersionNumber,\n declaration: CreatorDeclarationSchema,\n status: CreatorTemplateVersionStatusSchema,\n note: z.string().nullable(),\n artifact_id: idOf(\"bpa\").nullable(),\n submitted_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type CreatorTemplateVersion = z.infer<\n typeof CreatorTemplateVersionSchema\n>;\n\n/** `GET /v1/creator/balance` — the caller's commissions summed by derived status (§42.4). */\nexport const CreatorBalanceSchema = z.object({\n object: z.literal(\"creator_balance\"),\n pending_micro_usd: MicroUsdField.nonnegative(),\n available_micro_usd: MicroUsdField.nonnegative(),\n claimed_micro_usd: MicroUsdField.nonnegative(),\n paid_micro_usd: MicroUsdField.nonnegative(),\n minimum_payout_micro_usd: z.literal(CREATOR_PROGRAM.minimum_payout_micro_usd),\n});\nexport type CreatorBalance = z.infer<typeof CreatorBalanceSchema>;\n\n/** `POST /v1/referral_clicks` (§42.6) — what the landing page times its 30-day cookie by. */\nexport const ReferralClickSchema = z.object({\n object: z.literal(\"referral_click\"),\n code: CreatorCodeSchema,\n creator: z.object({ display_name: z.string().min(1) }),\n expires_at: Timestamp,\n});\nexport type ReferralClick = z.infer<typeof ReferralClickSchema>;\n\nconst Day = z.iso.date();\n\n/** One shape for both analytics routes (§42.11); the template route narrows to one template's installs. */\nexport const CreatorAnalyticsSchema = z.object({\n object: z.literal(\"creator_analytics\"),\n days: z.number().int().min(1).max(90),\n from: Day,\n to: Day,\n clicks: z.number().int().nonnegative(),\n referrals: z.number().int().nonnegative(),\n installs: z.number().int().nonnegative(),\n active_installs: z.number().int().nonnegative(),\n usage_by_day: z.array(\n z.object({ day: Day, debit_micro_usd: MicroUsdField.nonnegative() }),\n ),\n commission_micro_usd: z.object({\n pending: MicroUsdField.nonnegative(),\n available: MicroUsdField.nonnegative(),\n claimed: MicroUsdField.nonnegative(),\n paid: MicroUsdField.nonnegative(),\n }),\n commissions_by_template: z.array(\n z.object({\n creator_template_id: idOf(\"ctp\"),\n amount_micro_usd: MicroUsdField.nonnegative(),\n }),\n ),\n /** Every install covered, newest first: the day it was created and the day its twelve months end. */\n install_windows: z.array(z.object({ install_id: idOf(\"bpi\"), from: Day, until: Day })),\n});\nexport type CreatorAnalytics = z.infer<typeof CreatorAnalyticsSchema>;\n","/** Identity-owned legal: verifications and companies (`canonical-spec.md §43`). */\n\nimport { z } from \"zod\";\nimport { VettaError } from \"../errors\";\nimport { Metadata, MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const LEGAL_MEMBER_STATUSES = [\n \"pending\",\n \"link_ready\",\n \"link_sent\",\n \"in_progress\",\n \"pending_review\",\n \"verified\",\n \"failed\",\n] as const;\nexport const LegalMemberStatusSchema = z.enum(LEGAL_MEMBER_STATUSES);\nexport type LegalMemberStatus = z.infer<typeof LegalMemberStatusSchema>;\n\nexport const LEGAL_VERIFICATION_STATUSES = [\"in_progress\", \"pending_review\", \"verified\", \"failed\"] as const;\nexport const LegalVerificationStatusSchema = z.enum(LEGAL_VERIFICATION_STATUSES);\nexport type LegalVerificationStatus = z.infer<typeof LegalVerificationStatusSchema>;\n\nexport const LEGAL_COMPANY_STATUSES = [\"awaiting_payment\", \"paid\", \"submitted\", \"formed\", \"failed\"] as const;\nexport const LegalCompanyStatusSchema = z.enum(LEGAL_COMPANY_STATUSES);\nexport type LegalCompanyStatus = z.infer<typeof LegalCompanyStatusSchema>;\n\nexport const LEGAL_DOCUMENT_KINDS = [\"articles\", \"ein_letter\", \"operating_agreement\", \"other\"] as const;\nexport const LegalDocumentKindSchema = z.enum(LEGAL_DOCUMENT_KINDS);\nexport type LegalDocumentKind = z.infer<typeof LegalDocumentKindSchema>;\n\nexport const LegalMemberRoleSchema = z.enum([\"primary\", \"secondary\"]);\nexport const LegalEinStatusSchema = z.enum([\"none\", \"pending\", \"issued\"]);\nexport const LegalRequiredActionKindSchema = z.enum([\"signature\", \"information\", \"payment\", \"other\"]);\nexport type LegalRequiredActionKind = z.infer<typeof LegalRequiredActionKindSchema>;\n\n/** The 50 states plus DC, two-letter and uppercase. */\nexport const US_STATES = [\n \"AL\", \"AK\", \"AZ\", \"AR\", \"CA\", \"CO\", \"CT\", \"DE\", \"DC\", \"FL\", \"GA\", \"HI\", \"ID\", \"IL\", \"IN\", \"IA\", \"KS\",\n \"KY\", \"LA\", \"ME\", \"MD\", \"MA\", \"MI\", \"MN\", \"MS\", \"MO\", \"MT\", \"NE\", \"NV\", \"NH\", \"NJ\", \"NM\", \"NY\", \"NC\",\n \"ND\", \"OH\", \"OK\", \"OR\", \"PA\", \"RI\", \"SC\", \"SD\", \"TN\", \"TX\", \"UT\", \"VT\", \"VA\", \"WA\", \"WV\", \"WI\", \"WY\",\n] as const;\nexport const UsStateSchema = z.enum(US_STATES);\nexport type UsState = z.infer<typeof UsStateSchema>;\n\nexport const LegalMemberInputSchema = z.object({\n first_name: z.string().min(1).max(128),\n last_name: z.string().min(1).max(128),\n email: z.string().min(1).max(320),\n role: LegalMemberRoleSchema,\n is_responsible_party: z.boolean(),\n ownership_percent: z.number().int(),\n});\nexport type LegalMemberInput = z.infer<typeof LegalMemberInputSchema>;\n\nexport const LegalMemberSchema = LegalMemberInputSchema.extend({\n id: idOf(\"lgm\"),\n object: z.literal(\"legal_member\"),\n verification_id: idOf(\"lgv\"),\n status: LegalMemberStatusSchema,\n link_url: z.url().nullable(),\n link_expires_at: Timestamp.nullable(),\n completed_at: Timestamp.nullable(),\n});\nexport type LegalMember = z.infer<typeof LegalMemberSchema>;\n\nexport const LegalVerificationSchema = z.object({\n id: idOf(\"lgv\"),\n object: z.literal(\"legal_verification\"),\n identity_id: idOf(\"idn\"),\n status: LegalVerificationStatusSchema,\n members: z.array(LegalMemberSchema),\n ready_for_formation: z.boolean(),\n started_at: Timestamp,\n completed_at: Timestamp.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type LegalVerification = z.infer<typeof LegalVerificationSchema>;\n\nexport const StartLegalVerificationSchema = z.object({ members: z.array(LegalMemberInputSchema) });\nexport type StartLegalVerification = z.infer<typeof StartLegalVerificationSchema>;\n\nexport const CompleteLegalMemberSchema = z.object({ token: z.string().min(1) });\n\nexport const LegalNameOptionSchema = z.object({ name: z.string().min(1).max(200), ending: z.literal(\"LLC\") });\nexport type LegalNameOption = z.infer<typeof LegalNameOptionSchema>;\n\nexport const LegalMailingAddressSchema = z.object({\n line1: z.string().min(1).max(200),\n line2: z.string().max(200).nullable(),\n city: z.string().min(1).max(100),\n state: UsStateSchema,\n postal_code: z.string().min(1).max(16),\n country: z.literal(\"US\"),\n});\nexport type LegalMailingAddress = z.infer<typeof LegalMailingAddressSchema>;\n\nexport const LegalRequiredActionSchema = z.object({\n kind: LegalRequiredActionKindSchema,\n description: z.string(),\n url: z.url().nullable(),\n});\nexport type LegalRequiredAction = z.infer<typeof LegalRequiredActionSchema>;\n\n/** The one length rule the provider imposes on a company description. */\nexport const LEGAL_DESCRIPTION_MAX = 50;\n\nexport const CreateLegalCompanySchema = z.object({\n verification_id: idOf(\"lgv\"),\n state: UsStateSchema,\n name_options: z.array(z.string().min(1).max(200)).min(1).max(3),\n naics_code: z.string().regex(/^\\d{2,6}$/),\n description: z.string().min(1).max(LEGAL_DESCRIPTION_MAX),\n mailing_address: LegalMailingAddressSchema,\n});\nexport type CreateLegalCompany = z.infer<typeof CreateLegalCompanySchema>;\n\nexport const LegalCompanySchema = CreateLegalCompanySchema.omit({ name_options: true }).extend({\n id: idOf(\"lgc\"),\n object: z.literal(\"legal_company\"),\n identity_id: idOf(\"idn\"),\n status: LegalCompanyStatusSchema,\n entity_type: z.literal(\"llc\"),\n name_options: z.array(LegalNameOptionSchema),\n legal_name: z.string().nullable(),\n ein_status: LegalEinStatusSchema,\n price_micro_usd: MicroUsdField,\n required_actions: z.array(LegalRequiredActionSchema),\n failure_reason: z.string().max(256).nullable(),\n submitted_at: Timestamp.nullable(),\n formed_at: Timestamp.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type LegalCompany = z.infer<typeof LegalCompanySchema>;\n\nexport const LegalDocumentSchema = z.object({\n id: idOf(\"lgd\"),\n object: z.literal(\"legal_document\"),\n company_id: idOf(\"lgc\"),\n kind: LegalDocumentKindSchema,\n name: z.string(),\n created_at: Timestamp,\n});\nexport type LegalDocument = z.infer<typeof LegalDocumentSchema>;\n\nexport const LegalDocumentLinkSchema = z.object({\n object: z.literal(\"legal_document_link\"),\n url: z.url(),\n expires_at: Timestamp,\n});\nexport type LegalDocumentLink = z.infer<typeof LegalDocumentLinkSchema>;\n\nexport const NaicsCodeSchema = z.object({\n object: z.literal(\"naics_code\"),\n code: z.string().regex(/^\\d{2,6}$/),\n title: z.string(),\n});\nexport type NaicsCode = z.infer<typeof NaicsCodeSchema>;\n\nexport const LegalStateSchema = z.object({\n object: z.literal(\"legal_state\"),\n code: UsStateSchema,\n name: z.string(),\n formation_fee_micro_usd: MicroUsdField,\n});\nexport type LegalState = z.infer<typeof LegalStateSchema>;\n\n/** What the provider's webhook tells us about one hosted session, vendor words already translated. */\nexport const LegalWebhookEventSchema = z.object({\n provider_session_ref: z.string().min(1),\n status: z.enum([\"verified\", \"failed\", \"pending_review\"]),\n metadata: Metadata,\n});\nexport type LegalWebhookEvent = z.infer<typeof LegalWebhookEventSchema>;\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** The legacy `validateMembers` rules, messages verbatim, as one `validation_failed` (§43.3). */\nexport function checkMembers(members: readonly LegalMemberInput[]): void {\n const refuse = (message: string): never => {\n throw new VettaError(\"validation_failed\", message, \"members\");\n };\n if (members.length === 0) refuse(\"At least one member is required\");\n const primaryCount = members.filter((m) => m.role === \"primary\").length;\n if (primaryCount !== 1) refuse(`Exactly one member must have role 'primary', found ${primaryCount}`);\n const rpCount = members.filter((m) => m.is_responsible_party).length;\n if (rpCount !== 1) refuse(`Exactly one member must be designated as responsible party, found ${rpCount}`);\n for (const m of members) {\n if (m.ownership_percent < 0 || m.ownership_percent > 100) {\n refuse(`Ownership percentage must be 0-100, got ${m.ownership_percent} for ${m.email}`);\n }\n }\n const totalOwnership = members.reduce((sum, m) => sum + m.ownership_percent, 0);\n if (totalOwnership !== 100) refuse(`Ownership percentages must sum to 100, got ${totalOwnership}`);\n for (const m of members) if (!EMAIL.test(m.email)) refuse(`Invalid email address: ${m.email}`);\n}\n\nconst LLC_ENDING = /\\s*(?:,\\s*)?(?:l\\.?l\\.?c\\.?|limited\\s+liability\\s+company)\\s*$/i;\n\n/** Strips any spelling of the LLC ending and answers the canonical `{ name, ending }` (§43.3). */\nexport function canonicalName(raw: string): LegalNameOption {\n const name = raw.replace(LLC_ENDING, \"\").trim();\n if (name.length === 0) throw new VettaError(\"validation_failed\", \"A company name is required\", \"name_options\");\n return { name, ending: \"LLC\" };\n}\n\n/** The display form of a name option: `\"<name> LLC\"`. */\nexport const displayName = (option: LegalNameOption): string => `${option.name} ${option.ending}`;\n\n/** The legacy status machine: any failed → failed; any review → pending_review; all verified → verified. */\nexport function verificationStatus(statuses: readonly LegalMemberStatus[]): LegalVerificationStatus {\n if (statuses.some((s) => s === \"failed\")) return \"failed\";\n if (statuses.some((s) => s === \"pending_review\")) return \"pending_review\";\n if (statuses.length > 0 && statuses.every((s) => s === \"verified\")) return \"verified\";\n return \"in_progress\";\n}\n\n/**\n * What a store keeps for each legal object: the wire shape less its transient/derived fields, plus\n * the provider handles. No handle is a person's data and no hosted-session token is a field here,\n * so a record can only ever project into a safe wire object (§43.1, PII boundary).\n */\nexport type LegalVerificationRecord = Omit<LegalVerification, \"object\" | \"members\" | \"ready_for_formation\">;\nexport type LegalMemberRecord = Omit<LegalMember, \"object\" | \"link_url\"> & {\n provider_session_ref: string | null;\n provider_person_ref: string | null;\n created_at: string;\n updated_at: string;\n};\nexport type LegalCompanyRecord = Omit<LegalCompany, \"object\"> & {\n ledger_entry_id: string | null;\n provider_customer_ref: string | null;\n provider_formation_ref: string | null;\n};\nexport type LegalDocumentRecord = Omit<LegalDocument, \"object\"> & { provider_document_ref: string };\n\n/** Member states a webhook redelivery or a poll may no longer move (§43.2). */\nexport const isTerminalMember = (status: LegalMemberStatus): boolean => status === \"verified\" || status === \"failed\";\n\n/** A provider outcome lands on a member unless the member is already final (§43.2). */\nexport function settleMember(\n member: LegalMemberRecord,\n outcome: { status: LegalMemberStatus; providerPersonRef: string | null },\n now: string,\n): LegalMemberRecord {\n if (isTerminalMember(member.status) || outcome.status === \"in_progress\") return member;\n return {\n ...member,\n status: outcome.status,\n provider_person_ref: outcome.providerPersonRef ?? member.provider_person_ref,\n completed_at: isTerminalMember(outcome.status) ? now : member.completed_at,\n updated_at: now,\n };\n}\n\n/** The parent follows its members (`verificationStatus`); the same record back means nothing moved. */\nexport function settleVerification(\n record: LegalVerificationRecord,\n members: readonly LegalMemberRecord[],\n now: string,\n): LegalVerificationRecord {\n const status = verificationStatus(members.map((m) => m.status));\n if (status === record.status) return record;\n const done = status === \"verified\" || status === \"failed\";\n return { ...record, status, completed_at: done ? now : null, updated_at: now };\n}\n\n/**\n * What a paid company files as: the row plus its members by verified-person handle. The adapter reads\n * each person's PII back from the provider vault; nothing personal crosses here (§43.1).\n */\nexport function formationInput(record: LegalCompanyRecord, members: readonly LegalMemberRecord[]) {\n const { postal_code: postalCode, ...address } = record.mailing_address;\n return {\n idempotencyKey: record.id,\n state: record.state,\n nameOptions: record.name_options,\n naicsCode: record.naics_code,\n description: record.description,\n mailingAddress: { ...address, postalCode },\n members: members.map((m) => {\n if (m.provider_person_ref === null) {\n throw new VettaError(\"state_conflict\", \"every member must be verified before the formation is filed\");\n }\n return {\n role: m.role,\n is_responsible_party: m.is_responsible_party,\n ownership_percent: m.ownership_percent,\n providerPersonRef: m.provider_person_ref,\n };\n }),\n };\n}\n\n/** Folds the provider's view of a filing into the row; `formed` and `failed` are final. */\nexport function foldFormation(\n record: LegalCompanyRecord,\n state: {\n providerFormationRef: string;\n status: Extract<LegalCompanyStatus, \"submitted\" | \"formed\" | \"failed\">;\n legalName: string | null;\n einStatus: LegalCompany[\"ein_status\"];\n requiredActions: LegalRequiredAction[];\n failureReason: string | null;\n },\n now: string,\n): LegalCompanyRecord {\n return {\n ...record,\n status: state.status,\n legal_name: state.legalName,\n ein_status: state.einStatus,\n required_actions: state.requiredActions,\n failure_reason: state.failureReason,\n provider_formation_ref: state.providerFormationRef,\n submitted_at: record.submitted_at ?? now,\n formed_at: state.status === \"formed\" ? (record.formed_at ?? now) : record.formed_at,\n updated_at: now,\n };\n}\n\n/** The wire member; `linkUrl` is only ever the link this very call minted (create / resend). */\nexport function toLegalMember(record: LegalMemberRecord, linkUrl: string | null = null): LegalMember {\n const { provider_session_ref: _s, provider_person_ref: _p, created_at: _c, updated_at: _u, ...safe } = record;\n return { object: \"legal_member\", ...safe, link_url: linkUrl };\n}\n\nexport function toLegalVerification(record: LegalVerificationRecord, members: LegalMember[]): LegalVerification {\n return { object: \"legal_verification\", ...record, members, ready_for_formation: record.status === \"verified\" };\n}\n\n/** Links are only ever the ones this call minted; a read never carries one (§43.1). */\nexport const verificationView = (\n record: LegalVerificationRecord,\n members: readonly LegalMemberRecord[],\n links = new Map<string, string>(),\n): LegalVerification =>\n toLegalVerification(record, members.map((m) => toLegalMember(m, links.get(m.id) ?? null)));\n\nexport function toLegalCompany(record: LegalCompanyRecord): LegalCompany {\n const { ledger_entry_id: _l, provider_customer_ref: _c, provider_formation_ref: _f, ...safe } = record;\n return { object: \"legal_company\", ...safe };\n}\n\nexport function toLegalDocument(record: LegalDocumentRecord): LegalDocument {\n const { provider_document_ref: _r, ...safe } = record;\n return { object: \"legal_document\", ...safe };\n}\n","/** Identity-owned custodied wallet with x402 payments (`canonical-spec.md §44`). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\n/** CAIP-2 on the wire: Base Sepolia (the default) and Base mainnet. */\nexport const WALLET_NETWORKS = [\"eip155:84532\", \"eip155:8453\"] as const;\nexport const WalletNetworkSchema = z.enum(WALLET_NETWORKS);\nexport type WalletNetwork = z.infer<typeof WalletNetworkSchema>;\nexport const DEFAULT_WALLET_NETWORK: WalletNetwork = \"eip155:84532\";\n\n/** The CLI / IaC aliases, resolved client-side to the CAIP-2 value. */\nexport const WALLET_NETWORK_ALIASES: Record<\"base-testnet\" | \"base\", WalletNetwork> = {\n \"base-testnet\": \"eip155:84532\",\n base: \"eip155:8453\",\n};\n\n/** `?network=` on every wallet route: which of the identity's wallets a call addresses. */\nexport const WalletSelectSchema = z.object({ network: WalletNetworkSchema.optional() });\nexport type WalletSelect = z.infer<typeof WalletSelectSchema>;\n\nexport const WALLET_STATUSES = [\"active\", \"frozen\", \"swept\"] as const;\nexport const WalletStatusSchema = z.enum(WALLET_STATUSES);\nexport type WalletStatus = z.infer<typeof WalletStatusSchema>;\n\nexport const WALLET_TRANSACTION_KINDS = [\"fund\", \"transfer\", \"pay\", \"sweep\"] as const;\nexport const WalletTransactionKindSchema = z.enum(WALLET_TRANSACTION_KINDS);\nexport type WalletTransactionKind = z.infer<typeof WalletTransactionKindSchema>;\n\nexport const WALLET_TRANSACTION_STATUSES = [\"pending\", \"confirmed\", \"failed\"] as const;\nexport const WalletTransactionStatusSchema = z.enum(WALLET_TRANSACTION_STATUSES);\nexport type WalletTransactionStatus = z.infer<typeof WalletTransactionStatusSchema>;\n\nexport const WalletDirectionSchema = z.enum([\"in\", \"out\"]);\nexport const WalletFundSourceSchema = z.enum([\"faucet\", \"treasury\"]);\n\nexport const EvmAddressSchema = z.string().regex(/^0x[0-9a-fA-F]{40}$/, \"expected a 0x address\");\nexport const TxHashSchema = z.string().regex(/^0x[0-9a-fA-F]{64}$/, \"expected a 0x transaction hash\");\n\n/** $0.50: the legacy default per-transaction cap. */\nexport const DEFAULT_PER_TX_CAP_MICRO_USD = 500_000;\n\nexport const WalletPolicySchema = z.object({\n per_tx_cap_micro_usd: MicroUsdField.nonnegative(),\n daily_cap_micro_usd: MicroUsdField.positive().nullable(),\n low_balance_micro_usd: MicroUsdField.nonnegative().nullable(),\n});\nexport type WalletPolicy = z.infer<typeof WalletPolicySchema>;\n\nexport const isTestnet = (network: WalletNetwork): boolean => network === \"eip155:84532\";\n\n/** The UTC day a `wallet_spend_counter` row is keyed by. */\nexport const walletDay = (nowIso: string): string => nowIso.slice(0, 10);\n\n/**\n * Why an outward amount is refused by the wallet's own policy, or `null` when it fits. The one\n * rule the route and the agent tool both enforce before the custody provider sees a request.\n */\nexport function walletCapViolation(\n policy: WalletPolicy,\n amountMicroUsd: number,\n spentTodayMicroUsd: number,\n): string | null {\n if (amountMicroUsd > policy.per_tx_cap_micro_usd) return \"the amount exceeds per_tx_cap_micro_usd\";\n if (policy.daily_cap_micro_usd !== null && spentTodayMicroUsd + amountMicroUsd > policy.daily_cap_micro_usd) {\n return \"the amount exceeds daily_cap_micro_usd for today\";\n }\n return null;\n}\n\n/** The cheapest requirement on the wallet's own network — the one a quote reports and a pay signs. */\nexport function pickPaymentRequirement<T extends { network: WalletNetwork; amountMicroUsd: number }>(\n requirements: readonly T[],\n network: WalletNetwork,\n): T | undefined {\n return requirements\n .filter((requirement) => requirement.network === network)\n .sort((a, b) => a.amountMicroUsd - b.amountMicroUsd)[0];\n}\n\nexport const WalletSchema = z.object({\n id: idOf(\"wlt\"),\n object: z.literal(\"wallet\"),\n identity_id: idOf(\"idn\"),\n status: WalletStatusSchema,\n network: WalletNetworkSchema,\n address: EvmAddressSchema,\n asset: z.literal(\"usdc\"),\n balance_micro_usd: MicroUsdField,\n policy: WalletPolicySchema,\n spent_today_micro_usd: MicroUsdField,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Wallet = z.infer<typeof WalletSchema>;\n\nexport const CreateWalletSchema = z.object({\n network: WalletNetworkSchema.optional(),\n policy: WalletPolicySchema.partial().optional(),\n});\nexport type CreateWallet = z.infer<typeof CreateWalletSchema>;\n\nexport const UpdateWalletPolicySchema = WalletPolicySchema.partial();\n\nexport const FundWalletSchema = z.object({\n amount_micro_usd: MicroUsdField.positive(),\n source: WalletFundSourceSchema,\n});\nexport type FundWallet = z.infer<typeof FundWalletSchema>;\n\nexport const TransferWalletSchema = z.object({\n to: z.union([EvmAddressSchema, idOf(\"idn\")]),\n amount_micro_usd: MicroUsdField.positive(),\n purpose: z.string().min(1).max(256),\n});\nexport type TransferWallet = z.infer<typeof TransferWalletSchema>;\n\nexport const SweepWalletSchema = z.object({ to: EvmAddressSchema.optional() });\n\nexport const WalletTransactionSchema = z.object({\n id: idOf(\"wtx\"),\n object: z.literal(\"wallet_transaction\"),\n wallet_id: idOf(\"wlt\"),\n kind: WalletTransactionKindSchema,\n direction: WalletDirectionSchema,\n amount_micro_usd: MicroUsdField,\n counterparty: z.string().nullable(),\n origin: z.string().nullable(),\n purpose: z.string().nullable(),\n tx_hash: TxHashSchema.nullable(),\n session_id: idOf(\"ses\").nullable(),\n status: WalletTransactionStatusSchema,\n created_at: Timestamp,\n});\nexport type WalletTransaction = z.infer<typeof WalletTransactionSchema>;\n\nexport const ListWalletTransactionsSchema = z.object({\n kind: WalletTransactionKindSchema.optional(),\n direction: WalletDirectionSchema.optional(),\n origin: z.string().optional(),\n since: Timestamp.optional(),\n});\nexport type ListWalletTransactions = z.infer<typeof ListWalletTransactionsSchema>;\n\nconst HttpMethodSchema = z.enum([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nexport const WalletQuoteRequestSchema = z.object({ url: z.url(), method: HttpMethodSchema.optional() });\nexport type WalletQuoteRequest = z.infer<typeof WalletQuoteRequestSchema>;\n\nexport const WalletQuoteSchema = z.object({\n object: z.literal(\"wallet_quote\"),\n url: z.url(),\n payable: z.boolean(),\n network: WalletNetworkSchema.nullable(),\n asset: z.literal(\"usdc\").nullable(),\n amount_micro_usd: MicroUsdField.nullable(),\n pay_to: EvmAddressSchema.nullable(),\n description: z.string().nullable(),\n max_timeout_seconds: z.number().int().nullable(),\n});\nexport type WalletQuote = z.infer<typeof WalletQuoteSchema>;\n\nexport const WalletPayRequestSchema = WalletQuoteRequestSchema.extend({\n max_amount_micro_usd: MicroUsdField.positive().optional(),\n});\nexport type WalletPayRequest = z.infer<typeof WalletPayRequestSchema>;\n\n/** The paid response's body is echoed up to this many bytes. */\nexport const WALLET_RESPONSE_BODY_MAX = 64 * 1024;\n\nexport const WalletPaymentSchema = z.object({\n object: z.literal(\"wallet_payment\"),\n paid: z.boolean(),\n transaction_id: idOf(\"wtx\").nullable(),\n amount_micro_usd: MicroUsdField.nullable(),\n response_status: z.number().int(),\n response_body: z.string().max(WALLET_RESPONSE_BODY_MAX),\n});\nexport type WalletPayment = z.infer<typeof WalletPaymentSchema>;\n\nexport * from \"./wallet-flow\";\n","/** Identity-owned prepaid virtual cards (`canonical-spec.md §45`). */\n\nimport { z } from \"zod\";\nimport { Metadata, MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const CARD_STATUSES = [\"pending_payment\", \"issuing\", \"active\", \"failed\", \"cancelled\", \"refunded\"] as const;\nexport const CardStatusSchema = z.enum(CARD_STATUSES);\nexport type CardStatus = z.infer<typeof CardStatusSchema>;\n\n/** The prepaid product's floor and the hard ceiling; the live bounds come from `card_quote`. */\nexport const CARD_MIN_LOAD_MICRO_USD = 1_000_000;\nexport const CARD_MAX_LOAD_MICRO_USD = 150_000_000;\n/**\n * A load is priced to the issuer as a decimal amount of dollars, so it has to land on a whole\n * cent: 21_000_009 µUSD would be ordered as `21.000009` and the row would then overstate the card\n * by the remainder for the rest of its life.\n */\nexport const CARD_LOAD_GRANULARITY_MICRO_USD = 10_000;\n\n/** `GET …/transactions?limit=`: the legacy defaults, kept. */\nexport const CARD_TRANSACTIONS_DEFAULT_LIMIT = 50;\nexport const CARD_TRANSACTIONS_MAX_LIMIT = 200;\n\nexport const CardSchema = z.object({\n id: idOf(\"vcd\"),\n object: z.literal(\"card\"),\n identity_id: idOf(\"idn\"),\n kind: z.literal(\"prepaid\"),\n status: CardStatusSchema,\n label: z.string().min(1).max(128),\n brand: z.string().nullable(),\n last4: z.string().regex(/^\\d{4}$/).nullable(),\n load_micro_usd: MicroUsdField,\n spent_micro_usd: MicroUsdField,\n currency: z.literal(\"usd\"),\n expires_at: Timestamp.nullable(),\n failure_reason: z.string().max(256).nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Card = z.infer<typeof CardSchema>;\n\nexport const IssueCardSchema = z.object({\n label: CardSchema.shape.label,\n load_micro_usd: MicroUsdField.min(CARD_MIN_LOAD_MICRO_USD)\n .max(CARD_MAX_LOAD_MICRO_USD)\n .multipleOf(CARD_LOAD_GRANULARITY_MICRO_USD),\n});\nexport type IssueCard = z.infer<typeof IssueCardSchema>;\n\nexport const CardQuoteRequestSchema = IssueCardSchema.pick({ load_micro_usd: true });\n\nexport const CardQuoteSchema = z.object({\n object: z.literal(\"card_quote\"),\n load_micro_usd: MicroUsdField,\n price_micro_usd: MicroUsdField,\n brand: z.string().nullable(),\n min_load_micro_usd: MicroUsdField,\n max_load_micro_usd: MicroUsdField,\n});\nexport type CardQuote = z.infer<typeof CardQuoteSchema>;\n\n/** The one shape that ever carries a secret; answered by one route, never cached, never stored in a row type. */\nexport const CardCredentialsSchema = z.object({\n object: z.literal(\"card_credentials\"),\n card_id: idOf(\"vcd\"),\n number: z.string().min(1),\n pin: z.string().nullable(),\n cvv: z.string().nullable(),\n expiry: z.string().nullable(),\n url: z.url().nullable(),\n instructions: z.string().nullable(),\n revealed_at: Timestamp,\n});\nexport type CardCredentials = z.infer<typeof CardCredentialsSchema>;\n\nexport const CardTransactionSchema = z.object({\n id: idOf(\"vct\"),\n object: z.literal(\"card_transaction\"),\n card_id: idOf(\"vcd\"),\n amount_micro_usd: MicroUsdField,\n merchant: z.string().nullable(),\n description: z.string().nullable(),\n session_id: idOf(\"ses\").nullable(),\n metadata: Metadata,\n created_at: Timestamp,\n});\nexport type CardTransaction = z.infer<typeof CardTransactionSchema>;\n\nexport const LogCardTransactionSchema = z.object({\n amount_micro_usd: MicroUsdField.positive(),\n merchant: z.string().max(256).optional(),\n description: z.string().max(1024).optional(),\n metadata: Metadata.optional(),\n});\nexport type LogCardTransaction = z.infer<typeof LogCardTransactionSchema>;\n\nexport const ListCardsSchema = z.object({ status: CardStatusSchema.optional() });\n\n/**\n * The stored card: the wire object plus the server columns no projection returns — what was paid,\n * the ledger key that paid it, and the issuer's references. Routes and tools both hold one and hand\n * out `wireCard(record)`, never the record.\n */\nexport interface CardRecord extends Card {\n price_micro_usd: number;\n ledger_entry_id: string | null;\n provider_product_ref: string | null;\n provider_order_ref: string | null;\n idempotency_key: string | null;\n}\n\nexport function wireCard(record: CardRecord): Card {\n const {\n price_micro_usd: _price,\n ledger_entry_id: _ledger,\n provider_product_ref: _product,\n provider_order_ref: _order,\n idempotency_key: _key,\n ...card\n } = record;\n return card;\n}\n","/**\n * The proxy call trace (`canonical-spec §26.5`, ADR-0745, migration 0077) — what a call to\n * `/v1/proxy/*` actually said, beside the ledger debit that says what it cost.\n *\n * A hosted agent turn leaves a transcript. A proxy call left exactly one row in the whole schema:\n * its `ledger_entry` debit. This object is the other half — the same call's prompt, reply, routing\n * and upstream attribution. Since ADR-0762 it also records every hosted-harness model call\n * (`source: \"harness\"`), literally and joinably to its session and event `seq`, and keeps it:\n * `expires_at` is null on new rows and the bodies are inline (`content_scope: full`, ADR-0794).\n *\n * `id` IS THE JOIN. It is the request id the proxy already uses three ways — `x-request-id`, the\n * reply's message id, and the ledger entry's `idempotency_key` — so a trace and its debit need no\n * correlation column to find each other.\n */\nimport { z } from \"zod\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, TokenUsageSchema, WindowSchema, idOf } from \"./common\";\n\n/**\n * Which door the call came in by. `anthropic` / `openai` are the two public proxy envelopes; `native`\n * is a hosted harness's own call through `ChatTransport`, which has no public envelope (ADR-0762).\n */\nexport const ProxyDialectSchema = z.enum([\"anthropic\", \"openai\", \"native\"]);\nexport type ProxyDialect = z.infer<typeof ProxyDialectSchema>;\n\n/**\n * Where a trace row's bodies are, written onto the row itself (ADR-0762, superseding ADR-0745's\n * configurable scope — capture is always full now).\n *\n * `full` — the bodies are inline on the row, in Postgres: every new row (ADR-0794 — records in\n * Postgres, files in object storage). `object` was ADR-0762's object-storage form, never shipped to\n * production and no longer written or read back; `metadata` survives only on rows from before\n * ADR-0762. Both remain in the enum so an old row still parses.\n */\nexport const ProxyTraceContentScopeSchema = z.enum([\"full\", \"metadata\", \"object\"]);\nexport type ProxyTraceContentScope = z.infer<typeof ProxyTraceContentScopeSchema>;\n\n/** A tool call as the model made it: its id is what the tool's own events join on. */\nconst TraceToolCall = z.object({ id: z.string().optional(), name: z.string(), arguments: z.string() });\n\n/**\n * One prompt as the transport saw it: the vendor-neutral `ChatMessage` shape, never a dialect's\n * envelope, and LITERAL since ADR-0762 — assistant `tool_calls` with their ids, `tool_call_id` on a\n * tool result, image links on a user turn, the full tool schema array, the output allowance. Rows\n * from before ADR-0762 carry `{role, content}` messages and `tool_names` only.\n */\nexport const ProxyTraceRequestSchema = z.object({\n model: z.string().optional(),\n window: WindowSchema.optional(),\n system: z.string(),\n messages: z.array(\n z.looseObject({\n role: z.string(),\n content: z.string(),\n tool_calls: z.array(z.looseObject({ id: z.string(), name: z.string() })).optional(),\n tool_call_id: z.string().optional(),\n }),\n ),\n tools: z\n .array(z.object({ name: z.string(), description: z.string(), parameters: z.record(z.string(), z.unknown()) }))\n .optional(),\n tool_schema_hash: z.string().optional(),\n max_output_tokens: z.number().int().optional(),\n tool_names: z.array(z.string()).optional(),\n});\n\n/**\n * One reply as it was assembled from the stream, whichever dialect it was then rendered into —\n * including the model's reasoning and any provider `reasoning_details` blocks, verbatim (ADR-0793).\n */\nexport const ProxyTraceResponseSchema = z.object({\n text: z.string(),\n reasoning: z.string().optional(),\n reasoning_details: z.array(z.unknown()).optional(),\n tool_calls: z.array(TraceToolCall),\n /** A call that threw, was abandoned or never completed (ADR-0794): the reply is what streamed before. */\n is_error: z.literal(true).optional(),\n /** The error's class name — never its message — or `incomplete` for a stream that just stopped. */\n error_class: z.string().optional(),\n partial: z.literal(true).optional(),\n});\n\n/**\n * Lowercase hex sha-256 of the stored body — present on every row. Since ADR-0762 nothing is\n * truncated, so it is the hash of the whole body: the request with its tool array replaced by\n * `tool_schema_hash`, and the reply. It is also the body's object-storage key.\n */\nconst Sha256 = z.string().regex(/^[0-9a-f]{64}$/);\n\nexport const ProxyCallTraceSchema = z.object({\n /** The request id: also `x-request-id`, the reply's `id`, and the ledger entry's idempotency key. */\n id: idOf(\"req\"),\n object: z.literal(\"proxy_call_trace\"),\n dialect: ProxyDialectSchema,\n /** The principal that made the call (§17). An API key here is the answer to \"who sent this\". */\n actor: PrincipalSchema,\n /** The public model id the caller asked for. */\n model: z.string(),\n window: WindowSchema,\n /** The model the reply said served it — where `vetta/auto` resolves — or null if it named none. */\n resolved_model: z.string().nullable(),\n /**\n * The serving provider and the gateway's own generation id. Null on every row written before the\n * adapter stops dropping them (Track A); together they are what lets an upstream invoice line be\n * matched back to an organization, a key and a ledger entry.\n */\n provider: z.string().nullable(),\n generation_id: z.string().nullable(),\n stop: z.enum([\"end_turn\", \"tool_use\", \"length\"]).nullable(),\n usage: TokenUsageSchema,\n /** What the customer was charged, µUSD. The ledger entry is the authority; this is its copy. */\n billed_micro_usd: MicroUsdField.nullable(),\n /** What the vendor said it cost, µUSD. A CROSS-CHECK, NEVER A DEBIT. */\n vendor_cost_micro_usd: MicroUsdField.nullable(),\n duration_ms: z.number().int().nonnegative().nullable(),\n content_scope: ProxyTraceContentScopeSchema,\n /** `proxy` — a `/v1/proxy/*` call; `harness` — a hosted harness's own model call (ADR-0762). */\n source: z.enum([\"proxy\", \"harness\"]),\n /** The session the call belongs to: a harness call's, or a sandbox token's `sub` on the proxy. */\n session_id: z.string().nullable(),\n /**\n * The `seq` of the call's `span.model_request.end` event — or of its `.start` when the call failed\n * or its `.end` was withheld (ADR-0794). Null on the proxy, which writes no event.\n */\n seq: z.number().int().nullable(),\n /** The board card the session was woken for (`session.metadata.board.card_id`), or null. */\n board_card_id: z.string().nullable(),\n /** The ids of the tool calls this reply made — the join to the `tool.*` events they caused. */\n tool_call_ids: z.array(z.string()),\n /** sha-256 of the canonical JSON of the tool schema array the model was offered, or null. */\n tool_schema_hash: Sha256.nullable(),\n request_sha256: Sha256,\n response_sha256: Sha256,\n /** The UTF-8 size of each stored body. */\n request_bytes: z.number().int().nonnegative(),\n response_bytes: z.number().int().nonnegative(),\n /** Inline in `full` scope — every new row. Null on a legacy `metadata` or `object` row. */\n request: ProxyTraceRequestSchema.nullable(),\n response: ProxyTraceResponseSchema.nullable(),\n /** Always false since ADR-0762 (nothing is cut); true only on rows from before it. */\n truncated: z.boolean(),\n created_at: Timestamp,\n /** When the reaper deletes this row. Null since ADR-0762: model I/O is kept, not expired. */\n expires_at: Timestamp.nullable(),\n});\nexport type ProxyCallTrace = z.infer<typeof ProxyCallTraceSchema>;\n","/**\n * A review (`canonical-spec §47`, ADR-0796, migration 0083) — a person's verdict on agent work given\n * outside Vetta's approval box: a post rejected in an app's queue, a caption edited before it ships.\n * The approval box's own decisions are `tool.confirm.resolved` events (ADR-0764); this is the same\n * judgement from everywhere else, joined to the session and board card by the files it names.\n */\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\n\nexport const ReviewDecisionSchema = z.enum([\"approve\", \"reject\", \"edit\"]);\nexport type ReviewDecision = z.infer<typeof ReviewDecisionSchema>;\n\n/** A reviewed field set (`{caption, title}` for a post); free-form, bounded. */\nconst Fields = z.record(z.string().max(100), z.unknown()).nullable().optional();\n\n/** `POST /v1/reviews`. The actor is the calling principal and is never part of the body. */\nexport const CreateReviewSchema = z.object({\n decision: ReviewDecisionSchema,\n reason: z.string().max(4_000).nullable().optional(),\n file_ids: z.array(idOf(\"fil\")).max(50).optional(),\n session_id: idOf(\"ses\").optional(),\n subject: z.record(z.string().max(100), z.unknown()).optional(),\n before: Fields,\n after: Fields,\n});\nexport type CreateReview = z.infer<typeof CreateReviewSchema>;\n\n/** What `POST /v1/reviews` answers: the review and what it was linked to. */\nexport interface ReviewCreated {\n id: string;\n object: \"review\";\n session_id: string | null;\n board_card_id: string | null;\n}\n","/**\n * MINI APPS — a template's pages of the platform's data-bound blocks (canonical-spec §50, ADR-0982).\n * A template declares its mini apps as data; the platform resolves every binding and the studio\n * draws every mini app with one general UI. A page's spec is `compose`'s (§49): a flat element map\n * under one root, words written by the author, every number a `$source` binding code resolves. The\n * catalog is the same one, plus the blocks a page needs: sections, what waits on a person, what the\n * agents are doing, the accounts, the posts, the setup's answers and the company's media library.\n */\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { PendingActionSchema, TEMPLATE_QUESTIONS_MAX } from \"./session\";\nimport { PostSchema, SocialPlatformSchema } from \"./social\";\nimport { RoadmapViewSchema } from \"./show\";\nimport { Bound, bound, box, catalog, element, Key, label, leaf, Resolved, spec, unknownComponent, words } from \"./catalog\";\n\nexport const PAGE_BLOCKS = [\n \"Page\", \"Section\", \"Stack\", \"Grid\", \"Metric\", \"LineChart\", \"BarList\", \"Progress\", \"Roadmap\", \"Schedule\", \"Media\", \"Text\",\n \"Needs\", \"Activity\", \"Accounts\", \"Posts\", \"Answers\", \"MediaLibrary\",\n] as const;\nexport const MAX_PAGE_ELEMENTS = 48;\n/** The icons a mini app may wear on its tile: a small fixed set, drawn by the studio. Never an agent's face. */\nexport const MINI_APP_ICONS = [\"grid\", \"list\", \"chart\", \"calendar\", \"play\"] as const;\nexport const MiniAppIconSchema = z.enum(MINI_APP_ICONS);\nexport type MiniAppIcon = z.infer<typeof MiniAppIconSchema>;\nconst SLUG = \"[a-z][a-z0-9-]{0,39}\";\nexport const MiniAppSlugSchema = z.string().regex(new RegExp(`^${SLUG}$`), \"a slug is lowercase letters, digits and -\");\n\n/** Where a section's head may lead: a platform place, or a mini app (one of its pages, if named). */\nconst Place = z\n .string()\n .regex(new RegExp(`^/(board|connections|apps/${SLUG}(\\\\?page=${SLUG})?)$`), \"a section links to /board, /connections or /apps/<slug>[?page=<slug>]\");\nconst POSTS = [\"waiting\", \"scheduled\", \"posted\"] as const;\nconst PostStatus = z.enum(POSTS);\n/** How a list of posts is drawn (ADR-1020): rows, one sideways row of cards, or a picture grid. */\nconst PostLayout = z.enum([\"list\", \"row\", \"grid\"]);\n/** One status, or several read into one list in the order given (ADR-1010). */\nconst PostStatuses = z.union([PostStatus, z.array(PostStatus).min(1).max(3).refine((all) => new Set(all).size === all.length, \"each status once\")]);\n\n/** A page's side of the shared slots: a roadmap may be shorter per group, media is up to six tiles. */\nconst PageBound = {\n ...Bound,\n board: bound([\"roadmap\"], { per_group: z.number().int().min(1).max(5).default(5) }),\n media: bound([\"latest_media\", \"newest_media\"], { count: z.number().int().min(1).max(6).default(4) }),\n};\nconst PageResolved = {\n ...Resolved,\n board: z.strictObject({ $source: z.literal(\"roadmap\"), per_group: z.number().int(), groups: RoadmapViewSchema.shape.groups }),\n media: z.array(z.strictObject({ id: z.string(), kind: z.enum([\"image\", \"video\"]) })).max(6),\n};\n\n/** The page's own blocks, bound or resolved. */\nfunction pageBlocks<Needs extends z.ZodType, Agents extends z.ZodType, Accounts extends z.ZodType, Posts extends z.ZodType, Answers extends z.ZodType>(slot: {\n needs: Needs;\n agents: Agents;\n accounts: Accounts;\n posts: Posts;\n answers: Answers;\n}) {\n return {\n Page: element(\"Page\", {}, box, \"The page itself, the root and only the root.\"),\n Section: element(\"Section\", { title: words(40), to: Place.optional(), hide_empty: z.boolean().optional() }, box, \"A titled part of the page; hidden when every block in it is empty, if asked.\"),\n Needs: element(\"Needs\", { label, needs: slot.needs }, leaf, \"What waits on a person: approvals, questions, spent caps.\"),\n Activity: element(\"Activity\", { label, agents: slot.agents }, leaf, \"The agents working or waiting, and on what.\"),\n Accounts: element(\"Accounts\", { accounts: slot.accounts }, leaf, \"The template's networks: connected with a handle, or not.\"),\n Posts: element(\n \"Posts\",\n { label, layout: PostLayout.optional(), posts: slot.posts },\n leaf,\n \"Posts waiting on a person, scheduled, or posted; several statuses make one list. Drawn as rows (list, the default), one sideways row of cards (row), or a picture grid (grid).\",\n ),\n Answers: element(\"Answers\", { answers: slot.answers }, leaf, \"The setup's answers in one line, linking to the setup.\"),\n // No binding: the studio's gallery reads and pages the company's files itself (ADR-0987).\n MediaLibrary: element(\"MediaLibrary\", {}, leaf, \"Every picture and clip the company's agents made, with filters, sort and a viewer.\"),\n };\n}\n\nconst OwnBound = pageBlocks({\n needs: bound([\"needs\"], {}),\n agents: bound([\"agents_activity\"], {}),\n accounts: bound([\"accounts\"], {}),\n posts: bound([\"posts\"], { status: PostStatuses, limit: z.number().int().min(1).max(50).default(10) }),\n answers: bound([\"answers\"], { keys: z.array(Key).min(1).max(TEMPLATE_QUESTIONS_MAX) }),\n});\n\nconst Need = z.object({\n session_id: z.string(),\n agent_id: z.string(),\n agent: z.string(),\n since: Timestamp,\n /** The chat's stored title, or `null`: the studio names it by when it began. */\n title: z.string().nullable(),\n kind: z.enum([\"tool\", \"question\", \"budget\"]),\n /** The call or question it is held on; `null` for a spent cap. */\n action: PendingActionSchema.nullable(),\n});\nconst Working = z.object({\n agent_id: z.string(),\n agent: z.string(),\n state: z.enum([\"working\", \"waiting\"]),\n session_id: z.string().nullable(),\n title: z.string().nullable(),\n at: Timestamp,\n});\n\nconst OwnResolved = pageBlocks({\n needs: z.strictObject({ $source: z.literal(\"needs\"), items: z.array(Need) }),\n agents: z.strictObject({ $source: z.literal(\"agents_activity\"), agents: z.array(Working) }),\n accounts: z.strictObject({\n $source: z.literal(\"accounts\"),\n accounts: z.array(z.object({ platform: SocialPlatformSchema, connected: z.boolean(), handle: z.string().nullable() })),\n }),\n posts: z.strictObject({ $source: z.literal(\"posts\"), status: z.union([PostStatus, z.array(PostStatus)]), limit: z.number().int(), posts: z.array(PostSchema), more: z.boolean() }),\n answers: z.strictObject({\n $source: z.literal(\"answers\"),\n keys: z.array(z.string()),\n values: z.array(z.string()),\n template: z.object({ blueprint: z.string(), template: z.string() }).nullable(),\n }),\n});\n\nconst BoundBlocks = { ...catalog(PageBound), ...OwnBound };\nconst ResolvedBlocks = { ...catalog(PageResolved), ...OwnResolved };\n\n/** A block whose source could not be read: one quiet line in its place, never the page down. */\nconst Unread = element(\"Unread\", { of: z.string(), label: z.string().nullable(), reason: z.string() }, leaf, \"A block that could not be read.\");\n\n/* Spelled out for each side, as `compose.ts` does: a helper generic over the blocks loses their types. */\nconst B = BoundBlocks;\nexport const PageSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [B.Page, B.Section, B.Stack, B.Grid, B.Metric, B.LineChart, B.BarList, B.Progress, B.Roadmap, B.Schedule, B.Media, B.Text, B.Needs, B.Activity, B.Accounts, B.Posts, B.Answers, B.MediaLibrary],\n unknownComponent(PAGE_BLOCKS),\n ),\n \"Page\",\n MAX_PAGE_ELEMENTS,\n);\nexport type PageSpec = z.infer<typeof PageSpecSchema>;\nexport type PageElement = PageSpec[\"elements\"][string];\n\nconst R = ResolvedBlocks;\n/** One resolved block: checked as it is read, so a bad one is one `Unread` line, not the page down. */\nexport const ResolvedPageElementSchema = z.discriminatedUnion(\n \"type\",\n [R.Page, R.Section, R.Stack, R.Grid, R.Metric, R.LineChart, R.BarList, R.Progress, R.Roadmap, R.Schedule, R.Media, R.Text, R.Needs, R.Activity, R.Accounts, R.Posts, R.Answers, R.MediaLibrary, Unread],\n unknownComponent(PAGE_BLOCKS),\n);\nexport const ResolvedPageSpecSchema = spec(ResolvedPageElementSchema, \"Page\", MAX_PAGE_ELEMENTS);\nexport type ResolvedPageSpec = z.infer<typeof ResolvedPageSpecSchema>;\nexport type ResolvedPageElement = ResolvedPageSpec[\"elements\"][string];\n/** One block's resolved props: what the studio's renderer draws. */\nexport type BlockProps<T extends ResolvedPageElement[\"type\"]> = Extract<ResolvedPageElement, { type: T }>[\"props\"];\n\nconst unique = (items: { slug: string }[]) => new Set(items.map((item) => item.slug)).size === items.length;\n\n/** One page of a mini app: a tab of its own, under its own title. */\nexport const MiniAppPageSchema = z.strictObject({ slug: MiniAppSlugSchema, title: words(24), spec: PageSpecSchema });\n\n/** One mini app as a template declares it: data only, checked with the catalog when it is read (§50.2). */\nexport const MiniAppDeclSchema = z.strictObject({\n slug: MiniAppSlugSchema,\n name: words(40),\n icon: MiniAppIconSchema,\n pages: z.array(MiniAppPageSchema).min(1).max(6).refine(unique, \"each page's slug is its own\"),\n});\nexport type MiniAppDecl = z.infer<typeof MiniAppDeclSchema>;\nexport const MiniAppDeclsSchema = z.array(MiniAppDeclSchema).max(8).refine(unique, \"each mini app's slug is its own\");\n\n/**\n * WHAT A MINI APP READS (§50.3, ADR-1048), derived by code from its declaration, never written by\n * its author: every `$source` bound on any of its pages, `media_library` for the library block, and\n * `posts_waiting` where a posts list shows posts waiting on a person — which that person can allow\n * or refuse from it. Sorted, each once.\n */\nexport function miniAppReads(app: MiniAppDecl): string[] {\n const reads = new Set<string>();\n for (const page of app.pages) {\n for (const element of Object.values(page.spec.elements)) {\n if (element.type === \"MediaLibrary\") reads.add(\"media_library\");\n for (const value of Object.values(element.props as Record<string, unknown>)) {\n const source = typeof value === \"object\" && value !== null && \"$source\" in value ? (value as { $source: unknown; status?: unknown }) : null;\n if (typeof source?.$source !== \"string\") continue;\n reads.add(source.$source);\n if (source.$source === \"posts\" && [source.status].flat().includes(\"waiting\")) reads.add(\"posts_waiting\");\n }\n }\n }\n return [...reads].sort();\n}\n\n/** `GET /v1/mini-apps` — the mini apps a company has, in its template's order (§50.3). */\nexport const MiniAppSummarySchema = z.object({\n object: z.literal(\"mini_app\"),\n slug: MiniAppSlugSchema,\n name: z.string(),\n icon: MiniAppIconSchema,\n pages: z.array(z.object({ slug: MiniAppSlugSchema, title: z.string() })).min(1),\n /** What it reads (`miniAppReads`). Absent from an older API: the Studio then claims nothing it cannot see. */\n reads: z.array(z.string()).optional(),\n});\nexport type MiniAppSummary = z.infer<typeof MiniAppSummarySchema>;\n\n/**\n * `GET /v1/mini-apps/{slug}` — one mini app with one page read, every binding at `as_of` on the\n * company's clock. `networks` is the applied template's networks for the header's marks, each with\n * whether a persona is connected to it (`null`: that could not be read; ADR-0992).\n */\nexport const MiniAppSchema = MiniAppSummarySchema.extend({\n networks: z.array(z.object({ platform: SocialPlatformSchema, connected: z.boolean().nullable() })),\n page: MiniAppSlugSchema,\n as_of: Timestamp,\n timezone: z.string().min(1),\n spec: ResolvedPageSpecSchema,\n});\nexport type MiniApp = z.infer<typeof MiniAppSchema>;\n","/**\n * The dashboard's short-lived bearer credential (`canonical-spec.md §20`). It is **signed, not\n * stored**: an HMAC over a JSON payload, so a login writes no row, a logout needs no revocation\n * table, and the credential cannot outlive its `exp`.\n *\n * It is presented in `Authorization: Bearer` exactly like an API key, and like an API key it is a\n * server-side secret — the dashboard keeps it in an httpOnly session and never sends it to a\n * browser (ADR-0017).\n */\nimport { VettaError } from \"./errors\";\nimport { SCOPES, type Role, type Scope } from \"./schema/index\";\n\n/** `test` or `live` — the tier a credential spends in. Mirrors the column `api_key.mode`. */\nexport type KeyMode = \"test\" | \"live\";\n\nexport const SESSION_TOKEN_PREFIX = \"vt_\";\n/** Thirty days. The dashboard has no refresh credential, so this is also its absolute sign-in. */\nexport const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;\n\nexport interface SessionClaims {\n /** The `usr_` member id in `org`, or the provider subject when the person has no membership. */\n sub: string;\n email: string;\n /** `null` until the person picks or creates an organization (`canonical-spec.md §20.4`). */\n org: string | null;\n /** The member's role in `org`, and what `scopes` was derived from. `null` when `org` is. */\n role: Role | null;\n mode: KeyMode;\n /** Derived from `role`, never chosen by the caller (`canonical-spec.md §20.4`). */\n scopes: Scope[];\n /** Epoch seconds. */\n exp: number;\n /**\n * MINTED FOR A SANDBOX, NOT FOR A PERSON. A class-B harness runs as a process inside a customer's\n * micro-VM and needs a credential to reach our metered model door; this marks that token so\n * `authenticate` gives it a `system` principal instead of inventing a `usr_` that names a `ses_`.\n *\n * It is deliberately a claim rather than an inference from `scopes`: the day a person's token\n * happens to carry one scope, an inference would silently reclassify them.\n */\n sandbox?: boolean;\n /**\n * MINTED FOR ONE AGENT'S TURN: the `agt_` id whose platform tools this token opens\n * (`apps/runtime-do/src/platform-tools.ts`). Like `sandbox`, it names a subsystem, never a person,\n * and it reaches only the routes marked `agent: true` (`apps/api/src/router.ts`). That list is the\n * boundary. `scopes` only has to cover it.\n */\n agent?: string;\n /**\n * MINTED FOR THE CEO'S TURN, NOT FOR A PERSON (ADR-1100): the `agt_` id of the agent the\n * control-plane credential is bound to (ADR-1097). Like `sandbox`, it names a subsystem, so the\n * token files as `system:agent:<id>` and is never `ctx.user`. Its `scopes` are the least of what\n * every person who drove the session holds, within `ORCHESTRATOR_SCOPES`, derived by the runtime\n * when it mints (`apps/runtime-do/src/drivers.ts`).\n */\n orchestrator?: string;\n}\n\n/**\n * The scopes an agent's platform token carries: enough for every route marked `agent: true`, and\n * the API's test checks they still are. They do not limit the token. The route list does, because\n * `agents:read` alone would open every persona's inbox (ADR-1096).\n */\nexport const AGENT_TOKEN_SCOPES: Scope[] = [\"billing:read\", \"agents:read\"];\n\n/**\n * Role → scopes (`canonical-spec.md §20.4`). A plain member gets everything except the three that\n * can spend money, mint credentials or redirect the org's outbound traffic; `admin` implies the\n * rest, so an owner needs the one entry. Derived here and never taken from the caller. Here rather\n * than in `apps/api` because the runtime derives the CEO's turn from it too.\n */\nconst MEMBER_DENIED: Scope[] = [\"admin\", \"billing:write\", \"webhooks:*\"];\n\nexport function scopesForRole(role: Role): Scope[] {\n if (role === \"owner\" || role === \"admin\") return [\"admin\"];\n return SCOPES.filter((scope) => !MEMBER_DENIED.includes(scope));\n}\n\n/**\n * The most the CEO's turn may hold (ADR-0190): everything a person can drive, minus `admin`, which\n * would let it mint keys and seal credentials — the two that turn a prompt injection into a\n * standing one. A turn holds less when the people driving it do (ADR-1100).\n */\nexport const ORCHESTRATOR_SCOPES: readonly Scope[] = [\n \"agents:read\",\n \"agents:write\",\n \"sessions:read\",\n \"sessions:write\",\n \"computers:write\",\n \"files:read\",\n \"files:write\",\n \"billing:read\",\n \"billing:write\",\n \"webhooks:*\",\n \"audit:read\",\n];\n\nconst encoder = new TextEncoder();\n\nfunction b64url(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...bytes)).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nfunction unb64url(text: string): Uint8Array {\n const padded = text.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const binary = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nasync function sign(secret: string, payload: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return b64url(new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(payload))));\n}\n\n/** Length-checked before the byte compare, so a wrong-length signature cannot be timed (§14). */\nfunction equalsConstantTime(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let index = 0; index < a.length; index += 1) difference |= a.charCodeAt(index) ^ b.charCodeAt(index);\n return difference === 0;\n}\n\nexport async function mintSessionToken(secret: string, claims: SessionClaims): Promise<string> {\n const payload = b64url(encoder.encode(JSON.stringify(claims)));\n return `${SESSION_TOKEN_PREFIX}${payload}.${await sign(secret, payload)}`;\n}\n\n/** Bad signature, bad shape and expiry are one answer: `unauthorized`, naming no internal detail. */\nexport async function readSessionToken(\n secret: string | null,\n token: string,\n nowSeconds: number,\n): Promise<SessionClaims> {\n if (secret === null || secret === \"\") {\n throw new VettaError(\"feature_not_configured\", \"dashboard sign-in is not configured\");\n }\n const [payload, signature] = token.slice(SESSION_TOKEN_PREFIX.length).split(\".\");\n if (!payload || !signature) throw new VettaError(\"unauthorized\", \"invalid session token\");\n if (!equalsConstantTime(await sign(secret, payload), signature)) {\n throw new VettaError(\"unauthorized\", \"invalid session token\");\n }\n const claims = JSON.parse(new TextDecoder().decode(unb64url(payload))) as SessionClaims;\n if (typeof claims.exp !== \"number\" || claims.exp <= nowSeconds) {\n throw new VettaError(\"unauthorized\", \"this sign-in has expired; sign in again\");\n }\n // One token speaks for one kind of caller: a box, an agent's turn, the CEO's turn, or a person.\n const named = (claim: unknown): boolean => claim !== undefined;\n const kinds = [claims.sandbox === true, named(claims.agent), named(claims.orchestrator)].filter(Boolean).length;\n const blank = [claims.agent, claims.orchestrator].some((claim) => named(claim) && (typeof claim !== \"string\" || claim === \"\"));\n if (kinds > 1 || blank) throw new VettaError(\"unauthorized\", \"invalid session token\");\n return claims;\n}\n","/**\n * The company's logo, as the SVG a person or an agent wrote (`canonical-spec §20.7`, ADR-1085).\n * `checkLogoSvg` is the only gate: the API's `PATCH /v1/organizations/{id}` and the agent's\n * `company.set_logo` both call it, and store what it answers.\n *\n * An allow-list read by a small tokenizer, not a DOM (a Worker has none) and not a deny-list: every\n * byte must be an allowed element, an allowed attribute with a quoted value of plain characters,\n * whitespace, or words inside `<title>`/`<desc>`. Anything the tokenizer cannot account for is\n * refused, with a sentence the writer can act on.\n */\n\nconst MAX_BYTES = 16 * 1024;\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nconst ELEMENTS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\", \"defs\",\n \"linearGradient\", \"radialGradient\", \"stop\", \"title\", \"desc\", \"clipPath\", \"mask\",\n]);\n\nconst ATTRIBUTES = new Set([\n \"viewBox\", \"xmlns\", \"width\", \"height\", \"x\", \"y\", \"x1\", \"y1\", \"x2\", \"y2\", \"cx\", \"cy\", \"r\", \"rx\",\n \"ry\", \"d\", \"points\", \"fill\", \"stroke\", \"stroke-width\", \"stroke-linecap\", \"stroke-linejoin\",\n \"stroke-miterlimit\", \"stroke-dasharray\", \"opacity\", \"fill-opacity\", \"stroke-opacity\", \"fill-rule\",\n \"clip-rule\", \"transform\", \"offset\", \"stop-color\", \"stop-opacity\", \"gradientUnits\",\n \"gradientTransform\", \"id\", \"clip-path\", \"mask\", \"preserveAspectRatio\", \"fx\", \"fy\", \"spreadMethod\",\n \"role\", \"aria-hidden\",\n]);\n\n/** Elements that hold words and nothing else. */\nconst WORDS = new Set([\"title\", \"desc\"]);\n\nconst HINTS: Record<string, string> = {\n text: \"draw the letters as paths\",\n tspan: \"draw the letters as paths\",\n textPath: \"draw the letters as paths\",\n image: \"draw it with shapes; a logo embeds no image\",\n foreignObject: \"draw it with shapes\",\n script: \"a logo runs no code\",\n style: \"set fill and stroke as attributes on each shape\",\n use: \"draw the shape again where it repeats\",\n a: \"a logo links nowhere\",\n};\n\nconst OPEN = /<([A-Za-z][\\w:.-]*)/y;\nconst CLOSE = /<\\/([A-Za-z][\\w:.-]*)[ \\t\\r\\n]*>/y;\nconst ATTRIBUTE = /[ \\t\\r\\n]+([A-Za-z_:][\\w:.-]*)[ \\t\\r\\n]*=[ \\t\\r\\n]*(?:\"([^\"]*)\"|'([^']*)')/y;\n/** Characters XML refuses, or Postgres `text` does (NUL). Matching them is the point. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/;\nconst TAG_END = /[ \\t\\r\\n]*(\\/?)>/y;\nconst LOCAL_URL = /url\\(#[A-Za-z_][\\w.-]*\\)/g;\nconst VALUE_CHARS = /^[\\w \\t\\r\\n#.,%()+-]*$/;\nconst VIEW_BOX = /^\\s*-?[\\d.]+(?:[\\s,]+-?[\\d.]+){3}\\s*$/;\n/** A checked root's start tag: no value holds `>` or `=`, so this reads only its own attributes. */\nconst ROOT_NS = /^<svg[^>]*\\sxmlns\\s*=/;\n\nexport type LogoCheck = { ok: true; svg: string } | { ok: false; reason: string };\n\n/**\n * An `<svg>` with `xmlns` on its root. The studio draws a logo as an `<img>` of a data URL, and a\n * browser draws an SVG without its namespace there as nothing. The web calls it too, on a logo an\n * agent proposes, before any check has run.\n */\nexport function withSvgNamespace(input: string): string {\n const svg = input.trim();\n return !/^<svg[\\s>]/.test(svg) || ROOT_NS.test(svg) ? svg : `<svg xmlns=\"${SVG_NS}\"${svg.slice(\"<svg\".length)}`;\n}\n\n/** The answer always carries `xmlns` on its root (`withSvgNamespace`). */\nexport function checkLogoSvg(input: string): LogoCheck {\n const svg = input.trim();\n const reason = firstProblem(svg);\n if (reason !== undefined) return { ok: false, reason };\n return { ok: true, svg: withSvgNamespace(svg) };\n}\n\nfunction firstProblem(svg: string): string | undefined {\n if (new TextEncoder().encode(svg).length > MAX_BYTES) {\n return `the logo is over 16 KB: simplify it — fewer points, shorter paths`;\n }\n // XML's own whitespace only, in tags and between them: a no-break space reads as a separator to a\n // regex and as an error to a browser, and a NUL is refused by the database.\n if (CONTROL.test(svg)) return \"control characters are not allowed: remove them\";\n if (!svg.startsWith(\"<svg\")) return `the logo must be one <svg viewBox=\"…\">…</svg> element, with nothing around it`;\n const open: string[] = [];\n let at = 0;\n let closed = false;\n while (at < svg.length) {\n const lt = svg.indexOf(\"<\", at);\n const text = svg.slice(at, lt === -1 ? svg.length : lt);\n const problem = textProblem(text, open.at(-1));\n if (problem) return problem;\n if (lt === -1) break;\n if (closed) return \"nothing may follow the closing </svg>\";\n const special = declaration(svg, lt);\n if (special) return special;\n CLOSE.lastIndex = lt;\n const close = CLOSE.exec(svg);\n if (close) {\n const name = close[1] ?? \"\";\n const expected = open.pop();\n if (expected !== name) return expected ? `</${name}> closes <${expected}>: close it with </${expected}>` : `</${name}> closes nothing`;\n closed = open.length === 0;\n at = CLOSE.lastIndex;\n continue;\n }\n const tag = readElement(svg, lt, open);\n if (typeof tag === \"string\") return tag;\n if (!tag.selfClosing) open.push(tag.name);\n at = tag.end;\n }\n return open.length > 0 ? `<${open.at(-1)}> is never closed` : undefined;\n}\n\nfunction textProblem(text: string, parent: string | undefined): string | undefined {\n if (text.includes(\"&\")) return \"entities (&…;) are not allowed: write the character itself, or leave it out\";\n if (text.trim() !== \"\" && !(parent !== undefined && WORDS.has(parent))) {\n return \"words outside <title> or <desc> are not allowed: draw letters as paths\";\n }\n return undefined;\n}\n\nfunction declaration(svg: string, lt: number): string | undefined {\n if (svg.startsWith(\"<!--\", lt)) return \"comments are not allowed: remove them\";\n if (svg.startsWith(\"<![CDATA[\", lt)) return \"CDATA is not allowed: remove it\";\n if (svg.startsWith(\"<!\", lt)) return \"a DOCTYPE or entity declaration is not allowed: remove it\";\n if (svg.startsWith(\"<?\", lt)) return \"processing instructions (<?…?>) are not allowed: remove them\";\n return undefined;\n}\n\n/** One start tag at `lt`: its name, whether it closes itself, and where it ends — or why it is refused. */\nfunction readElement(svg: string, lt: number, open: string[]): { name: string; selfClosing: boolean; end: number } | string {\n OPEN.lastIndex = lt;\n const name = OPEN.exec(svg)?.[1];\n if (name === undefined) return \"a `<` must start an element: write shapes, not markup fragments\";\n const refused = elementProblem(name, open);\n if (refused) return refused;\n const attributes = new Map<string, string>();\n let at = OPEN.lastIndex;\n for (;;) {\n TAG_END.lastIndex = at;\n const end = TAG_END.exec(svg);\n if (end) {\n const selfClosing = end[1] === \"/\";\n const root = name === \"svg\" ? rootProblem(attributes, selfClosing) : undefined;\n return root ?? { name, selfClosing, end: TAG_END.lastIndex };\n }\n ATTRIBUTE.lastIndex = at;\n const attribute = ATTRIBUTE.exec(svg);\n if (!attribute) return `<${name}>'s attributes must each be name=\"value\", quoted, separated by spaces`;\n const [, key = \"\", double, single] = attribute;\n const value = double ?? single ?? \"\";\n if (attributes.has(key)) return `\\`${key}\\` is set twice on <${name}>: keep one`;\n const problem = attributeProblem(name, key, value);\n if (problem) return problem;\n attributes.set(key, value);\n at = ATTRIBUTE.lastIndex;\n }\n}\n\nfunction elementProblem(name: string, open: string[]): string | undefined {\n const parent = open.at(-1);\n if (parent === undefined && name !== \"svg\") return `the logo must be one <svg> element, not <${name}>`;\n if (parent !== undefined && name === \"svg\") return \"one <svg> only: group shapes with <g>, not a nested <svg>\";\n if (parent !== undefined && WORDS.has(parent)) return `<${parent}> holds words only, not <${name}>`;\n if (ELEMENTS.has(name)) return undefined;\n const hint = HINTS[name] ?? (name.startsWith(\"animate\") || name === \"set\" ? \"a logo holds still\" : undefined);\n if (hint) return `<${name}> is not allowed: ${hint}`;\n const lower = [...ELEMENTS].find((allowed) => allowed.toLowerCase() === name.toLowerCase());\n if (lower) return `<${name}> must be written <${lower}>`;\n return `<${name}> is not allowed: use only ${[...ELEMENTS].map((element) => `<${element}>`).join(\", \")}`;\n}\n\nfunction attributeProblem(element: string, name: string, value: string): string | undefined {\n if (/^on/i.test(name)) return `\\`${name}\\` is not allowed: a logo runs no code`;\n if (/href$/i.test(name)) return `\\`${name}\\` is not allowed: a logo links to nothing; draw the shape where it is used`;\n if (name === \"style\") return \"`style` is not allowed: set fill, stroke and opacity as attributes\";\n if (name === \"class\") return \"`class` is not allowed: set fill and stroke as attributes on each shape\";\n if (!ATTRIBUTES.has(name)) return `\\`${name}\\` is not allowed on <${element}>: drop it (presentation and geometry attributes only)`;\n if (name === \"xmlns\") return value === SVG_NS ? undefined : `xmlns must be \"${SVG_NS}\" or left out`;\n const lower = value.toLowerCase();\n if (lower.includes(\"javascript:\")) return `\\`${name}\\` holds a script: a logo runs no code`;\n if (lower.includes(\"data:\")) return `\\`${name}\\` embeds data: draw it with shapes instead`;\n if (lower.includes(\"http\")) return `\\`${name}\\` points to the web: a logo loads nothing`;\n if (value.includes(\"&\")) return `\\`${name}\\` holds an entity (&…;): write the character itself`;\n if (value.includes(\"<\")) return `\\`${name}\\` holds a \\`<\\`: values are numbers, colours and names`;\n if (lower.replace(LOCAL_URL, \"\").includes(\"url(\")) return `\\`${name}\\` may reference only url(#id), written exactly so`;\n if (!VALUE_CHARS.test(value)) return `\\`${name}\\` holds a character a logo does not need: use numbers, names, #colours and url(#id)`;\n return undefined;\n}\n\nfunction rootProblem(attributes: Map<string, string>, selfClosing: boolean): string | undefined {\n const viewBox = attributes.get(\"viewBox\");\n if (viewBox === undefined) return `the <svg> needs a viewBox, such as viewBox=\"0 0 64 64\"`;\n if (!VIEW_BOX.test(viewBox)) return `viewBox must be four numbers, such as \"0 0 64 64\"`;\n if (selfClosing) return \"the <svg> is empty: draw the mark inside it\";\n return undefined;\n}\n","/**\n * The §40 signed read for one stored file — the HMAC and the address, in one place.\n *\n * It lives here for the reason `session-token.ts` does: `apps/api` already depends on\n * `apps/runtime-do`, so a *session tool* that must MINT one of these could not import the minter\n * from the route that verifies it without a cycle. One definition, so what mints and what verifies\n * cannot drift — and they must not, because a link that verifies differently than it was signed is\n * a 403 on a URL the model was told to look at.\n *\n * The construction is unchanged from the one `apps/api/src/routes/files.ts` has served since §40:\n * an HMAC over **every other field in the URL**, so there is nothing in it a holder can edit, and\n * `{name}` rides in the path rather than a query parameter so the URL ends in a real file extension\n * — which is what lets a `<video>` tag, a fetch-once publishing provider, and now a model provider\n * fetching an `image_url` type the thing from its address alone.\n */\n\nconst encoder = new TextEncoder();\n\n/**\n * The bound for a link minted BY A SESSION rather than by a person or an API key (ADR-0725).\n *\n * What it hands back is an unauthenticated bearer capability to raw org media: whoever holds the\n * string reads the bytes, with no credential and no further check. Seven days is the right trade\n * for a review link a person opens out of an email tomorrow (`files.ts` `FILE_URL_TTL_MS`). It is\n * the wrong trade for a link whose only consumer is a provider fetching it once, seconds from now,\n * minted on the one path a prompt injection can reach — so the window is sized to that fetch.\n *\n * It is here rather than in `files.ts` because three callers now mint at this bound — the\n * `POST /v1/files/{id}/url` route, the social publish, and the image link a tool result carries\n * (§16.2) — and the three must agree.\n */\nexport const SESSION_FILE_URL_TTL_MS = 15 * 60_000;\n\n/**\n * WHERE A GENERATED ASSET'S BYTES ARE (`canonical-spec §33.5`, ADR-0885): the media bucket, under a\n * `media:` scheme no other key can begin with — every other writer's key starts with an org id,\n * `naive/`, `model-io/` or a blueprint slug, none of which holds a colon. The row's `storage_key`\n * says it, and the storage adapter routes by it; nothing infers it from a path segment.\n */\nexport const mediaStorageKey = (org: string, id: string): string => `media:${org}/${id}`;\nexport const isMediaStorageKey = (key: string): boolean => key.startsWith(\"media:\");\n\n/** Everything the MAC covers. Change one field and every URL ever minted stops verifying. */\nexport interface FileUrlParts {\n org: string;\n id: string;\n name: string;\n /** Epoch milliseconds. */\n expires: number;\n /** The bytes are a generated asset's, in the media bucket; absent for every other file. */\n store?: \"media\" | undefined;\n}\n\n/** The store a file's link reads from, by its row's key. */\nexport const storeOf = (storageKey: string): FileUrlParts[\"store\"] =>\n isMediaStorageKey(storageKey) ? \"media\" : undefined;\n\nfunction b64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The MAC alone. `v1` is in the signed string so a future construction cannot be replayed as this one. */\nexport async function signFileUrl(secret: string, parts: FileUrlParts): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n // A media link signs its store, so it cannot be edited into a read of the other bucket; every\n // other link signs exactly what it always did, so no URL already handed out stops working.\n const store = parts.store === \"media\" ? \":media\" : \"\";\n const message = `vetta.file-url.v1:${parts.org}:${parts.id}:${parts.name}:${parts.expires}${store}`;\n return b64url(new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message))));\n}\n\n/** Constant-time over equal-length strings; unequal lengths are already a mismatch. */\nexport function fileUrlMacMatches(expected: string, given: string): boolean {\n if (expected.length !== given.length) return false;\n let diff = 0;\n for (let i = 0; i < expected.length; i += 1) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * The whole address, at `origin`. Callers own the TTL, because the two callers want very different\n * ones: seven days for a review link a person opens tomorrow, fifteen minutes for a capability\n * minted on a path a prompt injection can reach (`files.ts`, ADR-0725).\n */\nexport async function fileUrl(secret: string, origin: string, parts: FileUrlParts): Promise<string> {\n const url = new URL(`/v1/files/${parts.id}/${encodeURIComponent(parts.name)}`, origin);\n url.searchParams.set(\"org\", parts.org);\n url.searchParams.set(\"expires\", String(parts.expires));\n if (parts.store === \"media\") url.searchParams.set(\"in\", \"media\");\n url.searchParams.set(\"sig\", await signFileUrl(secret, parts));\n return url.toString();\n}\n","/**\n * `defineProject` — the whole blueprint DSL (`workstreams/10-blueprints.md §2`). Five resource\n * kinds, keyed by name; every declared field is a field the public API accepts (`canonical-spec\n * §12, §29`), never a translation layer. Refusals happen at define time, in the author's own\n * vocabulary, because the old system's lesson is that a refusal surfaced anywhere later gets\n * misread as a toolchain problem (see `load.ts`).\n */\nimport {\n APP_NAME,\n AppMcpPathSchema,\n AppTypeSchema,\n BudgetSchema,\n CreateLegalCompanySchema,\n CreateWalletSchema,\n DEFAULT_WALLET_NETWORK,\n CreateBucketSchema,\n ENV_NAME,\n HandoffsField,\n IdentitySchema,\n IssueCardSchema,\n JsonSchemaDocument,\n McpServerSchema,\n MiniAppDeclsSchema,\n Metadata,\n MicroUsdField,\n QuestionFieldSchema,\n SkillRefSchema,\n SocialPlatformSchema,\n TEMPLATE_QUESTIONS_MAX,\n ToolsetSchema,\n VaultCredentialKindSchema,\n VaultSchema,\n WindowSchema,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeclMultiagentField, hasRoster, rosterNames } from \"./roster\";\nimport { BLUEPRINTS, chooseTemplate, type Template } from \"./template\";\n\n/**\n * A config that loaded but refuses itself. A distinct class so the loader can tell \"the author's\n * declaration is wrong\" apart from \"the module could not be evaluated\" — the two failure modes the\n * old `naive up` collapsed into one, silently.\n */\nexport class BlueprintRefusal extends Error {\n override readonly name = \"BlueprintRefusal\";\n}\n\n/**\n * Where an app's environment value COMES FROM — a literal, a variable read at apply time, or a\n * value nobody has yet (`canonical-spec §29.7`). A secret never sits in the config file either way.\n *\n * `{ generate: true }` is the third source and it names one: *the platform invents this, once, on\n * the apply that first sets it.* It exists because `DASHBOARD_TOKEN`'s own comment in both live\n * blueprints reads \"set it to any long random string\" — a human inventing entropy is a defect, not\n * a setup question — and because a hosted apply has no shell to read one from.\n *\n * It carries no length or alphabet knob: there is exactly one kind of value worth inventing, and a\n * knob no author can reason about is a knob that will be got wrong. `z.literal(true)` rather than a\n * boolean, so `generate: false` is not a second, silent spelling of \"required\" — `from_env` is the\n * only spelling of that.\n *\n * NOTHING GENERATES FOR AN UNSET VARIABLE. A declaration has to ask, because inventing a value for\n * whatever happens to be missing would silently manufacture a credential for something that\n * genuinely needed the operator's, and the app would come up holding a secret nobody can reproduce.\n */\nconst EnvValueSchema = z.union([\n z.string(),\n z.object({ from_env: z.string().min(1) }),\n z.object({ generate: z.literal(true) }),\n]);\n\nconst AppDeclSchema = z.object({\n /** Becomes a hostname, so the grammar is the platform's `APP_NAME` (a DNS label). */\n name: z.string().regex(APP_NAME, \"a lowercase DNS label, 63 characters or fewer\"),\n type: AppTypeSchema,\n description: z.string().optional(),\n /** A directory whose files are collected and shipped as the app's file-map deployment. */\n deploy_dir: z.string().min(1).optional(),\n /** The path the app itself serves MCP on (§29.5); `fullstack` only. Absent means none. */\n mcp: AppMcpPathSchema.optional(),\n /** Written as the app's write-only secrets (§29.2) on every apply; names follow the platform's `ENV_NAME`. */\n env: z\n .record(z.string().regex(ENV_NAME), EnvValueSchema, { error: \"keyed by environment variable name (A-Z, 0-9, _)\" })\n .optional(),\n /** An install may not leave this app out of its `selection` (§31.2). Absent means it may. */\n required: z.boolean().optional(),\n // core-gaps: U8-database\n /** SQL files applied in order to the app's database after it is provisioned (§37); `fullstack` only. */\n migrations: z.array(z.string().min(1)).optional(),\n // core-gaps: storage-stock\n /** Buckets the app's object store must hold (§38.2); `fullstack` only. `public` defaults to false. */\n buckets: z.array(CreateBucketSchema).optional(),\n});\n\n/**\n * A cron on the agent — a platform deployment (§12) minus what `up` fills in: `agent_id`, and the\n * `identity`, a declared persona *name* like the agent's own. `cron` is the key the reconciler\n * matches live rows by (deployments have no name), so it must be unique within one agent.\n * `budget_micro_usd` has no default on `POST /v1/deployments`, so it is required here for the\n * same reason the agent's `budget` is.\n */\nconst ScheduleDeclSchema = z.object({\n cron: z.string().min(1),\n timezone: z.string().min(1).optional(),\n /** The message every fire opens its session with (`input_template` on the wire). */\n input: z.string().min(1),\n budget_micro_usd: MicroUsdField.nonnegative(),\n identity: z.string().min(1).optional(),\n enabled: z.boolean().optional(),\n});\n\n/** `ToolsetSchema` already refuses a malformed `tools.configs.browser.config` by field (`canonical-spec §32.2`). */\nconst ToolsDeclSchema = ToolsetSchema;\n\n/** Exactly the `POST /v1/agents` fields a blueprint declares — `model` and `budget` are required by that route, so requiring them here turns a guaranteed apply-time refusal into a define-time one. */\nconst AgentDeclSchema = z.object({\n name: z.string().min(1),\n model: z.string().min(1),\n budget: BudgetSchema,\n description: z.string().optional(),\n /** Two or three words the studio prints beside the name (§31.5) — \"Head of content\", not a sentence. */\n role: z.string().min(1).optional(),\n /** An install may not leave this agent out of its `selection` (§31.2). Absent means it may. */\n required: z.boolean().optional(),\n system: z.string().optional(),\n tools: ToolsDeclSchema.optional(),\n skills: z.array(SkillRefSchema).optional(),\n mcp_servers: z.array(McpServerSchema).optional(),\n /** The rest of the runtime's agent config (§31.6), each the core schema; absent means the route's default and never drift. */\n window: WindowSchema.optional(),\n /** A roster names crew members by declared *name*; `up` resolves them to `agt_` ids in a second pass (`roster.ts`). */\n multiagent: DeclMultiagentField.optional(),\n output_schema: JsonSchemaDocument.nullable().optional(),\n structured_output_required: z.boolean().optional(),\n metadata: Metadata.optional(),\n /** Declared app *names*; `up` resolves them to `app_` ids in `tools.configs.apps` (§29.3). */\n allowed_apps: z.array(z.string()).optional(),\n /** A declared identity *name*; `up` attaches it after the agent upsert (§22). */\n identity: z.string().min(1).optional(),\n /**\n * Who this agent may `send_to_agent` (§31.7, §28.12): `true` (anyone in the organization),\n * `false` (nobody), `\"team\"` (its `multiagent` roster), or declared agent *names*, checked\n * against the roster here. Absent means the route's default, `true`, and is never drift.\n */\n handoffs: HandoffsField.optional(),\n /** The agent's deployments as a complete set: declared → owned, and the rest are pruned (ADR-0355). */\n schedules: z.array(ScheduleDeclSchema).optional(),\n /**\n * The first thing this agent reads, once, on the apply that **creates** it (`canonical-spec\n * §31.4`). It is what turns a provisioned crew into a crew that has started working.\n *\n * Neither of its neighbours can carry it. A `schedule` fires again and again; an intake happens\n * exactly once, at creation, and never on a later apply of the same agent. `system` is standing\n * instruction re-read every turn; an intake is a message the agent is sent.\n *\n * `budget_micro_usd` is optional here and required on a schedule, because a cron spends\n * repeatedly and unattended while an intake spends once, at an apply a person is watching. Absent\n * means the agent's own `budget` governs.\n */\n intake: z\n .object({ message: z.string().min(1), budget_micro_usd: MicroUsdField.nonnegative().optional() })\n .optional(),\n});\n\n/**\n * A vault credential (§23) minus what `up` fills in. `value` is a real third-party secret, so it is\n * `{ from_env }` only — never a literal — and travels once, on create. Values are write-only and\n * rows immutable, so `kind`, `key` and `host` / `mcp_server_url` are all the reconciler can match a\n * live row by.\n */\nconst CredentialDeclSchema = z.object({\n kind: VaultCredentialKindSchema,\n key: z.string().min(1).max(128),\n /** The one exact destination host an `env_var` is bound to. */\n host: z.string().min(1).optional(),\n /** The MCP server URL a `static_bearer` / `mcp_oauth` token is matched to. */\n mcp_server_url: z.url().optional(),\n value: z.object({ from_env: z.string().min(1) }),\n});\n\n/** `name` is the vault's `display_name`, the key it is found by; `identity` a declared persona *name*. */\nconst VaultDeclSchema = z.object({\n name: VaultSchema.shape.display_name,\n identity: z.string().min(1).optional(),\n credentials: z.array(CredentialDeclSchema),\n});\n\n/** `file` holds the skill body, resolved against the config's directory; the slug grammar is `POST /v1/skills`' (§13). */\nconst SkillDeclSchema = z.object({\n slug: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, \"lowercase letters, digits and dashes\"),\n file: z.string().min(1),\n});\n\n/**\n * A company the identity should hold (`canonical-spec §43.6`), keyed by `label`. Members are people\n * and never sit in a repo, so `up` only REPORTS whether a company matching a name option exists; it\n * never starts a hosted check and never debits a fee.\n */\nconst LegalDeclSchema = CreateLegalCompanySchema.pick({\n state: true,\n name_options: true,\n naics_code: true,\n description: true,\n}).extend({ label: z.string().min(1).max(128) });\n\n/**\n * `POST /v1/identities/{id}/wallet`'s body (§44.5): created if absent, policy patched on drift, never\n * swept. One declaration per network — a single object (the testnet wallet unless it names a network)\n * or a list for a persona holding both.\n */\nconst WalletDeclSchema = CreateWalletSchema.or(\n z.array(CreateWalletSchema).refine(\n (list) => new Set(list.map((w) => w.network ?? DEFAULT_WALLET_NETWORK)).size === list.length,\n { message: \"one wallet per network\" },\n ),\n);\n\n/** `POST /v1/identities/{id}/cards`' body (§45.5): presence by `label`; a live non-terminal card is `unchanged`. */\nconst CardDeclSchema = IssueCardSchema;\n\nconst IdentityDeclSchema = IdentitySchema.pick({ name: true, description: true })\n .partial({ description: true })\n .extend({\n legal: z.array(LegalDeclSchema).optional(),\n wallet: WalletDeclSchema.optional(),\n cards: z.array(CardDeclSchema).optional(),\n });\n\n/** Names to delete on `up` — the declarative tombstone for a resource dropped from the config. */\nconst RemovedSchema = z.object({\n apps: z.array(z.string().min(1)).default([]),\n agents: z.array(z.string().min(1)).default([]),\n skills: z.array(z.string().min(1)).default([]),\n identities: z.array(z.string().min(1)).default([]),\n vaults: z.array(z.string().min(1)).default([]),\n});\n\n/**\n * Names this apply widens over instead of narrowing away: an agent another template of the same\n * blueprint declares and the chosen one does not. `up` reports each one that is live and writes\n * nothing — the switch rule, WIDEN NEVER NARROW. It is the mirror of `removed`, which stays the\n * only way anything is deleted, and `defineProject` fills it in from `templates`.\n */\nconst KeptSchema = z.object({ agents: z.array(z.string().min(1)).default([]) });\n\n/**\n * One card the apply seeds on the organization's board (`canonical-spec §31.11`). `key` is the\n * card's idempotency handle — `<project>:<key>` on the wire — so a re-apply finds the card it wrote;\n * `assignee` is an agent NAME, which is what a board card carries (§28.11); `blocked_by` names\n * sibling tasks by key and becomes their `crd_` ids at apply time.\n */\nconst TaskDeclSchema = z.object({\n key: z.string().min(1),\n title: z.string().min(1).max(200),\n body: z.string().max(8192).optional(),\n assignee: z.string().min(1).optional(),\n blocked_by: z.array(z.string().min(1)).optional(),\n});\n\nexport const ProjectSchema = z.object({\n name: z.string().min(1),\n /** The machine this project runs: its repo, its screens, its `/api/*` (`template.ts`). */\n blueprint: z.string().min(1).optional(),\n /** Which of that blueprint's templates provides the crew; a blueprint with a default may omit it. */\n template: z.string().min(1).optional(),\n /**\n * What a person calls this template, one line on what its crew does, and the networks it\n * publishes to (`canonical-spec §31.5`). Printed on the artifact and never provisioned: where the\n * crew posts is the accounts connected to its persona, not this list.\n */\n title: z.string().min(1).max(80).optional(),\n description: z.string().min(1).max(280).optional(),\n platforms: z.array(SocialPlatformSchema).optional(),\n /**\n * The company's mini apps (`canonical-spec §50`): each a name, an icon and pages of the platform's\n * blocks — data only, checked with the platform's catalog here and again when a page is read. The\n * studio draws every one with one general UI, under Apps.\n */\n mini_apps: MiniAppDeclsSchema.optional(),\n /**\n * What a person is asked BEFORE the crew is provisioned (`canonical-spec §31.2`).\n *\n * `QuestionField` is reused rather than restated: a setup question and a question a parked agent\n * asks mid-run are the same object asked at different times, so a blueprint author writes one\n * shape and one component renders both. These are published on the artifact — they are the whole\n * reason the catalog has a `questions` column — and the answers a person gives go on the install\n * (§29.6), never into the tree, because the tree is identical for everyone.\n *\n * **Configuration only.** A secret is a vault credential or an app secret; neither is an answer.\n */\n questions: z.array(QuestionFieldSchema).default([]),\n skills: z.array(SkillDeclSchema).default([]),\n identities: z.array(IdentityDeclSchema).default([]),\n vaults: z.array(VaultDeclSchema).default([]),\n apps: z.array(AppDeclSchema).default([]),\n agents: z.array(AgentDeclSchema).default([]),\n /**\n * The agents this template creates PER CLIENT the operator signs (`canonical-spec §31.1`) —\n * printed on the artifact so a person sees the whole company, never provisioned by an apply,\n * because the apply does not know the clients yet. Names only: a model and a budget are the\n * crew's business at the moment a client is signed, not the declaration's.\n */\n crew_per_client: z\n .array(z.object({ name: z.string().min(1), role: z.string().min(1).optional(), description: z.string().optional() }))\n .optional(),\n /** The crew's first work, as cards on the organization's board rather than N private intakes (§31.11). */\n tasks: z.array(TaskDeclSchema).default([]),\n removed: RemovedSchema.default({ apps: [], agents: [], skills: [], identities: [], vaults: [] }),\n kept: KeptSchema.default({ agents: [] }),\n});\n\nexport type AppDecl = z.infer<typeof AppDeclSchema>;\nexport type AgentDecl = z.infer<typeof AgentDeclSchema>;\nexport type CrewPerClientDecl = NonNullable<ProjectConfig[\"crew_per_client\"]>[number];\nexport type ScheduleDecl = z.infer<typeof ScheduleDeclSchema>;\nexport type SkillDecl = z.infer<typeof SkillDeclSchema>;\nexport type IdentityDecl = z.infer<typeof IdentityDeclSchema>;\nexport type VaultDecl = z.infer<typeof VaultDeclSchema>;\nexport type CredentialDecl = z.infer<typeof CredentialDeclSchema>;\nexport type TaskDecl = z.infer<typeof TaskDeclSchema>;\nexport type ProjectConfig = z.infer<typeof ProjectSchema>;\n\nfunction refuse(message: string): never {\n throw new BlueprintRefusal(message);\n}\n\nfunction assertUniqueNames(kind: \"app\" | \"agent\" | \"skill\" | \"identity\" | \"vault\" | \"bucket\" | \"task\", names: string[]): void {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n refuse(`duplicate ${kind} name \"${name}\" — resources are keyed by name, so each ${kind} must be declared exactly once`);\n }\n seen.add(name);\n }\n}\n\n/**\n * The tasks with every blocker ahead of the card it blocks, declaration order otherwise — the order\n * `up` creates them in, since a card's `blocked_by` carries ids only an earlier create has answered.\n * A set that never empties is a cycle, refused by name.\n */\nexport function inDependencyOrder(tasks: readonly TaskDecl[]): TaskDecl[] {\n const placed = new Set<string>();\n const out: TaskDecl[] = [];\n while (out.length < tasks.length) {\n const next = tasks.find((task) => !placed.has(task.key) && (task.blocked_by ?? []).every((key) => placed.has(key)));\n if (next === undefined) {\n const stuck = tasks.filter((task) => !placed.has(task.key)).map((task) => `\"${task.key}\"`);\n refuse(`tasks ${stuck.join(\", \")}: blocked_by forms a cycle — a card cannot wait on a card that waits on it`);\n }\n placed.add(next.key);\n out.push(next);\n }\n return out;\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value)) deepFreeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The blueprint / template pair, judged before anything else: an unknown one is refused here, not\n * discovered at apply time against a half-provisioned org. A blueprint with a default fills the\n * template in, so the config that comes back always names the crew that was applied.\n */\nfunction applyChoice(config: ProjectConfig): void {\n const chosen = chooseTemplate(config.blueprint, config.template);\n if (!chosen.ok) refuse(chosen.message);\n if (chosen.template !== undefined) config.template = chosen.template;\n}\n\n/** Validate an untyped value (a loaded `.json`, an evaluated module) into a frozen project. */\nexport function parseProject(input: unknown): Readonly<ProjectConfig> {\n const parsed = ProjectSchema.safeParse(input);\n if (!parsed.success) {\n // A union (`wallet: {…} | [{…}]`) reports \"Invalid input\" at its own path; the branch that got past\n // the shape check carries the author's actual mistake, so name that instead.\n const unwrap = (i: z.core.$ZodIssue): z.core.$ZodIssue[] => {\n if (i.code !== \"invalid_union\") return [i];\n const branch = i.errors.find((b) => !b.some((e) => e.code === \"invalid_type\" && e.path.length === 0));\n return branch ? branch.map((e) => ({ ...e, path: [...i.path, ...e.path] })) : [i];\n };\n const lines = parsed.error.issues.flatMap(unwrap).map((i) => `${i.path.join(\".\") || \"config\"}: ${i.message}`);\n refuse(`invalid project config — ${lines.join(\"; \")}`);\n }\n const config = parsed.data;\n applyChoice(config);\n // The cap is on what the studio puts in front of a buyer, not on what a hand-written config may\n // ask (§7.1). It was three; the fourth slot was bought by `optional` — a question that may be\n // left blank costs a person a glance, not an answer, so a form of four whose tail is optional is\n // still the one sitting the cap exists to protect. A fifth is not (ADR-0757).\n if (config.template !== undefined && config.questions.length > TEMPLATE_QUESTIONS_MAX) {\n refuse(`template \"${config.template}\" asks ${config.questions.length} questions, but a template asks at most ${TEMPLATE_QUESTIONS_MAX} before anything is provisioned — a fifth belongs to the crew's first conversation`);\n }\n assertUniqueNames(\"app\", [...config.apps.map((a) => a.name), ...config.removed.apps]);\n assertUniqueNames(\"agent\", [...config.agents.map((a) => a.name), ...config.removed.agents, ...config.kept.agents]);\n assertUniqueNames(\"skill\", [...config.skills.map((s) => s.slug), ...config.removed.skills]);\n assertUniqueNames(\"identity\", [...config.identities.map((i) => i.name), ...config.removed.identities]);\n assertUniqueNames(\"vault\", [...config.vaults.map((v) => v.name), ...config.removed.vaults]);\n const appNames = new Set(config.apps.map((a) => a.name));\n for (const app of config.apps) {\n if (app.type === \"frontend_only\" && app.mcp !== undefined) {\n refuse(`app \"${app.name}\": mcp is set, but a frontend_only app has no server to answer on it — declare type \"fullstack\" or drop mcp`);\n }\n // core-gaps: U8-database\n if (app.type === \"frontend_only\" && app.migrations !== undefined) {\n refuse(`app \"${app.name}\": migrations are set, but a frontend_only app has no database — declare type \"fullstack\" or drop migrations`);\n }\n // core-gaps: storage-stock\n if (app.type === \"frontend_only\" && app.buckets !== undefined) {\n refuse(`app \"${app.name}\": buckets are set, but a frontend_only app has no object store — declare type \"fullstack\" or drop buckets`);\n }\n assertUniqueNames(\"bucket\", (app.buckets ?? []).map((bucket) => bucket.name));\n }\n const identityNames = new Set(config.identities.map((i) => i.name));\n for (const vault of config.vaults) {\n if (vault.identity !== undefined && !identityNames.has(vault.identity)) {\n refuse(`vault \"${vault.name}\": identity names \"${vault.identity}\", but no identity with that name is declared in this project`);\n }\n const seen = new Set<string>();\n for (const credential of vault.credentials) {\n if (credential.kind === \"env_var\") {\n refuse(\n `vault \"${vault.name}\": credential \"${credential.key}\" is an env_var, which needs substitution at the sandbox egress boundary — not available on this platform, so the API would refuse it; use a static_bearer or mcp_oauth credential with an mcp_server_url, which is injected before the sandbox sees it`,\n );\n }\n const at = [credential.kind, credential.key, credential.host ?? credential.mcp_server_url ?? \"\"].join(\" \");\n if (seen.has(at)) {\n refuse(`vault \"${vault.name}\": credential ${credential.kind} \"${credential.key}\" is declared twice for the same destination — credentials are matched to live rows by kind, key and destination, so each must be unique per vault`);\n }\n seen.add(at);\n }\n }\n const agentNames = new Set([...config.agents.map((a) => a.name), ...config.kept.agents]);\n for (const agent of config.agents) {\n const rostered = new Set<string>();\n for (const name of hasRoster(agent.multiagent) ? rosterNames(agent.multiagent) : []) {\n if (name === agent.name) refuse(`agent \"${agent.name}\": multiagent roster names itself — a coordinator delegates to a copy of itself with { type: \"self\" }`);\n if (config.removed.agents.includes(name)) refuse(`agent \"${agent.name}\": multiagent roster names \"${name}\", which this config removes — drop it from the roster or keep the agent`);\n if (!agentNames.has(name)) refuse(`agent \"${agent.name}\": multiagent roster names \"${name}\", but no agent with that name is declared in this project`);\n if (rostered.has(name)) refuse(`agent \"${agent.name}\": multiagent roster names \"${name}\" twice — a team names each member once`);\n rostered.add(name);\n }\n for (const name of agent.allowed_apps ?? []) {\n if (!appNames.has(name)) {\n refuse(`agent \"${agent.name}\": allowed_apps names \"${name}\", but no app with that name is declared in this project`);\n }\n }\n if (agent.identity !== undefined && !identityNames.has(agent.identity)) {\n refuse(`agent \"${agent.name}\": identity names \"${agent.identity}\", but no identity with that name is declared in this project`);\n }\n if (agent.handoffs === \"team\" && !hasRoster(agent.multiagent)) {\n refuse(`agent \"${agent.name}\": handoffs is \"team\", but the agent declares no multiagent roster — there is no team to hand to`);\n }\n const handoffs = new Set<string>();\n for (const name of Array.isArray(agent.handoffs) ? agent.handoffs : []) {\n if (name === agent.name) refuse(`agent \"${agent.name}\": handoffs names itself — an agent cannot send_to_agent its own seat`);\n if (config.removed.agents.includes(name)) refuse(`agent \"${agent.name}\": handoffs names \"${name}\", which this config removes — drop it from handoffs or keep the agent`);\n if (!agentNames.has(name)) refuse(`agent \"${agent.name}\": handoffs names \"${name}\", but no agent with that name is declared in this project`);\n if (handoffs.has(name)) refuse(`agent \"${agent.name}\": handoffs names \"${name}\" twice`);\n handoffs.add(name);\n }\n const crons = new Set<string>();\n for (const schedule of agent.schedules ?? []) {\n if (crons.has(schedule.cron)) {\n refuse(`agent \"${agent.name}\": schedule cron \"${schedule.cron}\" is declared twice — schedules are matched to live deployments by cron, so each must be unique per agent`);\n }\n crons.add(schedule.cron);\n if (schedule.identity !== undefined && !identityNames.has(schedule.identity)) {\n refuse(`agent \"${agent.name}\": schedule \"${schedule.cron}\" identity names \"${schedule.identity}\", but no identity with that name is declared in this project`);\n }\n }\n }\n assertUniqueNames(\"task\", config.tasks.map((task) => task.key));\n const taskKeys = new Set(config.tasks.map((task) => task.key));\n for (const task of config.tasks) {\n if (`${config.name}:${task.key}`.length > 128) {\n refuse(`task \"${task.key}\": \"${config.name}:${task.key}\" is longer than the 128 characters a card key holds — shorten the key`);\n }\n if (task.assignee !== undefined && !agentNames.has(task.assignee)) {\n refuse(`task \"${task.key}\": assignee names \"${task.assignee}\", but no agent with that name is declared in this project`);\n }\n for (const key of task.blocked_by ?? []) {\n if (key === task.key) refuse(`task \"${task.key}\": blocked_by names itself — a card cannot wait on itself`);\n if (!taskKeys.has(key)) refuse(`task \"${task.key}\": blocked_by names \"${key}\", but no task with that key is declared in this project`);\n }\n }\n inDependencyOrder(config.tasks);\n return deepFreeze(config);\n}\n\n/** A config, plus the template data modules its blueprint repo carries (`template.ts`). */\nexport interface DefineInput extends z.input<typeof ProjectSchema> {\n /**\n * Every template this blueprint has — all of them, not just the chosen one. The chosen one's\n * agents become the project's crew; the others are what the switch rule keeps, which is why a\n * repo that carries only some of them is refused: switching would silently narrow.\n */\n templates?: readonly Template[];\n}\n\n/**\n * Fold the chosen template into the config: its crew joins whatever the config declares itself,\n * and every agent only a sibling template declares becomes a `kept` name. `removed` wins over\n * `kept` — an explicit tombstone is the operator narrowing on purpose.\n */\nfunction withTemplate(input: DefineInput, templates: readonly Template[]): DefineInput {\n const chosen = chooseTemplate(input.blueprint, input.template);\n if (!chosen.ok) refuse(chosen.message);\n if (chosen.template === undefined) refuse(\"templates are declared but no blueprint is — add `blueprint: \\\"…\\\"`\");\n const declared = BLUEPRINTS[input.blueprint!]!.templates;\n const carried = templates.map((one) => one.name);\n if ([...declared].sort().join(\" \") !== [...carried].sort().join(\" \")) {\n refuse(\n `blueprint \"${input.blueprint}\" has templates ${declared.join(\", \")}, but this repo carries ${carried.join(\", \") || \"none\"} — one repo carries every template of its blueprint, so switching is an edit and never a re-clone`,\n );\n }\n const picked = templates.find((one) => one.name === chosen.template)!;\n const agents = [...picked.agents, ...(input.agents ?? [])];\n const mine = new Set(agents.map((one) => one.name));\n const removed = new Set(input.removed?.agents ?? []);\n const kept = templates\n .filter((one) => one.name !== chosen.template)\n .flatMap((one) => one.agents.map((agent) => agent.name))\n .filter((name) => !mine.has(name) && !removed.has(name));\n return { ...input, template: chosen.template, agents, kept: { agents: [...new Set([...(input.kept?.agents ?? []), ...kept])] } };\n}\n\n/** The one export a `naive.config.ts` calls. Identity plus validation; the object comes back frozen. */\nexport function defineProject({ templates, ...input }: DefineInput): Readonly<ProjectConfig> {\n return parseProject(templates === undefined ? input : withTemplate(input, templates));\n}\n","/**\n * A coordinator's roster, declared by NAME (`canonical-spec §31.6`, §28).\n *\n * At runtime a roster entry is `{type:\"agent\", id:\"agt_…\", version?}`; in a declaration no agent has\n * an id yet, so the entry carries the declared `name` where the id goes and is otherwise the\n * runtime's own `RosterEntrySchema` — `self` and `advisor` unchanged. `up()` resolves the names in\n * a second pass, once every agent of the declaration has been created or patched and so has an id.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { MultiagentSchema, normaliseMultiagent, type Agent, type Multiagent } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport type { AgentDecl } from \"./define\";\nimport { changed, type ResourceReport } from \"./report\";\n\nconst NAME = z.string().min(1);\nconst RosterNameSchema = z.union([\n NAME.transform((name) => ({ type: \"agent\" as const, name })),\n z.object({ type: z.literal(\"agent\"), name: NAME, version: z.number().int().positive().optional() }),\n z.object({ type: z.literal(\"self\") }),\n z.object({ type: z.literal(\"advisor\"), model: z.string().min(1) }),\n]);\n\n/** `MultiagentField` with the roster by name: `true | false | null | {type:\"coordinator\", agents, board?}`. */\nexport const DeclMultiagentField = z.union([\n z.boolean(),\n z.object({ ...MultiagentSchema.shape, agents: z.array(RosterNameSchema).min(1).max(20) }),\n z.null(),\n]);\nexport type DeclMultiagent = z.infer<typeof DeclMultiagentField>;\nexport type DeclRoster = Extract<DeclMultiagent, { type: \"coordinator\" }>;\n\nexport const hasRoster = (value: DeclMultiagent | undefined): value is DeclRoster =>\n typeof value === \"object\" && value !== null;\n\n/** The declared names a roster refers to, in roster order. */\nexport const rosterNames = (roster: DeclRoster): string[] =>\n roster.agents.flatMap((entry) => (entry.type === \"agent\" ? [entry.name] : []));\n\n/** `true`/`false`/`null` need no id and travel with the agent in pass one; a roster waits for pass two. */\nexport const teamWithoutRoster = (value: DeclMultiagent | undefined): boolean | null | undefined =>\n hasRoster(value) ? undefined : value;\n\n/**\n * The live roster as the declaration would compare it: the API pins every member to its current\n * `version` on save (§28), so a pin the declaration did not write is not drift.\n */\nfunction unpinned(desired: Multiagent, live: Multiagent): Multiagent {\n return {\n ...live,\n agents: live.agents.map((entry, i) => {\n const want = desired.agents[i];\n const pinned = want !== undefined && \"version\" in want && want.version !== undefined;\n return entry.type === \"agent\" && !pinned ? { type: \"agent\", id: entry.id } : entry;\n }),\n };\n}\n\n/**\n * Pass two for one agent: its roster's names become the ids the crew now has, and `multiagent` is\n * patched where the live roster differs. The agent's own report line is amended in place — an\n * `unchanged` agent whose team changed is `updated`; a name with no live agent is `refused`, which\n * also holds back its intake (a coordinator is not briefed without its team).\n */\nexport async function patchRoster(\n client: VettaClient,\n decl: AgentDecl,\n roster: DeclRoster,\n existing: Agent[],\n ids: Map<string, string>,\n dryRun: boolean,\n lines: ResourceReport[],\n): Promise<void> {\n const line = lines.find((one) => one.name === decl.name);\n if (line === undefined || line.action === \"refused\") return;\n const updated = (): void => {\n if (line.action === \"unchanged\") line.action = \"updated\";\n };\n const missing = rosterNames(roster).find((name) => !ids.has(name));\n if (missing !== undefined) {\n // A member this plan would create has no id yet, so the roster cannot be live: drift, not a refusal.\n if (dryRun && lines.some((one) => one.name === missing && one.action === \"created\")) return updated();\n line.action = \"refused\";\n line.reason = `multiagent roster needs agent \"${missing}\", which was not provisioned in this run`;\n return;\n }\n const desired: Multiagent = {\n ...roster,\n agents: roster.agents.map((entry) =>\n entry.type === \"agent\"\n ? { type: \"agent\", id: ids.get(entry.name)!, ...(\"version\" in entry && entry.version !== undefined ? { version: entry.version } : {}) }\n : entry,\n ),\n };\n const current = existing.find((agent) => agent.name === decl.name);\n const live = current === undefined ? null : normaliseMultiagent(current.multiagent);\n if (live !== null && !changed(desired, unpinned(desired, live))) return;\n if (!dryRun && line.id !== undefined) {\n try {\n await client.agents.update(line.id, { multiagent: desired });\n } catch (error) {\n line.action = \"refused\";\n line.reason = error instanceof Error ? error.message : String(error);\n return;\n }\n }\n updated();\n}\n","/**\n * The report vocabulary `up` speaks (`workstreams/10-blueprints.md §2` item 4) and the handful of\n * client-side moves every resource kind shares: one line per attempt with refusals caught into\n * the report, drift as \"a declared field whose live value differs\", 404 as \"not yet\", full\n * cursor pagination, and the by-name tombstone behind `removed`.\n */\nimport { ApiError, send, type ClientConfig } from \"@usenaive-sdk/vetta\";\nimport type { ResourceAction, ResourceReportLine } from \"@vetta/core\";\nimport { z } from \"zod\";\n\n/**\n * The report vocabulary is `@vetta/core`'s (`schema/install.ts`), re-exported here rather than\n * declared here, because the hosted apply publishes this report on the install row (§29.6) — which\n * makes it a wire shape, and a wire shape has one definition (`CLAUDE.md §2`). The names and the\n * fields are unchanged, so every reader of this package sees exactly what it always saw.\n */\nexport type { ResourceAction };\nexport type ResourceReport = ResourceReportLine;\n\nfunction message(error: unknown): string {\n // An API refusal carries a `request_id` even when its body was not the envelope (§3): a bare\n // \"HTTP 503\" off an edge is untraceable without it, and it is the one thing an operator hands\n // support. Named here, once, so every refusal in the report is traceable — not just an app's.\n if (error instanceof ApiError && error.requestId !== \"\") return `${error.message} (request ${error.requestId})`;\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * One report line per attempt: a thrown API refusal becomes `refused`, never an escape.\n *\n * `id` resolves the resource this attempt was working on, read only when the work threw — an app\n * that was created and then failed its deploy upload exists, and a `refused` line that dropped its\n * id would tell the operator nothing was made (ADR-0375's `refused`-with-id is the precedent). The\n * resolver is asked after the throw, so it reads whatever the failed work had already recorded.\n *\n * Split from `attempt` for the one caller that runs its attempts at once and files them in\n * DECLARATION order rather than completion order (`agents.ts`) — a report whose lines arrive in\n * whichever order the server answered would name the same resources in a different order on every\n * apply, which is exactly what a person reads the report to compare.\n */\nexport async function line(\n name: string,\n work: () => Promise<ResourceReport>,\n id?: () => string | undefined,\n): Promise<ResourceReport> {\n try {\n return await work();\n } catch (error) {\n const resolved = id?.();\n return { name, action: \"refused\", ...(resolved !== undefined ? { id: resolved } : {}), reason: message(error) };\n }\n}\n\n/**\n * HOW MANY WRITES OF ONE KIND AN APPLY HAS IN FLIGHT AT ONCE, AND WHY THERE IS A CEILING.\n *\n * Independent writes run together — that is what took a hosted install's four timers from 18 s to\n * under 5. But the fan-out cannot be the length of the list: a hosted apply admits up to 96 timers\n * (`apps/api/src/reconcile.ts`), and 96 requests launched at once queue behind the API's own\n * per-isolate connection gate until they time out and come back as refusals. Six at a time is the\n * whole of the win — the lists a blueprint actually declares are shorter than that — with none of\n * the fan-out, and it is the same number the API admits concurrently at its end.\n */\nconst AT_ONCE = 6;\n\n/** `work` over every item, six in flight, results in the order the items were given. */\nexport async function eachInFlight<T, R>(items: readonly T[], work: (item: T) => Promise<R>): Promise<R[]> {\n const out: R[] = [];\n for (let at = 0; at < items.length; at += AT_ONCE) {\n out.push(...(await Promise.all(items.slice(at, at + AT_ONCE).map(work))));\n }\n return out;\n}\n\n/** …and filed in the report, in the order the attempts were made. */\nexport async function attempt(into: ResourceReport[], name: string, work: () => Promise<ResourceReport>): Promise<ResourceReport> {\n const one = await line(name, work);\n into.push(one);\n return one;\n}\n\n/**\n * The same value, written with object keys in a fixed order, so two spellings of one value compare\n * equal. Arrays keep their order — in a toolset, a skill list or an `allowed_apps` it is meaning.\n */\nconst canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value === null || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.keys(value as Record<string, unknown>)\n .sort()\n .map((key) => [key, canonical((value as Record<string, unknown>)[key])]),\n );\n};\n\n/**\n * A declared field whose live value differs; an undeclared field is never drift.\n *\n * Compared canonically, because the server is free to echo an object back with its keys in another\n * order and that is not a change. It did: a toolset went out as `{default_config, configs}` and\n * came back as `{configs, default_config}` with the tool names in a different order too, so every\n * agent carrying a `tools` block was judged drifted and PATCHed on every single apply. `naive up`\n * is supposed to converge — `sales` had reached version 8 doing nothing.\n */\nexport const changed = <T>(declared: T | undefined, live: T): declared is T =>\n declared !== undefined && JSON.stringify(canonical(declared)) !== JSON.stringify(canonical(live));\n\n/** A by-ref `GET` (skills and identities resolve their name) where 404 means \"not yet\". */\nexport async function absent<T>(work: Promise<T>): Promise<T | null> {\n try {\n return await work;\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) return null;\n throw error;\n }\n}\n\n/** A cursor page, shape only — the rows inside it are parsed one at a time. */\nconst PageShape = z.object({\n data: z.array(z.unknown()),\n has_more: z.boolean(),\n next_cursor: z.string().nullable(),\n});\n\n/** `deployment dep_…`, from whatever of a row we could not read still survives. */\nfunction rowLabel(row: unknown): string {\n const { object, id } = (row ?? {}) as { object?: unknown; id?: unknown };\n const words = [object, id].filter((one): one is string => typeof one === \"string\");\n return words.length > 0 ? words.join(\" \") : \"a row\";\n}\n\nconst why = (error: z.ZodError): string =>\n error.issues.map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`).join(\"; \");\n\n/**\n * Every row of a cursor-paginated list (§9), parsed **one row at a time** and read over `send`\n * rather than the SDK method, because the SDK parses a whole page against one strict schema.\n *\n * `up` reads every list before it writes anything, so one row the current contract no longer\n * admits aborted the entire apply — nothing written, nothing named, for the whole organization.\n * Measured on staging: two pre-ADR-0161 deployments still holding an `http://` `on_idle` stopped\n * `naive up` dead, and any customer carrying a pre-migration row meets it on their first apply.\n * A row the engine cannot read is a row it cannot reconcile: it is skipped and named in\n * `UpReport.skipped`, never thrown.\n */\nexport async function listAll<T>(\n config: ClientConfig,\n path: string,\n item: z.ZodType<T>,\n skipped: string[],\n query: Record<string, string | number | undefined> = {},\n): Promise<T[]> {\n const rows: T[] = [];\n let after: string | undefined;\n for (;;) {\n const response = await send(config, { method: \"GET\", path, query: { ...query, limit: 100, after } }, \"application/json\");\n const text = await response.text();\n if (!response.ok) throw new Error(`could not list ${path} (HTTP ${response.status})`);\n const body = PageShape.parse(JSON.parse(text));\n for (const row of body.data) {\n const parsed = item.safeParse(row);\n if (parsed.success) rows.push(parsed.data);\n else skipped.push(`${rowLabel(row)} in ${path} could not be read and was skipped: ${why(parsed.error)}`);\n }\n if (!body.has_more || body.next_cursor === null) return rows;\n after = body.next_cursor;\n }\n}\n\n/**\n * `removed` names delete by the same by-name lookup the upserts use. A name that is already\n * absent is `unchanged`, so a `removed` entry can stay in the config forever and re-running\n * stays safe; only a name that resolves to a live resource issues the DELETE.\n */\nexport async function tombstone(\n name: string,\n current: { id: string } | null | undefined,\n remove: (id: string) => Promise<unknown>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n if (!current) return { name, action: \"unchanged\", reason: \"already absent\" };\n if (!dryRun) await remove(current.id);\n return { name, action: \"deleted\", id: current.id };\n}\n","/**\n * Blueprints and their templates.\n *\n * A **blueprint** is the machine: screens, `/api/*`, the store, build and deploy, the approval\n * flow — or, for a data-only blueprint, none of those. It is one repository, and it is shared across\n * its templates. A **template** is DATA — the crew and its prompts, the tool allow-lists and its\n * schedules. What a blueprint's own screens print per template is the blueprint's business, and\n * the engine never reads it (ADR-0903). One repo carries every template its blueprint has, so\n * switching is an edit plus `naive up`: never a re-clone, never a new app.\n *\n * The pair is checked here and refused at define time (`define.ts`), in the author's own\n * vocabulary, for the same reason every other refusal is: a wrong pair discovered at apply time is\n * discovered against a half-provisioned organization.\n */\nimport type { AgentDecl } from \"./define\";\n\n/**\n * The data module a blueprint repo exports, one per template it carries. Everything here is data:\n * nothing in it is a function, a component or a route, because those are the blueprint's and are\n * shared. `agents` is the config's own `agents` shape, so a template declares a crew exactly as a\n * hand-written config would — prompts, tool allow-lists and schedules included.\n */\nexport interface Template {\n /** Spelled exactly as `defineProject({ template })` and `naive template --template` name it. */\n name: string;\n /** One line for the operator: what this crew does. */\n description: string;\n agents: AgentDecl[];\n}\n\n/**\n * Every blueprint and the templates it carries. `agency` defaults to `blank` — a working agency\n * with no specialism is a safe thing to get by accident. `media` has NO default on purpose: its\n * three crews spend money in different ways — a long-form piece renders a minute-plus of video\n * where a clip only cuts one — so defaulting any of them is a bill the operator did not choose.\n * `web` carries one crew today, so `publisher` is its default for the reason `blank` is\n * `agency`'s: the only thing you can get is the thing you meant.\n */\nexport const BLUEPRINTS: Record<string, { templates: readonly string[]; default?: string }> = {\n /** Clients, pipeline, deliverables, calendar. */\n agency: { templates: [\"blank\", \"seo-geo\"], default: \"blank\" },\n /**\n * Post queue, accounts, calendar, analytics. The wire ids are frozen: `install.template` is a\n * stored string on every provisioned org, so the display names moved (\"Naive Short Form v1\",\n * \"Naive Long Form v1\", \"Naive Clipping v1\") and these did not.\n *\n * The first three are the base crews. The six after them are NICHE CHANNEL TEMPLATES (ADR-1115,\n * ADR-1119): each is a thin template that reuses a base crew (`gaming-clips`/`news`/`sports` on\n * `clipping`; `ufc`/`history`/`animal-feast` on `faceless`) and pins `naive/channel-template-<niche>`\n * in every seat's `skills[]`. They are ordinary templates of this blueprint, so they publish, install\n * and switch through the exact paths the base three do — the whole point of a template being data.\n */\n media: { templates: [\"faceless\", \"longform\", \"clipping\", \"gaming-clips\", \"news\", \"sports\", \"ufc\", \"history\", \"animal-feast\"] },\n /** Pages, posts, forms, analytics — a published site with a crew behind it (`usenaive/web-blueprint`). */\n web: { templates: [\"publisher\"], default: \"publisher\" },\n};\n\n/** Resolved (a default may have filled it in), or the refusal's own words for the caller to raise. */\nexport type TemplateChoice = { ok: true; template: string | undefined } | { ok: false; message: string };\n\nconst list = (names: readonly string[]): string => names.join(\", \");\n\n/** The one place a `blueprint` / `template` pair is judged — `defineProject` and the CLI share it. */\nexport function chooseTemplate(blueprint: string | undefined, template: string | undefined): TemplateChoice {\n if (blueprint === undefined) {\n if (template === undefined) return { ok: true, template: undefined };\n return {\n ok: false,\n message: `template \"${template}\" names no blueprint — a template belongs to one, so add \\`blueprint: \"…\"\\` (${list(Object.keys(BLUEPRINTS))})`,\n };\n }\n const known = BLUEPRINTS[blueprint];\n if (known === undefined) {\n return { ok: false, message: `blueprint \"${blueprint}\" is not a blueprint — the blueprints are ${list(Object.keys(BLUEPRINTS))}` };\n }\n if (template === undefined) {\n if (known.default !== undefined) return { ok: true, template: known.default };\n return {\n ok: false,\n message: `blueprint \"${blueprint}\" needs a template — choose one of ${list(known.templates)}. Its crews spend money in different ways, so there is no default to fall back to.`,\n };\n }\n if (!known.templates.includes(template)) {\n return { ok: false, message: `template \"${template}\" is not a template of blueprint \"${blueprint}\" — its templates are ${list(known.templates)}` };\n }\n return { ok: true, template };\n}\n","/**\n * Load `naive.config.{ts,js,mjs,json}` from a directory. The critical property, learned the hard\n * way in the old system: \"the toolchain could not evaluate the file\" and \"the file loaded and its\n * config is wrong\" are DIFFERENT failures. The old loader was `catch { return null }`, so every\n * deliberate define-time refusal was reported as a missing install and exited 0. Here the two are\n * separate variants with the author's message carried verbatim.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { BlueprintRefusal, parseProject, type ProjectConfig } from \"./define\";\n\nexport const CONFIG_CANDIDATES = [\n \"naive.config.ts\",\n \"naive.config.js\",\n \"naive.config.mjs\",\n \"naive.config.json\",\n] as const;\n\nexport type ConfigLoad =\n | { ok: true; path: string; config: Readonly<ProjectConfig> }\n /** No candidate file exists in the directory. */\n | { ok: false; reason: \"not_found\"; message: string }\n /** The module system could not evaluate the file: the toolchain/deps are missing. */\n | { ok: false; reason: \"unloadable\"; message: string }\n /** The file loaded and its config is wrong — a refusal or a bad shape. Fix the config. */\n | { ok: false; reason: \"invalid\"; message: string };\n\n/**\n * A module-resolution failure, as opposed to the config refusing itself. Matched on the CODE, not\n * the message: a refusal is free to mention a package name in its prose.\n */\nfunction isMissingModule(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction validate(path: string, raw: unknown): ConfigLoad {\n try {\n return { ok: true, path, config: parseProject(raw) };\n } catch (error) {\n if (error instanceof BlueprintRefusal) return { ok: false, reason: \"invalid\", message: error.message };\n throw error;\n }\n}\n\nexport async function loadConfig(dir: string): Promise<ConfigLoad> {\n // Absolute from the start: the CLI's default `--dir` is `.`, and a relative path handed to\n // jiti is a bare specifier it cannot resolve (\"Cannot find module 'naive.config.ts'\").\n const path = CONFIG_CANDIDATES.map((name) => resolve(join(dir, name))).find(existsSync);\n if (!path) {\n return {\n ok: false,\n reason: \"not_found\",\n message: `no ${CONFIG_CANDIDATES.join(\" / \")} in ${dir}`,\n };\n }\n if (path.endsWith(\".json\")) {\n // A committed .json needs no toolchain, so a parse failure is only ever the file's own fault.\n try {\n return validate(path, JSON.parse(readFileSync(path, \"utf8\")));\n } catch (error) {\n if (error instanceof SyntaxError) return { ok: false, reason: \"invalid\", message: message(error) };\n throw error;\n }\n }\n let importFile: (specifier: string) => Promise<unknown>;\n try {\n const { createJiti } = await import(\"jiti\");\n importFile = createJiti(pathToFileURL(path).href).import;\n } catch (error) {\n return { ok: false, reason: \"unloadable\", message: message(error) };\n }\n let raw: unknown;\n try {\n const mod = await importFile(path);\n raw = (mod as { default?: unknown } | null)?.default ?? mod;\n } catch (error) {\n // The config's own imports failing to resolve is a toolchain problem; the config THROWING is\n // almost always a named define-time refusal, surfaced verbatim rather than replaced by a guess.\n return { ok: false, reason: isMissingModule(error) ? \"unloadable\" : \"invalid\", message: message(error) };\n }\n if (raw === null || typeof raw !== \"object\") {\n return {\n ok: false,\n reason: \"invalid\",\n message: `${path} evaluated to ${raw === undefined ? \"undefined\" : typeof raw}; it must \\`export default defineProject({...})\\``,\n };\n }\n return validate(path, raw);\n}\n","/**\n * Collect a `deploy_dir` into the file map `POST /v1/apps/{id}/deployments` takes: relative\n * POSIX path → base64 bytes (`canonical-spec §29.2`). Local state and secrets never ship:\n * `node_modules`, `.git`, `dist`-less build caches are the host's, `.env*` is the customer's.\n *\n * `contentHash` digests that map so `naive up` can send it as the deployment's `content_hash` and,\n * on the next apply, skip the upload when the newest live deployment carries the same one.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\n\nconst SKIP_DIRS = new Set([\"node_modules\", \".git\", \"dist\"]);\nconst MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n/**\n * A built tree, from either place one can be. A **directory** is the apply a person runs: a\n * checkout on their laptop or in CI. A **file map** is the apply the platform runs on their\n * behalf — the tree comes out of a published artifact's object-store entry (`canonical-spec §31.1`)\n * and there is no checkout anywhere, because a hosted run never clones a blueprint.\n */\nexport type FileSource = string | Record<string, string>;\n\n/**\n * ONE FILTER, ONE DIGEST, BOTH SOURCES — which is the whole of why the map arm exists rather than\n * the caller handing its map straight to `contentHash`.\n *\n * A published artifact's `content_hash` is compared against the newest deployment's to decide\n * whether to upload at all (§31.1), and the two sides of that comparison are collected in different\n * places: the deployment's from a directory here, the artifact's from a map on the server. If the\n * map arm skipped one exclusion or one size cap, the digests would differ for two trees that ship\n * the same bytes and every hosted install would re-upload, forever, with nothing to point at.\n */\nexport function collectFiles(source: FileSource): Record<string, string> {\n if (typeof source !== \"string\") return fromMap(source);\n const root = source;\n const files: Record<string, string> = {};\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n // `.env`, `.env.local`, `.env.production`, … — never upload secrets to a deploy.\n if (SKIP_DIRS.has(entry.name) || entry.name.startsWith(\".env\")) continue;\n const full = join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && statSync(full).size <= MAX_FILE_BYTES) {\n files[relative(root, full).split(sep).join(\"/\")] = readFileSync(full).toString(\"base64\");\n }\n }\n };\n walk(root);\n return files;\n}\n\n/**\n * The same rules read off the path instead of off `readdirSync`. A map's keys are already the POSIX\n * relative paths the walk produces, so an excluded file is one whose path has an excluded segment —\n * and the size cap is measured on the decoded bytes, which is what the walk's `statSync` measured.\n */\nfunction fromMap(map: Record<string, string>): Record<string, string> {\n const files: Record<string, string> = {};\n for (const [path, base64] of Object.entries(map)) {\n const segments = path.split(\"/\");\n if (segments.some((segment) => SKIP_DIRS.has(segment) || segment.startsWith(\".env\"))) continue;\n if (Buffer.from(base64, \"base64\").length > MAX_FILE_BYTES) continue;\n files[path] = base64;\n }\n return files;\n}\n\n/**\n * sha-256 over the files in path order, each as `path NUL byte-length NUL bytes`: the same tree\n * hashes the same from any walk order, and the length prefix keeps two trees from sharing an\n * encoding. Hex, so it travels as a plain string.\n */\nexport function contentHash(files: Record<string, string>): string {\n const hash = createHash(\"sha256\");\n for (const [path, base64] of Object.entries(files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n const bytes = Buffer.from(base64, \"base64\");\n hash.update(`${path}\\0${bytes.length}\\0`).update(bytes);\n }\n return hash.digest(\"hex\");\n}\n","/**\n * The reconciler behind `naive up` (`workstreams/10-blueprints.md §2`): a pure client of the\n * public REST API through the SDK — upsert-by-name over routes that are already idempotent. No\n * server-side diff engine, no manifest store; re-running is always safe because every resource is\n * keyed by its config name.\n *\n * Nothing is deleted by omission (ADR-0352): `removed` names are the only tombstones, with one\n * bounded exception — a declared agent's `schedules` are owned as a complete set (`agents.ts`).\n * Skills and identities live here; apps, agents and vaults each have their own module, sharing the\n * report vocabulary in `report.ts`.\n *\n * One thing here is not a reconcile: an agent this apply **created** that declares an `intake` is\n * sent its briefing as a started session (`agents.ts`, `canonical-spec §31.4`). It is what turns a\n * provisioned crew into a crew that has started working, and it is idempotent for the same reason\n * everything else here is — the agent is created exactly once. `tasks` (`tasks.ts`, §31.11) is the\n * reconcile that supersedes it: cards on the organization's board, keyed so a re-apply finds them,\n * woken by the API's tick rather than started here.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { AgentSchema, DeploymentSchema, VaultCredentialSchema, VaultSchema, type Agent, type BlueprintSelection, type Vault } from \"@vetta/core\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { openIntake, reconcileSchedules, upsertAgent, type Ids } from \"./agents\";\nimport { findApp, ownershipRefusal, upsertApp, PLATFORM_ENV, type Owner, type PlatformEnv } from \"./apps\";\nimport { BlueprintRefusal, type AgentDecl, type AppDecl, type IdentityDecl, type ProjectConfig, type SkillDecl } from \"./define\";\nimport { reconcileCards } from \"./reconcile-cards\";\nimport { reportLegal } from \"./reconcile-legal\";\nimport type { MigrationFile } from \"./migrations\";\nimport { absent, attempt, eachInFlight, line, listAll, tombstone, type ResourceAction, type ResourceReport } from \"./report\";\nimport { hasRoster, patchRoster } from \"./roster\";\nimport { seedTasks } from \"./tasks\";\nimport { upsertCredential, upsertVault } from \"./vaults\";\nimport { reconcileWallet, walletName } from \"./reconcile-wallet\";\n\nexport interface UpReport {\n dry_run: boolean;\n /** The machine, and the template within it whose crew this apply provisioned (`template.ts`). */\n blueprint?: string;\n template?: string;\n skills: ResourceReport[];\n identities: ResourceReport[];\n /** One line per vault, then one per declared credential named `<vault> / <key>`. */\n vaults: ResourceReport[];\n apps: ResourceReport[];\n agents: ResourceReport[];\n /** One line per declared cron and per pruned live row, named `<agent> @ <cron>`. */\n schedules: ResourceReport[];\n /**\n * One line per agent this apply **created** that declares an `intake` — the session that was\n * started, named by the agent, `id` the `ses_`. Empty on every later apply of the same crew: an\n * agent is created once, so it is briefed once (`agents.ts`).\n */\n intake: ResourceReport[];\n /**\n * One line per declared task, named by its key, `id` the `crd_` (`tasks.ts`, `canonical-spec\n * §31.11`): `created` on the apply that seeded the card, `unchanged` on every later one — the\n * card's key stands for the task. The board's owner is a line under `agents` like any member.\n */\n tasks: ResourceReport[];\n /**\n * Live rows this client could not parse, named and stepped over (`report.ts`). One legacy row\n * used to abort the whole apply before any write; it is now a line here and nothing else.\n */\n skipped: string[];\n /**\n * Declared agents and apps the operator's `select` left out (`canonical-spec §31.2`): not created,\n * not armed, not briefed, and — when one already exists — left exactly as it is. A choice, kept\n * apart from `skipped` (rows this client could not read) and from a `refused` line (an attempt).\n */\n deselected: string[];\n}\n\nexport interface UpOptions {\n /** Plan only: reads happen, writes do not, and the report says what apply would do. */\n dry_run?: boolean;\n /** Base directory `deploy_dir` is resolved against — the config file's directory. */\n dir?: string;\n /**\n * `naive up --adopt`: take every app this run touches whose row names another project, or none\n * (ADR-0375). Off by default — adopting by default is what overwrote a live deployment.\n */\n adopt?: boolean;\n /**\n * The built trees, by app name, for an apply that runs where there is no checkout: the platform\n * applying a published artifact on an operator's behalf (`canonical-spec §31.1`). The bytes come\n * out of the artifact's object-store entry, in the same file map `deploy_dir` would have been\n * collected into — which is why `collectFiles` takes both and there is one digest (`files.ts`).\n *\n * Present ⇒ the disk is never read for an app, and an app whose tree is not in the map is refused\n * by name rather than deployed empty. Absent ⇒ `dir` + `deploy_dir`, exactly as before.\n */\n trees?: Record<string, Record<string, string>>;\n /**\n * Why a declared app is absent from `trees`, by app name — an object-store read that failed\n * rather than an object that was never uploaded. Both come out of `builtTree` as one refusal;\n * only the caller that did the reading can tell them apart, so only it can say (`apps.ts`).\n */\n tree_errors?: Record<string, string>;\n /**\n * core-gaps: U8-database — each app's `migrations`, by app name, as the publisher shipped them on\n * its built tree (`canonical-spec §31.1`); read only when `trees` is present. An app that declares\n * migrations and is absent here is refused by name (`migrations.ts`).\n */\n migrations?: Record<string, MigrationFile[]>;\n /**\n * A skill's bytes by slug, for a hosted apply of a published declaration that carries them\n * inline (`canonical-spec §42.8`). A hosted skill absent from this map is still refused by name.\n */\n skills?: Record<string, string>;\n /**\n * What an app's `{ from_env }` reads (`apps.ts`). The process's own environment by default —\n * the author's shell, which is the whole point of `from_env` on a laptop. A hosted apply has no\n * shell and passes the operator's **answers** instead (`canonical-spec §31.2`): the same\n * declaration, resolved against the only environment that apply has.\n */\n env?: Record<string, string | undefined>;\n /**\n * THE PLATFORM ENVIRONMENT (`canonical-spec §29.7`) — what the platform itself provides an app,\n * read BEFORE `env` and written whether or not the declaration names it.\n *\n * Present only on a hosted apply, and that is the whole of the local/hosted difference: `naive up`\n * from a checkout passes none, reads the author's shell, and behaves exactly as it always has.\n *\n * `NAIVE_IDENTITY_ID` is filled in here rather than by the caller, because the id does not exist\n * until this run has created the identity — identities are upserted before apps for the same\n * reason agents reference them by name.\n */\n platform?: PlatformEnv;\n /**\n * Which of the declared crew to provision, by name (§31.2). Omitted means everything, which is what\n * every apply before this option did. A name the declaration lacks, or a `required` one left out,\n * is a `BlueprintRefusal` before anything is read — the one thrown escape `up` has, because it is\n * the caller's input that is wrong and not a resource that could not be made.\n */\n select?: BlueprintSelection;\n /**\n * The install this crew belongs to — what a template agent's `metadata.project` names (§31.8).\n * Defaults to `config.name`, which is the install `naive up` files under. A hosted apply files\n * under the customer's own `project` and passes it here, so the runtime's lookup of the latest\n * applied install lands on the row that exists.\n */\n project?: string;\n /**\n * An install that shares the organization by its own names (ADR-1104, `scoped.ts`): its crew is\n * filed under `project` rather than the template, and an identity is stamped with `project` and\n * adopted only when it already carries it — another project's persona, or one nobody stamped, is\n * refused rather than taken. Absent is every apply before that rule, exactly as it was.\n */\n isolated?: boolean;\n /**\n * What dials an app's own address before its crew is briefed (`awaitServing`). The platform's\n * `fetch` by default; a test hands in a fake. It is NOT the client's `fetch`, which on a hosted\n * apply loops back into the API and never leaves the isolate.\n */\n probe?: typeof globalThis.fetch;\n}\n\n/** Bounded: an address still not answering after this is briefed anyway, and the turn says so. */\nconst SERVING_TRIES = 90;\nconst SERVING_MS = 2_000;\n\n/**\n * WAIT UNTIL EVERY APP THE CREW REACHES ANSWERS ON ITS OWN ADDRESS.\n *\n * A deployment reads `ready` — and the apply's `settleDeploy` returns — a moment before the host\n * serves the lasting hostname. Measured on staging: an install whose seven intakes opened 21 s\n * after the deploy row was written briefed six agents whose first turn found no `dashboard.*`\n * tools at all and one, 1 s later, that found them and filed fifteen leads. The runtime resolves\n * an app's MCP tools by dialing `url + mcp` at the turn (§29.5), so an intake that opens before\n * the address answers is a first turn spent asking for tools the declaration already granted.\n * A 401 or a 405 to a bare `/mcp` GET is the endpoint answering — reachability is the question,\n * not authorization. A 404 is not: the host answers 404 for an alias it has not propagated yet\n * (measured on staging, a second run — the wait returned at once and every first turn was again\n * tool-less), so it is waited out like a refused connection. Nor is a 5xx: a fullstack app's\n * database lands after its first build and the host re-ships it, and until that re-ship serves,\n * `/mcp` answers 503 on a bare GET (the dashboards open their store before the 405) — measured\n * on staging as a first turn told \"tool not found\" for every tool the declaration granted. The\n * bound is three minutes because a re-ship is a build, not an alias flip.\n */\nasync function awaitServing(addresses: readonly string[], probe: typeof globalThis.fetch): Promise<void> {\n await Promise.all(\n addresses.map(async (address) => {\n for (let poll = 0; poll < SERVING_TRIES; poll++) {\n try {\n const { status } = await probe(address, { method: \"GET\" });\n if (status < 500 && status !== 404) return;\n } catch {\n // Not serving yet: a refused connection or an unresolved name is the state being waited out.\n }\n await new Promise((resolve) => setTimeout(resolve, SERVING_MS));\n }\n }),\n );\n}\n\n/** The crew this apply takes (`UpOptions.select`), and the names it leaves out. */\nexport function selectCrew(\n config: Readonly<ProjectConfig>,\n select: BlueprintSelection | undefined,\n): { apps: readonly AppDecl[]; agents: readonly AgentDecl[]; deselected: string[] } {\n if (select === undefined) return { apps: config.apps, agents: config.agents, deselected: [] };\n const named = (kind: \"app\" | \"agent\", names: readonly string[]) => names.map((name) => `${kind} \"${name}\"`);\n const unknown = [\n ...named(\"app\", select.apps.filter((name) => !config.apps.some((decl) => decl.name === name))),\n ...named(\"agent\", select.agents.filter((name) => !config.agents.some((decl) => decl.name === name))),\n ];\n if (unknown.length > 0) {\n throw new BlueprintRefusal(`selection names ${unknown.join(\", \")}, which this declaration does not declare`);\n }\n const apps = config.apps.filter((decl) => select.apps.includes(decl.name));\n const agents = config.agents.filter((decl) => select.agents.includes(decl.name));\n const missing = [\n ...named(\"app\", config.apps.filter((decl) => decl.required === true && !apps.includes(decl)).map((decl) => decl.name)),\n ...named(\"agent\", config.agents.filter((decl) => decl.required === true && !agents.includes(decl)).map((decl) => decl.name)),\n ];\n if (missing.length > 0) {\n throw new BlueprintRefusal(\n `selection leaves out ${missing.join(\", \")}, which this template requires — ${missing.length === 1 ? \"it\" : \"they\"} cannot be deselected`,\n );\n }\n const deselected = [\n ...config.apps.filter((decl) => !apps.includes(decl)).map((decl) => decl.name),\n ...config.agents.filter((decl) => !agents.includes(decl)).map((decl) => decl.name),\n ];\n return { apps, agents, deselected };\n}\n\n/**\n * The one identity an app runs as, when the declaration declares exactly one (§29.7). A declaration\n * with several has not said which, and handing an app the wrong persona would give it the wrong\n * connected accounts; a declaration with none has no answer at all. Both live blueprints declare one.\n */\nfunction identityEnv(config: Readonly<ProjectConfig>, ids: Map<string, string>): Record<string, string> {\n if (config.identities.length !== 1) return {};\n const id = ids.get(config.identities[0]!.name);\n return id === undefined ? {} : { [PLATFORM_ENV.identity_id]: id };\n}\n\n/**\n * Skills are content-addressed (§13): the server mints a version only when the bytes differ, so\n * the local digest against the newest version says `unchanged` vs `updated` without a write —\n * which is also what makes the dry-run line exact.\n */\nasync function upsertSkill(\n client: VettaClient,\n decl: SkillDecl,\n opts: { dryRun: boolean; dir: string; hosted: boolean; skills: Record<string, string> },\n): Promise<ResourceReport> {\n // A HOSTED APPLY HAS NO CHECKOUT, so there is no file to read and `resolve(\"\", decl.file)` would\n // fail with an ENOENT naming a path that exists on nobody's disk. `trees` carries an app's bytes\n // and only a creator's published declaration carries a skill's inline (§13, §31.1, §42.8), so the\n // honest answer otherwise is a refusal that says which published thing is missing rather than a\n // filesystem error the operator cannot act on.\n const inline = opts.skills[decl.slug];\n if (opts.hosted && inline === undefined) {\n throw new Error(\n `skill \"${decl.slug}\" is declared as the file \"${decl.file}\", and a hosted apply has no ` +\n `checkout to read it from. Push it with \\`naive up\\` from a clone, or publish it as part of the blueprint.`,\n );\n }\n const content = inline ?? readFileSync(resolve(opts.dir, decl.file), \"utf8\");\n const sha256 = createHash(\"sha256\").update(content).digest(\"hex\");\n const current = await absent(client.skills.get(decl.slug));\n const latest = current ? (await client.skills.listVersions(decl.slug, { limit: 1 })).data[0] : undefined;\n const action: ResourceAction = !current ? \"created\" : latest?.sha256 === sha256 ? \"unchanged\" : \"updated\";\n if (action === \"unchanged\" || opts.dryRun) {\n return { name: decl.slug, action, ...(current ? { id: current.id } : {}) };\n }\n const pushed = await client.skills.push({ slug: decl.slug, content, sha256 });\n return { name: decl.slug, action, id: pushed.id };\n}\n\n/** `owner` is the isolated install's project (`UpOptions.isolated`); `undefined` adopts by name, as ever. */\nasync function upsertIdentity(\n client: VettaClient,\n decl: IdentityDecl,\n dryRun: boolean,\n identityIds: Map<string, string>,\n owner: string | undefined,\n): Promise<ResourceReport> {\n const current = await absent(client.identities.get(decl.name));\n if (!current) {\n if (dryRun) return { name: decl.name, action: \"created\" };\n const created = await client.identities.create({\n name: decl.name,\n ...(decl.description !== undefined ? { description: decl.description } : {}),\n ...(owner !== undefined ? { metadata: { project: owner } } : {}),\n });\n identityIds.set(decl.name, created.id);\n return { name: decl.name, action: \"created\", id: created.id };\n }\n const held = typeof current.metadata[\"project\"] === \"string\" ? current.metadata[\"project\"] : null;\n if (owner !== undefined && held !== owner) {\n return { name: decl.name, action: \"refused\", id: current.id, reason: ownershipRefusal(decl.name, owner, held, \"identity\") };\n }\n identityIds.set(decl.name, current.id);\n const drifted = decl.description !== undefined && decl.description !== current.description;\n if (drifted && !dryRun) await client.identities.update(current.id, { description: decl.description ?? null });\n return { name: decl.name, action: drifted ? \"updated\" : \"unchanged\", id: current.id };\n}\n\n/**\n * The `removed` tombstones, agents first so an agent never outlives an app it pointed at, and a\n * vault before its identity: deleting the vault is what hard-deletes the credentials (§23).\n */\nasync function applyRemoved(\n client: VettaClient,\n removed: ProjectConfig[\"removed\"],\n live: { agents: Agent[]; vaults: Vault[] },\n owner: Owner,\n report: UpReport,\n): Promise<void> {\n const dryRun = report.dry_run;\n for (const name of removed.agents) {\n const current = live.agents.find((agent) => agent.name === name);\n await attempt(report.agents, name, () => tombstone(name, current, (id) => client.agents.delete(id), dryRun));\n }\n // The same predicate as the upsert (ADR-0375): a delete tears down the hosting project and the\n // app database, so deleting another project's app is worse than overwriting it.\n for (const name of removed.apps) {\n await attempt(report.apps, name, async () => {\n const current = await findApp(client, name, owner.skipped);\n if (current !== null && current.project !== owner.project && !owner.adopt) {\n return { name, action: \"refused\", id: current.id, reason: ownershipRefusal(name, owner.project, current.project) };\n }\n return tombstone(name, current, (id) => client.apps.delete(id), dryRun);\n });\n }\n for (const slug of removed.skills) {\n await attempt(report.skills, slug, async () =>\n tombstone(slug, await absent(client.skills.get(slug)), (id) => client.skills.delete(id), dryRun),\n );\n }\n for (const name of removed.vaults) {\n const current = live.vaults.find((vault) => vault.display_name === name);\n await attempt(report.vaults, name, () => tombstone(name, current, (id) => client.vaults.delete(id), dryRun));\n }\n for (const name of removed.identities) {\n await attempt(report.identities, name, async () =>\n tombstone(name, await absent(client.identities.get(name)), (id) => client.identities.delete(id), dryRun),\n );\n }\n}\n\n/** The crew this apply provisioned, named in the report whenever the config declares it. */\nconst applied = (config: Readonly<ProjectConfig>) => ({\n ...(config.blueprint !== undefined ? { blueprint: config.blueprint } : {}),\n ...(config.template !== undefined ? { template: config.template } : {}),\n});\n\n/**\n * The switch rule (ADR-0389): a template switch WIDENS and never narrows. An agent the previous\n * template declared and this one does not is named in the report and left exactly as it is — the\n * same thing that already happens to a resource dropped from the config, said out loud so the\n * operator can see what the old crew left behind and retire it themselves with `removed`.\n */\nfunction reportKept(config: Readonly<ProjectConfig>, live: Agent[], into: ResourceReport[]): void {\n const by = config.template === undefined ? \"this template\" : `template \"${config.template}\"`;\n for (const name of config.kept.agents) {\n const current = live.find((agent) => agent.name === name);\n if (current !== undefined) into.push({ name, action: \"unchanged\", id: current.id, reason: `not declared by ${by}; kept, never deleted` });\n }\n}\n\n/**\n * Whether the agent's toolset grants a tool this app serves. An app's MCP tools reach the turn as\n * `<app>.<tool>` (§29.5) and only while the app is live, so a first message that sends the agent to\n * an app this run declined to create would only be the agent asking for tools that do not exist.\n */\nfunction reaches(decl: AgentDecl, app: string): boolean {\n return Object.entries(decl.tools?.configs ?? {}).some(\n ([name, one]) => name.startsWith(`${app}.`) && one.enabled && one.permission !== \"deny\",\n );\n}\n\n/** Plan → apply → report. Every refusal is one line in the report, never a thrown escape. */\nexport async function up(\n config: Readonly<ProjectConfig>,\n client: VettaClient,\n opts: UpOptions = {},\n): Promise<UpReport> {\n const dryRun = opts.dry_run ?? false;\n const dir = opts.dir ?? process.cwd();\n const ids: Ids = { apps: new Map(), identities: new Map() };\n // Judged before the first read: a selection that is wrong is the caller's to fix, not a report line.\n const taken = selectCrew(config, opts.select);\n const report: UpReport = { dry_run: dryRun, ...applied(config), skills: [], identities: [], vaults: [], apps: [], agents: [], schedules: [], intake: [], tasks: [], skipped: [], deselected: taken.deselected };\n // The stamp every app in this run is judged against is the config's own name (ADR-0375).\n const owner: Owner = { project: config.name, adopt: opts.adopt ?? false, skipped: report.skipped };\n const project = opts.project ?? config.name;\n const isolated = opts.isolated === true ? project : undefined;\n // Skills and identities first: agents reference both by name.\n // `trees` is present exactly when this apply runs where there is no checkout (`UpOptions`).\n const hosted = opts.trees !== undefined;\n for (const decl of config.skills) {\n await attempt(report.skills, decl.slug, () => upsertSkill(client, decl, { dryRun, dir, hosted, skills: opts.skills ?? {} }));\n }\n for (const decl of config.identities) {\n await attempt(report.identities, decl.name, () => upsertIdentity(client, decl, dryRun, ids.identities, isolated));\n const identityId = ids.identities.get(decl.name);\n report.identities.push(...(await reportLegal(client, decl.legal ?? [], identityId, report.skipped)));\n for (const wallet of decl.wallet === undefined ? [] : Array.isArray(decl.wallet) ? decl.wallet : [decl.wallet]) {\n await attempt(report.identities, walletName(decl.name, wallet), () =>\n reconcileWallet(client, { name: decl.name, id: identityId }, wallet, dryRun),\n );\n }\n await reconcileCards(client, decl.name, identityId, decl.cards ?? [], dryRun, report.identities, report.skipped);\n }\n // Vaults have no by-name lookup; one list serves every upsert and tombstone below.\n const vaults =\n config.vaults.length > 0 || config.removed.vaults.length > 0\n ? await listAll(client.config, \"/v1/vaults\", VaultSchema, report.skipped)\n : [];\n for (const decl of config.vaults) {\n const line = await attempt(report.vaults, decl.name, () => upsertVault(client, decl, vaults, ids.identities, dryRun));\n const vaultId = line.action === \"unchanged\" ? line.id : undefined;\n const rows =\n vaultId === undefined\n ? []\n : await listAll(client.config, `/v1/vaults/${vaultId}/credentials`, VaultCredentialSchema, report.skipped);\n for (const cred of decl.credentials) {\n await attempt(report.vaults, `${decl.name} / ${cred.key}`, () =>\n upsertCredential(client, line, cred, rows, dryRun, opts.env ?? process.env),\n );\n }\n }\n // After the identities, because one of the platform's known values is an identity this run made.\n // The install's project is another: it is the row the app's `/api/context` looks up, and a hosted\n // apply files it under the customer's slug, not the declaration's name.\n const platform = opts.platform && {\n ...opts.platform,\n known: {\n ...opts.platform.known,\n [PLATFORM_ENV.project]: project,\n ...identityEnv(config, ids.identities),\n },\n };\n // Together, filed in declaration order: one app's create, secrets and build wait share nothing\n // with the next app's, and a hosted install was paying each build's wait once per app.\n report.apps.push(\n ...(await eachInFlight(taken.apps, (decl) =>\n line(\n decl.name,\n () =>\n upsertApp(\n client,\n decl,\n {\n ...owner,\n dryRun,\n dir,\n trees: opts.trees,\n tree_errors: opts.tree_errors,\n migrations: opts.migrations,\n env: opts.env ?? process.env,\n platform,\n },\n ids.apps,\n ),\n // The app's id is recorded the moment it exists — before its secrets and deploy — so a\n // failure in that upload reports `refused` naming the created app, not one the operator\n // cannot find. A pre-create refusal (an unset `from_env`, a missing tree) has set nothing.\n () => ids.apps.get(decl.name),\n ),\n )),\n );\n const existing =\n taken.agents.length > 0 || config.removed.agents.length > 0 || config.kept.agents.length > 0 || config.tasks.length > 0\n ? await listAll(client.config, \"/v1/agents\", AgentSchema, report.skipped)\n : [];\n const deployments = taken.agents.some((decl) => decl.schedules !== undefined)\n ? await listAll(client.config, \"/v1/deployments\", DeploymentSchema, report.skipped)\n : [];\n /**\n * The apps THIS project provisioned, which is what its agents may reach — see `upsertAgent`.\n * `undefined` when the declaration declares none at all, because scoping an agent to an empty\n * list would be a removal by omission; empty when every declared app was refused, because an\n * agent must not be handed tool names for an app this run declined to create.\n */\n const scoped = config.apps.length > 0 ? [...ids.apps.values()] : undefined;\n // Each agent with its own timers, the crew together: an agent is keyed by its name and its\n // schedules by its id, so nothing one member writes is read by the next.\n const crew = await eachInFlight(taken.agents, async (decl) => {\n const of = { project, ...applied(config), adopt: opts.adopt ?? false, ...(isolated === undefined ? {} : { group: project }) };\n const agent = await line(decl.name, () => upsertAgent(client, decl, existing, ids, dryRun, scoped, of));\n const schedules: ResourceReport[] = [];\n if (decl.schedules !== undefined) {\n await reconcileSchedules(client, agent, decl.schedules, deployments, ids.identities, dryRun, schedules);\n }\n return { decl, agent, schedules };\n });\n const briefed: [ResourceReport, NonNullable<AgentDecl[\"intake\"]>][] = [];\n // A dry run creates no app, so it has nothing to hold against a briefing.\n // Every app the DECLARATION names, not the ones the selection kept: a deselected app is as\n // absent from this run as a refused one, and `reaches()` must be asked about it too (§31.4).\n const unbuilt = dryRun ? [] : config.apps.map((decl) => decl.name).filter((name) => !ids.apps.has(name));\n for (const { decl, agent, schedules } of crew) {\n report.agents.push(agent);\n report.schedules.push(...schedules);\n // `created` is the whole condition (§31.4): the agent that already existed was briefed on the\n // apply that made it, and a refused one has nothing to brief.\n if (decl.intake === undefined || agent.action !== \"created\") continue;\n const needs = unbuilt.find((app) => reaches(decl, app));\n if (needs === undefined) briefed.push([agent, decl.intake]);\n else report.intake.push({ name: decl.name, action: \"refused\", reason: `needs app \"${needs}\", which was not provisioned in this run` });\n }\n // Pass two (§31.6): every agent of the declaration now has an id, so a roster's names can become them.\n const agentIds = new Map(existing.map((agent) => [agent.name, agent.id]));\n for (const line of report.agents) if (line.id !== undefined) agentIds.set(line.name, line.id);\n for (const decl of config.agents) {\n if (hasRoster(decl.multiagent)) await patchRoster(client, decl, decl.multiagent, existing, agentIds, dryRun, report.agents);\n }\n reportKept(config, existing, report.agents);\n // The crew has its ids and its owner's board can seat it (§31.11); the cards it seeds are woken by\n // the API's tick, so an intake below still finds every card of this apply already on the board.\n if (config.tasks.length > 0) await seedTasks(client, config, existing, report.agents, dryRun, report.tasks, report.skipped);\n await applyRemoved(client, config.removed, { agents: existing, vaults }, owner, report);\n // Last, after every write: an intake is the only thing `up` does that makes an agent act, and a\n // crew member that delegates (§28) or reaches for an app must find the rest of the apply landed —\n // including the app's own MCP endpoint answering, which `ready` alone does not promise.\n if (briefed.length > 0 && !dryRun) {\n const serving = taken.apps.flatMap((decl) => {\n const url = report.apps.find((one) => one.name === decl.name)?.url;\n return decl.mcp !== undefined && typeof url === \"string\" ? [url + decl.mcp] : [];\n });\n await awaitServing(serving, opts.probe ?? globalThis.fetch);\n }\n report.intake.push(\n ...(await eachInFlight(briefed, ([agent, decl]) => line(agent.name, () => openIntake(client, agent, decl, dryRun)))),\n );\n return report;\n}\n","/**\n * Apps in `naive up`: upsert by `GET /v1/apps?name=` (§29.2), `env` written as write-only secrets\n * only when the live `value_hash` differs from the local one (ADR-0354, ADR-0357), and the\n * `deploy_dir` shipped only when its content hash differs from the newest live deployment's\n * (ADR-0357). Live secret names the config does not declare are reported, never deleted\n * (ADR-0352). `mcp` is patched on drift, absent meaning `null` (§29.5); the platform mints the\n * app's `VETTA_MCP_TOKEN` itself, so nothing here ever holds that token.\n *\n * A hosted apply also arrives with a PLATFORM ENVIRONMENT (`PlatformEnv`, §29.7) — the base URL, the\n * identity the install runs as, and a scoped key it will mint for an app that asks. That layer is\n * read before `{ from_env }`'s own environment, and a declaration may ask for a value nobody has\n * with `{ generate: true }`. Both are provisioned ONCE per app, because a value the platform invents\n * has no stable digest and rewriting it every apply would rotate a live credential.\n *\n * An app also records the project that made it (ADR-0375), and that stamp is compared before any\n * write: a name this project does not own is refused rather than adopted, which is what standing\n * up a second blueprint did to the first one's live deployment.\n */\nimport type { AppCreate, VettaClient } from \"@usenaive-sdk/vetta\";\nimport { AppSchema, type App } from \"@vetta/core\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { resolve } from \"node:path\";\n// core-gaps: storage-stock\nimport { applyBuckets } from \"./buckets\";\nimport type { AppDecl } from \"./define\";\nimport { collectFiles, contentHash } from \"./files\";\n// core-gaps: U8-database\nimport { applyMigrations, declaredMigrations, type MigrationFile } from \"./migrations\";\nimport { eachInFlight, listAll, type ResourceAction, type ResourceReport } from \"./report\";\n\n/** What every app in one run is judged against: the config's own `name`, and `naive up --adopt`. */\nexport interface Owner {\n project: string;\n adopt: boolean;\n /** Rows the engine could not read (`report.ts`), collected rather than thrown. */\n skipped: string[];\n}\n\n/** `GET /v1/apps?name=` — the by-name lookup that makes app upsert idempotent (§29.2). */\nexport async function findApp(client: VettaClient, name: string, skipped: string[]): Promise<App | null> {\n const rows = await listAll(client.config, \"/v1/apps\", AppSchema, skipped, { name });\n return rows.find((app) => app.name === name) ?? null;\n}\n\n/**\n * ADR-0375's refusal, and the one place its wording lives — upserts and `removed` tombstones read\n * the same predicate, because deleting another project's app is worse than overwriting it.\n */\nexport function ownershipRefusal(name: string, project: string, owner: string | null, kind: \"app\" | \"agent\" | \"identity\" = \"app\"): string {\n const held = owner === null ? \"no project (it was created outside a blueprint)\" : `project \"${owner}\"`;\n const verb = owner === null ? \"take\" : \"transfer\";\n return `${kind} \"${name}\" is owned by ${held}; this project is \"${project}\". Rename the ${kind} in your config, or re-run \\`naive up --adopt\\` to ${verb} it.`;\n}\n\n/**\n * `POST /v1/apps` is the ensure, and the only door provenance moves through (§29.2): a create\n * stamps `project`, and `adopt: true` on a name another project owns transfers the stamp. Widened\n * over the SDK's `AppCreate`, which does not name the two fields yet; when it does, the\n * intersection is redundant and this alias collapses to `AppCreate`.\n */\ntype AppEnsure = AppCreate & { project: string; adopt?: boolean };\nconst ensureApp = (client: VettaClient, body: AppEnsure) => client.apps.create(body);\n\n/** The platform environment's variable names (`canonical-spec §29.7`) — fixed, never inferred. */\nexport const PLATFORM_ENV = {\n /** The base URL of the API this apply ran through. */\n api_url: \"NAIVE_API_URL\",\n /** The identity the install runs as, when the declaration declares exactly one. */\n identity_id: \"NAIVE_IDENTITY_ID\",\n /** The install's `project` — the row the app's own context lookup lands on (§31.8). */\n project: \"NAIVE_PROJECT\",\n /** The base URL of the Studio that installed the app, so it can send a signed-out visitor back. */\n studio_url: \"NAIVE_STUDIO_URL\",\n /** The app's own `app_…` id — the one known value learnt from the row, not from the apply. */\n app_id: \"NAIVE_APP_ID\",\n /** A scoped organization API key minted for the app that asks for it. */\n api_key: \"NAIVE_API_KEY\",\n} as const;\n\n/** The one generated name a *person* types, so it is shaped for a person (§29.7, ADR-0656). */\nconst DASHBOARD_PASSWORD = \"DASHBOARD_PASSWORD\";\n\n/**\n * WHAT THE PLATFORM PROVIDES A HOSTED APPLY, AND THE ONE DISTINCTION THAT MATTERS\n * (`canonical-spec §29.7`).\n *\n * Absent on a laptop apply, which reads the author's shell and nothing else — the hosted path gains\n * a layer, the local path does not lose one.\n *\n * **What the platform KNOWS it always tells the app; what the platform must INVENT it invents only\n * on request, and only once.** That is not a stylistic split. A known value has a stable digest, so\n * the `value_hash` compare that makes `naive up` idempotent (§29.2) can say `unchanged` about it and\n * re-asserting it every apply costs nothing. An invented one never matches its own previous digest,\n * so re-inventing it every apply would rotate a live credential under a build that still holds the\n * old one — and, for a minted key, leave one dead `api_key` row behind per apply.\n */\nexport interface PlatformEnv {\n /**\n * Values the platform knows. Written to every app this apply deploys that declares an `env` —\n * whether or not the declaration names them, which is the `VETTA_MCP_TOKEN` precedent (§29.2) —\n * and read FIRST by a `{ from_env }` that does name them.\n */\n known: Record<string, string>;\n /**\n * Values the platform must invent, by variable name, given the app that asked. Called at most\n * once per app, and only when that app holds no secret of that name.\n */\n minted?: Record<string, (app: string) => Promise<string>>;\n}\n\n/**\n * One declared variable, resolved as far as it can be BEFORE the app is read.\n *\n * The split is what keeps the refusal where it has always been. Anything genuinely missing — a\n * `{ from_env }` no layer supplies — throws out of `planEnv`, before the first request, so an app is\n * never half-written. Only the *invented* values wait, because whether to invent one is a question\n * about the live app that this apply has not asked yet.\n */\ninterface Planned {\n name: string;\n /** Known now: a literal, an answer, the author's shell, or a value the platform holds. */\n value?: string;\n /** Invented, and therefore provisioned once: a generated secret or a minted key. */\n invent?: () => Promise<string>;\n}\n\n/**\n * `{ from_env }` reads the environment the apply is running in, so a value never sits in the config\n * file. An unset variable refuses the app before any write — naming the variable, never a value.\n *\n * WHICH ENVIRONMENT depends on where the apply runs, and there are two. On a laptop or in CI it is\n * the author's shell, which is what `opts.env` defaults to. A hosted apply has no shell: it is\n * given the **platform environment** (`PlatformEnv`, §29.7) layered over the **answers** the\n * operator typed into the setup questions before anything was provisioned (§31.2). Platform first,\n * answers second, refuse third — because none of `NAIVE_API_KEY`, `DASHBOARD_TOKEN`,\n * `NAIVE_API_URL` or `NAIVE_IDENTITY_ID` is a thing an operator has to give, and asking for one is\n * how a hosted install came to provision a crew and never its dashboard.\n */\nfunction planEnv(decl: AppDecl, opts: AppOptions): Planned[] {\n if (decl.env === undefined) return [];\n const plan = new Map<string, Planned>();\n for (const [name, value] of Object.entries(decl.env)) {\n if (typeof value === \"string\") {\n plan.set(name, { name, value });\n continue;\n }\n if (\"generate\" in value) {\n plan.set(name, { name, invent: async () => (name === DASHBOARD_PASSWORD ? generatedPassword() : generatedSecret()) });\n continue;\n }\n const known = opts.platform?.known[value.from_env];\n const mint = opts.platform?.minted?.[value.from_env];\n if (known !== undefined) plan.set(name, { name, value: known });\n else if (mint !== undefined) plan.set(name, { name, invent: () => mint(decl.name) });\n else {\n const local = opts.env[value.from_env];\n if (local === undefined) throw new Error(`env ${name} reads local variable ${value.from_env}, which is not set`);\n plan.set(name, { name, value: local });\n }\n }\n // Last, so a known platform value wins over a literal or an answer of the same name: it is the\n // address of the API this apply just provisioned against, and a declaration that disagrees points\n // the app at a platform that is not holding its agents.\n for (const [name, value] of Object.entries(opts.platform?.known ?? {})) plan.set(name, { name, value });\n return [...plan.values()];\n}\n\n/**\n * The plan, made real. `held` is the set of secret names the live app already carries — empty for an\n * app about to be created — and it is the whole of the provision-once rule: an invented value the\n * app already holds is not re-invented and not written, so it is not rotated under a running build.\n * Rotation is by hand (`DELETE …/secrets/{name}`, then apply again), the §29.2 `mcp` idiom.\n *\n * `--dry-run` must not mint a key or generate a token — planning is a read. So an invented value the\n * app does not already hold is NAMED (`unmade`) and not made, and the plan line still says it would\n * be set.\n */\nasync function materialize(\n plan: Planned[],\n held: ReadonlySet<string>,\n dryRun: boolean,\n): Promise<{ values: Record<string, string>; unmade: string[] }> {\n const values: Record<string, string> = {};\n const unmade: string[] = [];\n for (const one of plan) {\n if (one.value !== undefined) values[one.name] = one.value;\n else if (held.has(one.name)) continue;\n else if (dryRun) unmade.push(one.name);\n else values[one.name] = await invent(one);\n }\n return { values, unmade };\n}\n\n/**\n * A value the platform could not invent refuses this app **by variable name**, exactly as an unset\n * one does. A mint is a real request that can be turned down — a caller that does not hold the\n * scopes the key carries does not get one minted on its behalf — and a missing scope on its own\n * does not tell an operator which of their app's variables went without.\n */\nasync function invent(one: Planned): Promise<string> {\n try {\n return await one.invent!();\n } catch (cause) {\n throw new Error(\n `env ${one.name} is provisioned by the platform, and could not be: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n}\n\n/** A value nobody has: 256 bits, URL-safe, no alphabet an app secret or a header would mangle. */\nexport const generatedSecret = (): string => randomBytes(32).toString(\"base64url\");\n\n/** Lowercase and digits with nothing a person misreads: no `0`/`o`, no `1`/`l`/`i`. */\nconst PASSWORD_ALPHABET = \"abcdefghjkmnpqrstuvwxyz23456789\";\nconst PASSWORD_GROUPS = 4;\nconst PASSWORD_GROUP_LENGTH = 4;\n\n/**\n * `kq7m-x2rt-8bvn-pz4h`: four groups of four from a 31-letter alphabet, 16·log2(31) ≈ 79 bits. Each\n * character is drawn by rejection sampling so the alphabet is used evenly — a modulo over 256 would\n * not be.\n */\nexport function generatedPassword(): string {\n const limit = 256 - (256 % PASSWORD_ALPHABET.length);\n const groups: string[] = [];\n let group = \"\";\n while (groups.length < PASSWORD_GROUPS) {\n for (const byte of randomBytes(PASSWORD_GROUPS * PASSWORD_GROUP_LENGTH * 2)) {\n if (byte >= limit) continue;\n group += PASSWORD_ALPHABET[byte % PASSWORD_ALPHABET.length];\n if (group.length === PASSWORD_GROUP_LENGTH) {\n groups.push(group);\n group = \"\";\n if (groups.length === PASSWORD_GROUPS) break;\n }\n }\n }\n return groups.join(\"-\");\n}\n\n/**\n * `NAIVE_APP_ID` is known, but only once the row exists — so it joins the environment here, after\n * the create or the read, rather than in `planEnv`. Written on the same terms as the other known\n * values: every hosted app that declares an `env`, named or not.\n */\nfunction withAppId(env: Record<string, string>, decl: AppDecl, opts: AppOptions, id: string): Record<string, string> {\n if (decl.env === undefined || opts.platform === undefined) return env;\n return { ...env, [PLATFORM_ENV.app_id]: id };\n}\n\n/** An app about to be created holds nothing. */\nconst EMPTY: ReadonlySet<string> = new Set();\n\n/**\n * The digest sent as the secret's `value_hash` (§29.2): sha-256 over `name NUL value`, hex. A\n * fingerprint, not the value — it lets the next apply see \"the value I hold is the value I last\n * wrote\" without any route ever returning one.\n */\nfunction secretHash(name: string, value: string): string {\n return createHash(\"sha256\").update(`${name}\\0`).update(value).digest(\"hex\");\n}\n\ninterface Tree {\n files: Record<string, string>;\n hash: string;\n}\n\n/**\n * The tree as it would ship, hashed once so it can be held against the newest live deployment.\n *\n * Two sources, one function, because there are two places an apply runs from (`files.ts`). A\n * **directory** is the apply a person runs on a checkout. A **built tree** is the apply the\n * platform runs on their behalf: the bytes come out of a published artifact and there is no\n * checkout anywhere, so `opts.trees` is present and the disk is not.\n *\n * When `trees` is given it is the ONLY source — no silent fall back to `deploy_dir` on a disk that\n * does not exist. An app the declaration says to deploy and the artifact published no tree for is\n * refused by name, before any write, rather than created empty and reported as deployed.\n */\nfunction builtTree(decl: AppDecl, opts: AppOptions): Tree | null {\n if (!decl.deploy_dir) return null;\n const hosted = opts.trees;\n if (hosted !== undefined && hosted[decl.name] === undefined) {\n // Two very different facts wear the same words unless the caller says which. \"No tree was\n // published for this app\" sends an operator to the publisher; \"the object is there and the read\n // of it failed\" sends them to the object store, and telling them the first when it is the\n // second costs them the whole investigation. So the caller that did the reading passes what\n // went wrong (`tree_errors`), and it is named here rather than swallowed.\n const failed = opts.tree_errors?.[decl.name];\n throw new Error(\n `app \"${decl.name}\" declares deploy_dir \"${decl.deploy_dir}\", but this apply was handed no built tree for it` +\n (failed === undefined ? \"\" : `: ${failed}`),\n );\n }\n const files = collectFiles(hosted?.[decl.name] ?? resolve(opts.dir, decl.deploy_dir));\n return { files, hash: contentHash(files) };\n}\n\n/**\n * Secrets before the deploy, so the build that follows runs with the declared environment.\n *\n * Then wait for it. A build is asynchronous and the app's lasting hostname is only assigned when\n * one goes live, so an apply that returns the moment the upload lands reports `url: null` and\n * leaves the platform holding no address for the app — which is also the address a declared `mcp`\n * endpoint is resolved against (§29.5). Deployments advance on read, so reading is the wait.\n */\nasync function writeApp(client: VettaClient, id: string, env: Record<string, string>, tree: Tree | null) {\n // Concurrently: each secret is one full round trip through the API and no declared value depends\n // on another, so writing them in sequence made a hosted install pay that latency once per\n // variable — measured on staging at 3.0-3.7 s each, under 350 ms of which was the hosting\n // provider. The deploy below still waits for every one of them, which is the ordering that\n // matters: the build must run with the declared environment already in place.\n await eachInFlight(Object.entries(env), ([name, value]) =>\n client.apps.setSecret(id, { name, value, value_hash: secretHash(name, value) }),\n );\n if (!tree) return;\n await client.apps.deploy(id, tree.files, tree.hash);\n await settleDeploy(client, id);\n}\n\n/** Bounded: a build that outlasts it is still building, and the next apply reads it again. */\nconst SETTLE_TRIES = 30;\nconst SETTLE_MS = 4_000;\n\nasync function settleDeploy(client: VettaClient, id: string): Promise<void> {\n for (let poll = 0; poll < SETTLE_TRIES; poll++) {\n const newest = (await client.apps.deployments(id, { limit: 1 })).data[0];\n if (newest === undefined || newest.status === \"ready\" || newest.status === \"error\") return;\n await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));\n }\n}\n\nasync function createApp(\n client: VettaClient,\n decl: AppDecl,\n env: Record<string, string>,\n tree: Tree | null,\n migrations: MigrationFile[],\n opts: AppOptions,\n appIds: Map<string, string>,\n): Promise<ResourceReport> {\n const created = await ensureApp(client, {\n name: decl.name,\n type: decl.type,\n project: opts.project,\n ...(decl.description !== undefined ? { description: decl.description } : {}),\n ...(decl.mcp !== undefined ? { mcp: decl.mcp } : {}),\n });\n appIds.set(decl.name, created.id);\n await writeApp(client, created.id, withAppId(env, decl, opts, created.id), tree);\n const notes: string[] = [];\n if (migrations.length > 0) notes.push((await applyMigrations(client, created.id, migrations)).note);\n if (decl.buckets !== undefined) notes.push((await applyBuckets(client, created.id, decl.buckets)).note);\n // Re-read: the hostname is assigned by the build `writeApp` just waited on, not by create.\n return {\n name: decl.name,\n action: \"created\",\n id: created.id,\n url: (await client.apps.get(created.id)).url,\n ...(notes.length > 0 ? { reason: notes.join(\"; \") } : {}),\n };\n}\n\nexport interface AppOptions extends Owner {\n dryRun: boolean;\n /** Base directory `deploy_dir` is resolved against — the config file's directory. */\n dir: string;\n /**\n * Built trees by app name, for an apply that has no checkout (`up.ts`). Present ⇒ the disk is not\n * consulted at all; absent ⇒ `dir` + `deploy_dir` is the source, as it always was.\n */\n trees?: Record<string, Record<string, string>> | undefined;\n /**\n * Why an app's tree is missing from `trees`, by app name, when the caller knows. Only a caller\n * that fetched them can distinguish an object nobody uploaded from one whose read failed, and the\n * refusal above is the only place an operator ever sees either.\n */\n tree_errors?: Record<string, string> | undefined;\n /** core-gaps: U8-database — each app's published migrations, by name, under a hosted apply (`migrations.ts`). */\n migrations?: Record<string, MigrationFile[]> | undefined;\n /** What `{ from_env }` reads. The author's shell by default; a hosted apply's answers instead. */\n env: Record<string, string | undefined>;\n /**\n * What the PLATFORM provides, read before `env` and written whether or not the declaration names\n * it (`PlatformEnv`, `canonical-spec §29.7`). Present only on a hosted apply.\n */\n platform?: PlatformEnv | undefined;\n}\n\n/**\n * An app whose row names another project — or no project at all — is **refused before any write**\n * (ADR-0375), unless `--adopt` takes it; adoption stamps the row through the ensure and reports\n * `updated` with the transfer as its reason.\n *\n * Secret values are write-only (§29.2): nothing reads one back. Drift is judged by `value_hash`,\n * the client digest the list route echoes — a declared name is (re-)set only when its live hash\n * differs from the local one, so an untouched app is honestly `unchanged`. The list also names\n * live secrets the config does not declare; those are reported, never deleted (ADR-0352).\n *\n * A `deploy_dir` ships only when its hash differs from the newest live deployment's `content_hash`\n * (ADR-0357): equal means the site is `unchanged` and nothing is uploaded; a deployment made\n * without a hash (`null`) can never match, so it is redeployed once and carries one from then on.\n */\nexport async function upsertApp(\n client: VettaClient,\n decl: AppDecl,\n opts: AppOptions,\n appIds: Map<string, string>,\n): Promise<ResourceReport> {\n // Planned before the first request, so a variable no layer supplies still refuses this app before\n // anything is written — naming the variable and never a value (`planEnv`).\n const declared = planEnv(decl, opts);\n const writesAppId = decl.env !== undefined && opts.platform !== undefined;\n const names = [...declared.map((one) => one.name), ...(writesAppId ? [PLATFORM_ENV.app_id] : [])];\n const note = (notes: string[]) => (notes.length > 0 ? { reason: notes.join(\"; \") } : {});\n const mcpPlan = decl.mcp !== undefined ? [`will set mcp ${decl.mcp}`] : [];\n const migrationPlan = decl.migrations !== undefined ? [`will apply migrations ${decl.migrations.join(\", \")}`] : [];\n const bucketPlan = decl.buckets !== undefined ? [`will ensure buckets ${decl.buckets.map((one) => one.name).join(\", \")}`] : [];\n const current = await findApp(client, decl.name, opts.skipped);\n if (!current) {\n const willSet = names.length > 0 ? [`will set ${names.join(\", \")}`] : [];\n if (opts.dryRun) {\n return {\n name: decl.name,\n action: \"created\",\n ...note([...willSet, ...mcpPlan, ...(decl.deploy_dir ? [`will deploy ${decl.deploy_dir}`] : []), ...migrationPlan, ...bucketPlan]),\n };\n }\n // Resolved before the create, not inside it: a tree that cannot be read refuses the app\n // rather than leaving a created, empty one behind (`builtTree`). A new app holds no secrets,\n // so every invented value is invented here — once, on the apply that made the app.\n const { values } = await materialize(declared, EMPTY, false);\n return createApp(client, decl, values, builtTree(decl, opts), declaredMigrations(decl, opts), opts, appIds);\n }\n // Ownership is compared before `appIds` and before every write, so `--dry-run` tells the truth\n // and a refused app is neither half-written nor wired into an agent's `allowed_apps` (§29.3).\n const owned = current.project === opts.project;\n if (!owned && !opts.adopt) {\n return {\n name: decl.name,\n action: \"refused\",\n id: current.id,\n reason: ownershipRefusal(decl.name, opts.project, current.project),\n };\n }\n appIds.set(decl.name, current.id);\n if (current.type !== decl.type) {\n return {\n name: decl.name,\n action: \"refused\",\n id: current.id,\n reason: `app \"${decl.name}\" exists as ${current.type} and type cannot change; delete it or declare type \"${current.type}\"`,\n };\n }\n // The ensure is what writes the stamp — the update path never POSTs — so adoption happens here,\n // once, before the writes it authorises.\n const from = current.project === null ? \"(previously unowned)\" : `from project \"${current.project}\"`;\n const adoption = owned ? [] : [`${opts.dryRun ? \"will adopt\" : \"adopted\"} ${from}`];\n if (!owned && !opts.dryRun) {\n await ensureApp(client, { name: decl.name, type: decl.type, project: opts.project, adopt: true });\n }\n const live = declared.length === 0 ? [] : (await client.apps.secrets(current.id)).data;\n // Judged against what the config DECLARES, not against what this apply resolved: an invented value\n // the app already holds is deliberately left out of `env`, and calling it unmanaged would tell an\n // operator their own minted key was set by someone else.\n const managed = new Set(names);\n const unmanaged = live.map((secret) => secret.name).filter((name) => !managed.has(name));\n const held = new Map(live.map((secret) => [secret.name, secret.value_hash]));\n const { values, unmade } = await materialize(declared, new Set(held.keys()), opts.dryRun);\n const env = withAppId(values, decl, opts, current.id);\n // A live hash equal to the local one means the value stands as declared; a null (set before\n // hashes existed, or by hand) never matches, so it is rewritten once and carries one from then on.\n const staleEnv = Object.fromEntries(\n Object.entries(env).filter(([name, value]) => held.get(name) !== secretHash(name, value)),\n );\n const staleNames = [...Object.keys(staleEnv), ...unmade];\n // An undeclared `mcp` is `null` on the wire: dropping it from the config clears the endpoint\n // and forgets its token, the way a dropped resource is removed rather than left behind.\n const patch = {\n ...(decl.description !== undefined && decl.description !== current.description ? { description: decl.description } : {}),\n ...((decl.mcp ?? null) !== current.mcp ? { mcp: decl.mcp ?? null } : {}),\n };\n const drifted = Object.keys(patch).length > 0;\n const tree = builtTree(decl, opts);\n const newest = tree ? (await client.apps.deployments(current.id, { limit: 1 })).data[0] : undefined;\n const stale = tree !== null && newest?.content_hash !== tree.hash;\n let action: ResourceAction = !owned || drifted || stale || staleNames.length > 0 ? \"updated\" : \"unchanged\";\n const plan = opts.dryRun\n ? [\n ...(staleNames.length > 0 ? [`will set ${staleNames.join(\", \")}`] : []),\n ...(\"mcp\" in patch ? (patch.mcp === null ? [\"will clear mcp\"] : mcpPlan) : []),\n ...(decl.deploy_dir ? [stale ? `will deploy ${decl.deploy_dir}` : `${decl.deploy_dir} unchanged`] : []),\n ...migrationPlan,\n ...bucketPlan,\n ]\n : [];\n if (!opts.dryRun) {\n // The server guards the ensure AND the patch by project (ADR-0388), so the patch has to say\n // which project is speaking or it is refused on every drift of an app we ourselves stamped.\n if (drifted) await client.apps.update(current.id, { ...patch, project: opts.project });\n await writeApp(client, current.id, staleEnv, stale ? tree : null);\n // Migrations are idempotent by name (§37), so every apply re-runs the list and the note says\n // how many were new; an app that only gained one is `updated`.\n const migrations = declaredMigrations(decl, opts);\n if (migrations.length > 0) {\n const { fresh, note } = await applyMigrations(client, current.id, migrations);\n if (fresh > 0) action = \"updated\";\n plan.push(note);\n }\n // Buckets likewise: a missing one is made, a held one is left as it is, and nothing is deleted.\n if (decl.buckets !== undefined) {\n const { fresh, note } = await applyBuckets(client, current.id, decl.buckets);\n if (fresh > 0) action = \"updated\";\n plan.push(note);\n }\n }\n return {\n name: decl.name,\n action,\n id: current.id,\n // Re-read only when a build actually ran: a dry run issues no call at all.\n url: !opts.dryRun && stale ? (await client.apps.get(current.id)).url : current.url,\n ...note([...adoption, ...plan, ...(unmanaged.length > 0 ? [`unmanaged secrets: ${unmanaged.join(\", \")}`] : [])]),\n };\n}\n","/**\n * core-gaps: storage-stock — `apps[].buckets` in `naive up` (`canonical-spec §38.2`). A declared\n * bucket the app's object store lacks is created with the declared `public`; one it already holds is\n * left exactly as it is, `public` included, because flipping visibility on a bucket that is serving\n * URLs is a decision for a person. Nothing is ever deleted: a bucket dropped from the config, or made\n * by the app's own code, stays. `DELETE …/storage/buckets/{bucket}` is the only way one goes.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\n\nexport interface BucketDecl {\n name: string;\n public: boolean;\n}\n\n/** One list, then one create per missing name; `fresh` counts the ones that were made. */\nexport async function applyBuckets(\n client: VettaClient,\n appId: string,\n buckets: readonly BucketDecl[],\n): Promise<{ fresh: number; note: string }> {\n const live = new Set((await client.storage.buckets.list({ app: appId })).data.map((row) => row.name));\n const missing = buckets.filter((bucket) => !live.has(bucket.name));\n for (const bucket of missing) await client.storage.buckets.create(bucket.name, { app: appId, public: bucket.public });\n return { fresh: missing.length, note: `${buckets.length} bucket(s), ${missing.length} new` };\n}\n","/**\n * core-gaps: U8-database — `apps[].migrations` in `naive up` (`canonical-spec §37`). Each entry is a\n * path under the config's directory, with `*` allowed in the file name (`sql/*.sql`); files match\n * in name order within one entry and entries in declaration order, so `0001_…`, `0002_…` is the\n * whole ordering story. A file's migration name is its base name without the extension, and\n * `POST /v1/apps/{id}/db/migrations` applies each once: a replay is a no-op, changed SQL under a\n * kept name is `409 version_conflict`, which the report carries by name.\n *\n * A hosted apply has no checkout: the publisher read the files and shipped them on the app's built\n * tree (`canonical-spec §31.1`), so they arrive as `opts.migrations` by app name.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { readFileSync, readdirSync } from \"node:fs\";\nimport { basename, dirname, extname, join, resolve } from \"node:path\";\nimport type { AppDecl } from \"./define\";\n\nexport interface MigrationFile {\n name: string;\n sql: string;\n}\n\n/** `*` matches within one path segment; anything else in the pattern is literal. */\nfunction matcher(pattern: string): (name: string) => boolean {\n const source = pattern\n .split(\"*\")\n .map((part) => part.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n .join(\"[^/]*\");\n const regex = new RegExp(`^${source}$`);\n return (name) => regex.test(name);\n}\n\n/** The files each pattern names, in order, each read once; a pattern that names nothing refuses. */\nexport function migrationFiles(patterns: readonly string[], dir: string): MigrationFile[] {\n const seen = new Set<string>();\n const files: MigrationFile[] = [];\n for (const pattern of patterns) {\n const full = resolve(dir, pattern);\n const paths = pattern.includes(\"*\")\n ? readdirSync(dirname(full), { withFileTypes: true })\n .filter((entry) => entry.isFile() && matcher(basename(full))(entry.name))\n .map((entry) => join(dirname(full), entry.name))\n .sort()\n : [full];\n if (paths.length === 0) throw new Error(`migrations \"${pattern}\" matches no file under ${dir}`);\n for (const path of paths) {\n const name = basename(path, extname(path));\n if (seen.has(name)) continue;\n seen.add(name);\n files.push({ name, sql: readFileSync(path, \"utf8\") });\n }\n }\n return files;\n}\n\n/**\n * The SQL an app declares, read before any write so an unreadable file refuses the app whole. Under\n * a hosted apply (`trees` present) the disk is never read: an artifact published before the SQL\n * rode the tree carries none, and the app is refused by name rather than created unmigrated.\n */\nexport function declaredMigrations(\n decl: AppDecl,\n opts: { dir: string; trees?: object | undefined; migrations?: Record<string, MigrationFile[]> | undefined },\n): MigrationFile[] {\n if (decl.migrations === undefined) return [];\n if (opts.trees === undefined) return migrationFiles(decl.migrations, opts.dir);\n const published = opts.migrations?.[decl.name];\n if (published === undefined) {\n throw new Error(\n `app \"${decl.name}\" declares migrations, but this apply was handed no published SQL for it. Republish the artifact, or apply them with \\`naive up\\` from a clone.`,\n );\n }\n return published;\n}\n\n/** Applies in order; `fresh` counts the ones the app had not seen, and a refused one throws by name. */\nexport async function applyMigrations(\n client: VettaClient,\n appId: string,\n files: readonly MigrationFile[],\n): Promise<{ fresh: number; note: string }> {\n const applied = new Set((await client.database.migrations({ app: appId })).map((row) => row.name));\n for (const file of files) await client.database.migrate(file.name, file.sql, { app: appId });\n const fresh = files.filter((file) => !applied.has(file.name)).length;\n return { fresh, note: `${files.length} migration(s), ${fresh} new` };\n}\n","/**\n * Agents in `naive up`: upsert by name with a drift-only PATCH, `allowed_apps` names resolved to\n * app ids in the `apps` tool config (§29.3), the platform config passthrough (`system`, `skills`,\n * `mcp_servers`) verbatim, and `identity` attached after the upsert, never revoked (ADR-0353).\n *\n * An agent's `schedules` are the one bounded exception to \"nothing is deleted by omission\"\n * (ADR-0355): deployments have no name, so the declared list is owned as a **complete set** keyed\n * by exact `cron`. Matched rows are patched where other fields drifted, missing crons are created,\n * and the agent's rows whose cron is not declared are deleted. The prune reaches only deployments\n * of agents this blueprint declares with `schedules`; an agent without the key keeps whatever it has.\n *\n * **The match is the cron STRING, not the schedule it denotes.** `\"0 8 * * 1\"` and `\"0 08 * * 1\"`\n * fire at the same minute and are two different keys: re-spelling a declared cron is read as the\n * declared one being absent and an undeclared one being live, so it is a DELETE plus a CREATE, not\n * a PATCH. The new row is a new `dep_` id with a fresh `next_run_at`, and whatever the old row's\n * `enabled: false` was holding back is gone. Nothing here parses cron — a client that normalised\n * the string would have to agree with the server's parser forever to stay idempotent, and the day\n * they disagreed every apply would churn every schedule. Edit a cron and expect a new deployment.\n */\nimport type { AgentPatch, DeploymentPatch, VettaClient } from \"@usenaive-sdk/vetta\";\nimport { handoffsEnabled, handoffsOf, normaliseMultiagent, type Agent, type Deployment, type Toolset } from \"@vetta/core\";\nimport type { AgentDecl, ScheduleDecl } from \"./define\";\nimport { attempt, changed, eachInFlight, line, tombstone, type ResourceReport } from \"./report\";\nimport { ownershipRefusal } from \"./apps\";\nimport { teamWithoutRoster } from \"./roster\";\n\n/** Declared-name → live id for the resources agents reference by name. */\nexport interface Ids {\n apps: Map<string, string>;\n identities: Map<string, string>;\n}\n\n/** The install an agent belongs to (`canonical-spec §31.8`): what its `metadata` names, when a template made it. */\nexport interface Membership {\n project: string;\n blueprint?: string;\n template?: string;\n /** `naive up --adopt`: take a same-named agent another project, or none, owns (ADR-0785). */\n adopt?: boolean;\n /** What `metadata.group` files the crew under; the template when absent (ADR-1104). */\n group?: string;\n}\n\n/**\n * What every template agent's `system` opens with (§31.8): the one paragraph that turns the setup\n * answers into something the crew acts on. The `project_context` tool it names is offered only to\n * an agent whose metadata names a project with an applied install — exactly the agents this is\n * prepended for.\n */\nexport const PROJECT_CONTEXT_PREAMBLE =\n \"Before anything else, read the project context with the `project_context` tool. The answers in it \" +\n \"are the client's own — never invent, assume or restate them from memory; what the context does not \" +\n \"say, you ask. Use the context's own words for the company, its offer and its audience.\";\n\n/** `metadata` for a template agent — the declared keys over what the live row carries, the membership over both; the declaration's alone outside a template. */\nfunction desiredMetadata(decl: AgentDecl, of: Membership, current: Agent | null): Record<string, unknown> | undefined {\n if (of.template === undefined) return decl.metadata;\n return {\n ...current?.metadata,\n ...decl.metadata,\n project: of.project,\n ...(of.blueprint !== undefined ? { blueprint: of.blueprint } : {}),\n template: of.template,\n group: of.group ?? of.template,\n };\n}\n\n/**\n * The declared `system`, opened with the preamble when a template made this agent. Computed from\n * the declaration alone and never from the live row, so a re-apply compares the same string it\n * wrote last time and stacks nothing.\n */\nfunction desiredSystem(decl: AgentDecl, of: Membership): string | undefined {\n if (of.template === undefined) return decl.system;\n return decl.system === undefined ? PROJECT_CONTEXT_PREAMBLE : `${PROJECT_CONTEXT_PREAMBLE}\\n\\n${decl.system}`;\n}\n\n/**\n * `allowed_apps` on the wire is app ids in the `apps` tool's config (`canonical-spec §29.3`);\n * the blueprint declares app *names*, resolved here. `ids` is `undefined` when nothing scopes this\n * agent, and then the toolset the config (or the live agent) already carries is left alone.\n */\nfunction desiredTools(\n decl: AgentDecl,\n current: Agent | null,\n ids: string[] | undefined,\n): Toolset | undefined {\n // A declared `handoffs` (§31.7) is the whole grant: the agent tools run `allow`, because a handoff\n // runs unattended; who they reach is the `handoffs` field itself, not a config here.\n const handoff = decl.handoffs !== undefined && handoffsEnabled(decl.handoffs);\n if (ids === undefined && !handoff) return decl.tools;\n const base: Toolset = decl.tools ??\n current?.tools ?? { default_config: { permission: \"allow\" }, configs: {} };\n const appsTool = base.configs[\"apps\"] ?? { enabled: true, permission: base.default_config.permission };\n const allowed = { enabled: true, permission: \"allow\" } as const;\n return {\n default_config: base.default_config,\n configs: {\n ...base.configs,\n ...(ids !== undefined ? { apps: { ...appsTool, config: { ...appsTool.config, allowed_apps: ids } } } : {}),\n ...(handoff ? { send_to_agent: allowed, list_agents: allowed } : {}),\n },\n };\n}\n\nasync function createAgent(\n client: VettaClient,\n decl: AgentDecl,\n tools: Toolset | undefined,\n team: boolean | null | undefined,\n identityId: string | undefined,\n system: string | undefined,\n metadata: Record<string, unknown> | undefined,\n): Promise<ResourceReport> {\n const created = await client.agents.create({\n name: decl.name,\n model: decl.model,\n budget: decl.budget,\n ...(decl.description !== undefined ? { description: decl.description } : {}),\n ...(system !== undefined ? { system } : {}),\n ...(decl.skills !== undefined ? { skills: decl.skills } : {}),\n ...(decl.mcp_servers !== undefined ? { mcp_servers: decl.mcp_servers } : {}),\n ...(tools !== undefined ? { tools } : {}),\n ...(decl.window !== undefined ? { window: decl.window } : {}),\n ...(team !== undefined ? { multiagent: team } : {}),\n ...(decl.handoffs !== undefined ? { handoffs: decl.handoffs } : {}),\n ...(decl.output_schema !== undefined ? { output_schema: decl.output_schema } : {}),\n ...(decl.structured_output_required !== undefined ? { structured_output_required: decl.structured_output_required } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n });\n if (identityId !== undefined) await client.identities.attach(created.id, identityId);\n return { name: decl.name, action: \"created\", id: created.id };\n}\n\n/**\n * *** WHAT AN AGENT MAY REACH IS THIS PROJECT'S APPS, NOT THE ORGANIZATION'S. ***\n *\n * `allowed_apps` absent means \"every app in the organization\" (`canonical-spec §29.3`), which is\n * the right default for an agent somebody wrote by hand and the wrong one for a crew a blueprint\n * declares. Measured: the media crew's first unattended run, session\n * `ses_p3t7rbns376ky36tjztp95yb9f` off its 07:00 producer cron, read its four `channel.*` tools\n * and then called `dashboard.list_clients` — an app belonging to `seo-geo-agency`, an unrelated\n * blueprint installed in the same organization — and parked on `awaiting_approval` with nobody\n * there to approve. 56,849 µUSD, no video. The media blueprint's `default_config` is\n * `permission: \"ask\"`, so a sibling project's whole MCP namespace arrives as a question rather than\n * as a refusal, and its own comment's claim that the leftover \"can only be a tool from an account\n * this channel connected\" is simply false.\n *\n * So a declaration that declares apps scopes the agents it declares to those apps: `scoped` is the\n * ids this run actually provisioned. `undefined` — a declaration with no apps at all — keeps the\n * old behaviour rather than locking such an agent out of apps it was using before this ran, which\n * would be a silent removal by omission (ADR-0355).\n *\n * An app that was REFUSED is not in `scoped`, which is deliberate and is the other half of the\n * hosted-apply problem: granting `<app>.<tool>` for an app the same run declined to create hands\n * the crew a tool surface that does not exist.\n */\nexport async function upsertAgent(\n client: VettaClient,\n decl: AgentDecl,\n existing: Agent[],\n ids: Ids,\n dryRun: boolean,\n scoped: string[] | undefined,\n of: Membership,\n): Promise<ResourceReport> {\n const unresolved = (decl.allowed_apps ?? []).filter((name) => !ids.apps.has(name));\n const identityId = decl.identity === undefined ? undefined : ids.identities.get(decl.identity);\n // Define-time validation pins these to declared resources, so at apply time a miss only means\n // the app or identity itself was refused above — the agent must not silently widen to \"all\n // apps\" (§29.3) or quietly run as nobody (§22).\n const missing =\n unresolved.length > 0\n ? `allowed_apps needs app \"${unresolved[0]}\"`\n : decl.identity !== undefined && identityId === undefined\n ? `identity needs \"${decl.identity}\"`\n : null;\n if (missing !== null && !dryRun) {\n return { name: decl.name, action: \"refused\", reason: `${missing}, which was not provisioned in this run` };\n }\n const appIds =\n decl.allowed_apps !== undefined\n ? decl.allowed_apps.flatMap((name) => ids.apps.get(name) ?? [])\n : scoped;\n const current = existing.find((agent) => agent.name === decl.name) ?? null;\n /**\n * ADR-0785, the apps rule (ADR-0375) for agents. Adoption was by bare name, so installing a\n * template into a company that already had an `analyst` rewrote that agent's prompt, tools and\n * budget — and a second channel from the same template took over the first one's crew. A\n * template agent carries its project; one that names ANOTHER is refused. An untagged agent is\n * still tagged, because template agents from before the stamp (2026-09-09) carry none.\n */\n const owner = typeof current?.metadata?.[\"project\"] === \"string\" ? current.metadata[\"project\"] : null;\n if (current && of.template !== undefined && owner !== null && owner !== of.project && !of.adopt) {\n return { name: decl.name, action: \"refused\", id: current.id, reason: ownershipRefusal(decl.name, of.project, owner, \"agent\") };\n }\n const tools = desiredTools(decl, current, appIds);\n // A roster is resolved to ids in pass two (`roster.ts`), once every crew member has one.\n const team = teamWithoutRoster(decl.multiagent);\n const system = desiredSystem(decl, of);\n const metadata = desiredMetadata(decl, of, current);\n if (!current) {\n return dryRun ? { name: decl.name, action: \"created\" } : createAgent(client, decl, tools, team, identityId, system, metadata);\n }\n const patch = drift(decl, current, tools, team, system, metadata);\n // The grant is attach-only here: `identity` says what the agent may act as, never what to revoke.\n const held = identityId === undefined ? [] : (await client.identities.held(current.id)).data;\n const grant = identityId === undefined || held.some((one) => one.id === identityId) ? null : identityId;\n const drifted = Object.keys(patch).length > 0 || missing !== null || grant !== null;\n if (!drifted) return { name: decl.name, action: \"unchanged\", id: current.id };\n if (!dryRun) {\n if (Object.keys(patch).length > 0) await client.agents.update(current.id, patch);\n if (grant !== null) await client.identities.attach(current.id, grant);\n }\n return { name: decl.name, action: \"updated\", id: current.id };\n}\n\n/** Every declared field that differs from the live agent; an undeclared one is never drift (§31.6). */\nfunction drift(\n decl: AgentDecl,\n current: Agent,\n tools: Toolset | undefined,\n team: boolean | null | undefined,\n system: string | undefined,\n metadata: Record<string, unknown> | undefined,\n): AgentPatch {\n const patch: AgentPatch = {};\n if (changed(decl.model, current.model)) patch.model = decl.model;\n if (changed(decl.budget, current.budget)) patch.budget = decl.budget;\n if (changed(decl.description, current.description)) patch.description = decl.description;\n if (changed(system, current.system)) patch.system = system;\n if (changed(decl.skills, current.skills)) patch.skills = decl.skills;\n if (changed(decl.mcp_servers, current.mcp_servers)) patch.mcp_servers = decl.mcp_servers;\n if (changed(tools, current.tools)) patch.tools = tools;\n if (changed(decl.window, current.window)) patch.window = decl.window;\n if (team !== undefined && changed(normaliseMultiagent(team), normaliseMultiagent(current.multiagent))) patch.multiagent = team;\n // A live agent from before §28.15 carries no `handoffs`; it reads as `true`, so declaring `true` is not drift.\n if (changed(decl.handoffs, handoffsOf(current))) patch.handoffs = decl.handoffs;\n if (changed(decl.output_schema, current.output_schema)) patch.output_schema = decl.output_schema;\n if (changed(decl.structured_output_required, current.structured_output_required)) patch.structured_output_required = decl.structured_output_required;\n if (changed(metadata, current.metadata)) patch.metadata = metadata;\n return patch;\n}\n\n/**\n * The intake (`canonical-spec §31.4`): the first thing an agent reads, on the apply that **created**\n * it and on no other. `POST /v1/sessions` creates *and* starts in one call with `message` as the\n * first user turn (§7) — exactly what a cron fire already does with `deployment.input_template`,\n * pointed for the first time at a newly created agent.\n *\n * **That is the whole idempotency story.** An agent is created exactly once, so `upsertAgent`\n * answers `created` exactly once and a second `naive up` reports `unchanged` and starts nothing.\n * There is no marker column and no metadata flag, so there is nothing to go stale, nothing to\n * migrate and nothing to disagree with the agent's own existence. Delete the agent and re-apply and\n * it intakes again, which is the correct reading of \"this agent is new\".\n *\n * `budget_micro_usd` is optional and absent means the agent's own `budget` governs, so it is\n * omitted from the body rather than sent as a null.\n */\nexport async function openIntake(\n client: VettaClient,\n agent: ResourceReport,\n decl: NonNullable<AgentDecl[\"intake\"]>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n // No id yet means a dry-run `created` agent: the session it would open is planned, not started.\n if (dryRun || agent.id === undefined) return { name: agent.name, action: \"created\" };\n const started = await client.sessions.create({\n agent_id: agent.id,\n message: decl.message,\n ...(decl.budget_micro_usd !== undefined ? { budget_micro_usd: decl.budget_micro_usd } : {}),\n });\n return { name: agent.name, action: \"created\", id: started.id };\n}\n\n/**\n * `identity` on the wire is echoed as an `idn_` id whatever was written (§12), so drift compares\n * the resolved id. A schedule of an agent that was refused is refused with it, and one whose\n * identity was not provisioned is refused rather than created to run as nobody (§22).\n */\n/** The opening sentence of a timer's brief, short enough to sit in a list beside its time. */\nfunction brief(input: string): string {\n const first = input.trim().split(/(?<=[.!?])\\s|\\n/)[0]?.trim() ?? \"\";\n const text = first.replace(/[.\\s]+$/, \"\");\n return text.length > 72 ? `${text.slice(0, 71).trimEnd()}…` : text;\n}\n\nasync function upsertSchedule(\n client: VettaClient,\n agent: ResourceReport,\n decl: ScheduleDecl,\n current: Deployment | undefined,\n identityIds: Map<string, string>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n const name = `${agent.name} @ ${decl.cron}`;\n if (agent.action === \"refused\") throw new Error(`agent \"${agent.name}\" was not provisioned in this run`);\n const identity = decl.identity === undefined ? undefined : identityIds.get(decl.identity);\n const unresolved = decl.identity !== undefined && identity === undefined;\n if (unresolved && !dryRun) throw new Error(`identity needs \"${decl.identity}\", which was not provisioned in this run`);\n if (!current) {\n // No id yet means a dry-run `created` agent — every declared cron would be created with it.\n if (dryRun || agent.id === undefined) return { name, action: \"created\" };\n const created = await client.deployments.create({\n agent_id: agent.id,\n cron: decl.cron,\n input_template: decl.input,\n budget_micro_usd: decl.budget_micro_usd,\n ...(decl.timezone !== undefined ? { timezone: decl.timezone } : {}),\n ...(identity !== undefined ? { identity } : {}),\n ...(decl.enabled !== undefined ? { enabled: decl.enabled } : {}),\n });\n return { name, action: \"created\", id: created.id };\n }\n const patch: DeploymentPatch = {};\n if (changed(decl.timezone, current.timezone)) patch.timezone = decl.timezone;\n if (changed(decl.input, current.input_template)) patch.input_template = decl.input;\n if (changed(decl.budget_micro_usd, current.budget_micro_usd)) patch.budget_micro_usd = decl.budget_micro_usd;\n if (changed(identity, current.identity)) patch.identity = identity;\n if (changed(decl.enabled, current.enabled)) patch.enabled = decl.enabled;\n if (Object.keys(patch).length === 0 && !unresolved) return { name, action: \"unchanged\", id: current.id };\n if (!dryRun) await client.deployments.update(current.id, patch);\n return { name, action: \"updated\", id: current.id };\n}\n\n/** The complete-set reconcile from the header: upsert each declared cron, then prune the agent's rest. */\nexport async function reconcileSchedules(\n client: VettaClient,\n agent: ResourceReport,\n declared: ScheduleDecl[],\n live: Deployment[],\n identityIds: Map<string, string>,\n dryRun: boolean,\n into: ResourceReport[],\n): Promise<void> {\n const rows = live.filter((row) => row.agent_id === agent.id);\n // Concurrently: a declared timer is one write keyed by its own cron and shares nothing with the\n // next, so arming them in sequence made a crew pay the request latency once per timer — measured\n // on staging at 4.4-4.8 s apiece, none of it the provider's. `line` rather than `attempt` because\n // the report is filed in DECLARATION order, not in the order the server happened to answer.\n into.push(\n ...(await eachInFlight(declared, async (decl) => ({\n ...(await line(`${agent.name} @ ${decl.cron}`, () =>\n upsertSchedule(client, agent, decl, rows.find((row) => row.cron === decl.cron), identityIds, dryRun),\n )),\n // `<agent> @ <cron>` says WHEN a timer runs and nothing about what it does, so the dashboard's\n // opening message could only ever draw a timetable from these lines. The brief's first\n // sentence is what turns that timetable into a roadmap (§29.6).\n summary: brief(decl.input),\n }))),\n );\n // A refused agent's id, when it has one, is ANOTHER project's agent (ADR-0785): its timers are not ours to prune.\n if (agent.action === \"refused\") return;\n for (const row of rows.filter((row) => !declared.some((decl) => decl.cron === row.cron))) {\n const name = `${agent.name} @ ${row.cron}`;\n await attempt(into, name, () => tombstone(name, row, (id) => client.deployments.delete(id), dryRun));\n }\n}\n","/**\n * `identities[].cards[]` in `naive up` (`canonical-spec §45.5`): presence by `label`. A live card\n * with the declared label that is still `pending_payment | issuing | active` is `unchanged`; one\n * that has ended its life (`failed | cancelled | refunded`) is `refused`, never re-bought; and only\n * a label with no card at all is issued through `POST /v1/identities/{id}/cards`, which debits\n * credits. A prepaid card cannot be reloaded, so there is no drift to patch — only present or not\n * — and nothing here ever cancels, refunds or re-buys. `--dry-run` quotes instead of issuing and\n * says what it would cost, so the operator sees the credits before they move.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { CardSchema, decimalStringFromMicro, microUsd, type Card, type CardStatus, type IssueCard } from \"@vetta/core\";\nimport { attempt, listAll, type ResourceReport } from \"./report\";\n\nconst LIVE: ReadonlySet<CardStatus> = new Set([\"pending_payment\", \"issuing\", \"active\"]);\n\n/** `<identity> / card <label>` — one line per declared card, filed under the identity's report. */\nconst nameOf = (identity: string, decl: IssueCard): string => `${identity} / card ${decl.label}`;\n\nasync function upsertCard(\n client: VettaClient,\n identityId: string,\n decl: IssueCard,\n live: Card[],\n dryRun: boolean,\n name: string,\n): Promise<ResourceReport> {\n const current = live.find((card) => card.label === decl.label && LIVE.has(card.status));\n if (current) return { name, action: \"unchanged\", id: current.id };\n // A card with this label that has already been through its life is NOT re-bought. `up` runs on\n // every deploy: re-issuing would debit credits and place a fresh order once per run against a\n // card the issuer keeps refusing, and would buy back one the customer deliberately cancelled.\n // Presence by label means \"declared once\", not \"buy until one sticks\" — see this file's header.\n const spent = live.find((card) => card.label === decl.label);\n if (spent) {\n return { name, action: \"refused\", id: spent.id, reason: `a card labelled \"${decl.label}\" is ${spent.status}; issue a replacement by hand` };\n }\n if (dryRun) {\n const quote = await client.identities.cards.quote(identityId, { load_micro_usd: decl.load_micro_usd });\n const price = decimalStringFromMicro(microUsd(quote.price_micro_usd));\n return { name, action: \"created\", reason: `would debit ${price} USD of credits (${quote.price_micro_usd} micro-USD)` };\n }\n const issued = await client.identities.cards.issue(identityId, decl);\n return { name, action: \"created\", id: issued.id };\n}\n\n/**\n * Every declared card of one identity, in declaration order. `identityId` is `undefined` when the\n * identity does not exist yet: on a dry run that is the plan (each card `created`, the price left\n * to the apply that makes the identity); on an apply it means the identity was refused, and so is\n * every card that would hang off it.\n */\nexport async function reconcileCards(\n client: VettaClient,\n identity: string,\n identityId: string | undefined,\n decls: readonly IssueCard[],\n dryRun: boolean,\n into: ResourceReport[],\n skipped: string[],\n): Promise<void> {\n if (decls.length === 0) return;\n if (identityId === undefined) {\n for (const decl of decls) {\n into.push(\n dryRun\n ? { name: nameOf(identity, decl), action: \"created\", reason: \"quoted once the identity exists; issuing debits credits\" }\n : { name: nameOf(identity, decl), action: \"refused\", reason: `identity \"${identity}\" was not provisioned in this run` },\n );\n }\n return;\n }\n const live = await listAll(client.config, `/v1/identities/${identityId}/cards`, CardSchema, skipped);\n for (const decl of decls) {\n const name = nameOf(identity, decl);\n await attempt(into, name, () => upsertCard(client, identityId, decl, live, dryRun, name));\n }\n}\n","/**\n * `identities[].legal` under `up` (`workstreams/12 §8`, canonical-spec §43): a company the identity\n * should hold, keyed by `label`, **reported and never provisioned**. A hosted identity check needs a\n * person on the other end and a formation debits the organization's credits, so a repo cannot be\n * the one that starts either. `up` reads what exists — the case status, whether a company matching\n * a declared name option exists and how far along it is — and refuses the rest with the command a\n * person runs to move it.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport {\n canonicalName,\n LegalCompanySchema,\n LegalVerificationSchema,\n type LegalCompany,\n type LegalVerification,\n} from \"@vetta/core\";\nimport type { IdentityDecl } from \"./define\";\nimport { listAll, type ResourceReport } from \"./report\";\n\nexport type LegalDecl = NonNullable<IdentityDecl[\"legal\"]>[number];\n\nconst FILE = \"vetta identity legal form\";\nconst VERIFY = \"vetta identity legal verify\";\n\n/** Newest case first: the one a person is working on is the one the report should name. */\nfunction latest(\n cases: readonly LegalVerification[],\n): LegalVerification | undefined {\n return [...cases].sort((a, b) => b.created_at.localeCompare(a.created_at))[0];\n}\n\n/** A live company whose state and one name option match the declaration. */\nfunction match(\n decl: LegalDecl,\n companies: readonly LegalCompany[],\n): LegalCompany | undefined {\n const wanted = new Set(\n decl.name_options.map((raw) => canonicalName(raw).name),\n );\n return companies.find(\n (c) =>\n c.state === decl.state && c.name_options.some((o) => wanted.has(o.name)),\n );\n}\n\nfunction report(\n decl: LegalDecl,\n company: LegalCompany | undefined,\n verification: LegalVerification | undefined,\n): ResourceReport {\n const name = decl.label;\n if (company !== undefined) {\n const reason =\n company.status === \"failed\"\n ? `failed: ${company.failure_reason ?? \"the filing was rejected\"}`\n : company.status;\n return {\n name,\n action: company.status === \"failed\" ? \"refused\" : \"unchanged\",\n id: company.id,\n reason,\n };\n }\n if (verification === undefined)\n return {\n name,\n action: \"refused\",\n reason: `no verification case — a person must start one with \\`${VERIFY}\\``,\n };\n if (verification.status === \"verified\") {\n return {\n name,\n action: \"refused\",\n id: verification.id,\n reason: `verified; the fee is debited from credits, so a person files it with \\`${FILE}\\``,\n };\n }\n return {\n name,\n action: \"refused\",\n id: verification.id,\n reason: `verification ${verification.status}; nothing to file yet`,\n };\n}\n\n/**\n * One line per declared company. Only reads: `up` issues no POST here, in a dry run or a real one.\n * An identity this run has not created yet has nothing to read, so every line is a refusal naming\n * the first move.\n */\nexport async function reportLegal(\n client: VettaClient,\n decls: readonly LegalDecl[],\n identityId: string | undefined,\n skipped: string[],\n): Promise<ResourceReport[]> {\n if (decls.length === 0) return [];\n if (identityId === undefined)\n return decls.map((decl) => report(decl, undefined, undefined));\n const base = `/v1/identities/${identityId}/legal`;\n const [companies, cases] = await Promise.all([\n listAll(client.config, `${base}/companies`, LegalCompanySchema, skipped),\n listAll(\n client.config,\n `${base}/verifications`,\n LegalVerificationSchema,\n skipped,\n ),\n ]);\n return decls.map((decl) =>\n report(decl, match(decl, companies), latest(cases)),\n );\n}\n","/**\n * `tasks` in `naive up` (`canonical-spec §31.11`): the crew's first work, seeded as cards on the\n * organization's board rather than sent as N private intakes. Three ensures, in order — the board's\n * owner (the standing orchestrator, `metadata.role: \"orchestrator\"`, created as `CEO` when absent\n * and never renamed) with the crew on its roster and `board: true`; its board; one card per task\n * under the key `<project>:<task.key>`, which is what makes a re-apply answer the same card.\n *\n * Nothing here starts a session. A `todo` card with an assignee and no open blocker is *due*, and\n * the API's tick (§28.18) wakes the assignee — which is the whole point: a crew that starts from\n * the board it will keep working from, with the work, its owner and its order durable from day one.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { BoardCardSchema, normaliseMultiagent, type Agent, type Multiagent } from \"@vetta/core\";\nimport { BlueprintRefusal, inDependencyOrder, type ProjectConfig } from \"./define\";\nimport { changed, line, listAll, type ResourceReport } from \"./report\";\n\n/** The seat the dashboard's Hire page creates (`apps/web/app/lib/orchestrator.server.ts`): same marker, same shape, so the two never make two. */\nconst ORCHESTRATOR_MARKER = \"orchestrator\";\nconst CEO_LABEL = \"CEO\";\nconst CEO_DETAIL = \"Hires and directs the crew\";\nconst CEO_BUDGET = { cap_micro_usd: 50_000_000, max_task_micro_usd: 5_000_000, period: \"month\" as const };\n\nconst isOrchestrator = (agent: Agent): boolean => agent.metadata[\"role\"] === ORCHESTRATOR_MARKER;\n\n/** The owner's team as the board needs it: whatever roster it had, this crew seated after, board on. */\nfunction seated(live: Multiagent | null, members: readonly string[]): Multiagent {\n const roster = live?.agents ?? [];\n const already = new Set(roster.flatMap((entry) => (entry.type === \"agent\" ? [entry.id] : [])));\n const joining = members.filter((id) => !already.has(id)).map((id) => ({ type: \"agent\" as const, id }));\n return { type: \"coordinator\", board: true, agents: [...roster, ...joining] };\n}\n\n/** One line, handled like any other agent: `created` as CEO, `updated` when the crew joins its roster, else `unchanged`. */\nasync function ensureOrchestrator(client: VettaClient, existing: Agent[], members: readonly string[], dryRun: boolean): Promise<ResourceReport> {\n const current = existing.find(isOrchestrator);\n const live = current === undefined ? null : normaliseMultiagent(current.multiagent);\n const team = seated(live, members);\n if (current === undefined) {\n if (dryRun) return { name: CEO_LABEL, action: \"created\" };\n const model = (await client.models.list({ window: \"immediate\", limit: 1 })).data[0];\n if (model === undefined) throw new BlueprintRefusal(\"no model is served, so the board's owner cannot be created\");\n const made = await client.agents.create({\n name: CEO_LABEL,\n harness: \"pi\",\n model: model.id,\n description: CEO_DETAIL,\n budget: CEO_BUDGET,\n metadata: { role: ORCHESTRATOR_MARKER },\n multiagent: team,\n });\n return { name: CEO_LABEL, action: \"created\", id: made.id };\n }\n if (live !== null && !changed(team, live)) return { name: current.name, action: \"unchanged\", id: current.id };\n if (!dryRun) await client.agents.update(current.id, { multiagent: team });\n return { name: current.name, action: \"updated\", id: current.id };\n}\n\n/**\n * The owner's line joins `agents`; one line per task joins `tasks`. Cards are written one after\n * another in dependency order because a card's `blocked_by` carries the ids the earlier creates\n * answered. `created` or `unchanged` is read off the board: the card's id was, or was not, on it\n * before this apply wrote. A dry run plans every card as `created` — a card carries no key on the\n * wire, so which ones a re-apply would find is only known by writing.\n */\nexport async function seedTasks(\n client: VettaClient,\n config: Readonly<ProjectConfig>,\n existing: Agent[],\n agents: ResourceReport[],\n dryRun: boolean,\n into: ResourceReport[],\n skipped: string[],\n): Promise<void> {\n const members = agents.flatMap((one) => (one.id === undefined ? [] : [one.id]));\n const owner = await line(CEO_LABEL, () => ensureOrchestrator(client, existing, members, dryRun));\n agents.push(owner);\n const board = owner.action === \"refused\" || dryRun || owner.id === undefined ? null : await client.board.create(owner.id);\n const before = board === null ? [] : await listAll(client.config, `/v1/boards/${board.id}/cards`, BoardCardSchema, skipped);\n const known = new Set(before.map((card) => card.id));\n const ids = new Map<string, string>();\n for (const task of inDependencyOrder(config.tasks)) {\n into.push(\n await line(task.key, async () => {\n if (owner.action === \"refused\") return { name: task.key, action: \"refused\", reason: `board owner \"${owner.name}\" was refused: ${owner.reason}` };\n const assignee = task.assignee;\n if (assignee !== undefined && !agents.some((one) => one.name === assignee && one.action !== \"refused\")) {\n return { name: task.key, action: \"refused\", reason: `assignee \"${assignee}\" was not provisioned in this run` };\n }\n if (board === null) return { name: task.key, action: \"created\" };\n const blockers = task.blocked_by ?? [];\n const unmet = blockers.find((key) => !ids.has(key));\n if (unmet !== undefined) return { name: task.key, action: \"refused\", reason: `blocked_by \"${unmet}\" was not seeded in this run` };\n const card = await client.board.cards.create(board.id, {\n key: `${config.name}:${task.key}`,\n title: task.title,\n body: task.body,\n assignee,\n blocked_by: blockers.map((key) => ids.get(key)!),\n });\n ids.set(task.key, card.id);\n // The title and the seat ride the line: `name` is the key a re-apply matches on, and the\n // dashboard's opening message needs the words the board actually shows (§29.6).\n return {\n name: task.key,\n action: known.has(card.id) ? \"unchanged\" : \"created\",\n id: card.id,\n title: task.title,\n ...(assignee === undefined ? {} : { assignee }),\n };\n }),\n );\n }\n}\n","/**\n * Vaults in `naive up` (ADR-0356): upsert by `display_name` from one list (no by-name route, no\n * update route — `identity` is fixed at create), then credentials by **presence** on\n * `(kind, key, host / mcp_server_url)`. Values are write-only and rows immutable (§23), so a live\n * credential is `unchanged`, a missing one is created from the author's shell, and nothing live is\n * ever deleted or overwritten here; rotation stays create-new + delete-old on the platform.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport type { Vault, VaultCredential } from \"@vetta/core\";\nimport type { CredentialDecl, VaultDecl } from \"./define\";\nimport type { ResourceReport } from \"./report\";\n\n/**\n * Vaults have no update route, so `identity` is fixed at create: a live vault held by another\n * identity is refused rather than silently kept, the way an app's `type` is.\n */\nexport async function upsertVault(\n client: VettaClient,\n decl: VaultDecl,\n existing: Vault[],\n identityIds: Map<string, string>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n const identityId = decl.identity === undefined ? undefined : identityIds.get(decl.identity);\n if (decl.identity !== undefined && identityId === undefined && !dryRun) {\n return { name: decl.name, action: \"refused\", reason: `identity needs \"${decl.identity}\", which was not provisioned in this run` };\n }\n const current = existing.find((vault) => vault.display_name === decl.name);\n if (!current) {\n if (dryRun) return { name: decl.name, action: \"created\" };\n const created = await client.vaults.create({\n display_name: decl.name,\n ...(identityId !== undefined ? { identity_id: identityId } : {}),\n });\n return { name: decl.name, action: \"created\", id: created.id };\n }\n if (identityId !== undefined && current.identity_id !== identityId) {\n return {\n name: decl.name,\n action: \"refused\",\n id: current.id,\n reason: `vault \"${decl.name}\" belongs to another identity and that cannot change; remove it or declare the identity it has`,\n };\n }\n return { name: decl.name, action: \"unchanged\", id: current.id };\n}\n\n/**\n * Presence, not drift: with no readable value and no update route, a live row with the declared\n * (kind, key, host / mcp_server_url) *is* the credential. The value is read from the author's\n * shell only when a create is due, and an unset variable refuses that one credential — naming the\n * variable, never a value.\n */\nexport async function upsertCredential(\n client: VettaClient,\n vault: ResourceReport,\n decl: CredentialDecl,\n existing: VaultCredential[],\n dryRun: boolean,\n from: Record<string, string | undefined>,\n): Promise<ResourceReport> {\n const name = `${vault.name} / ${decl.key}`;\n if (vault.action === \"refused\") throw new Error(`vault \"${vault.name}\" was not provisioned in this run`);\n const current = existing.find(\n (row) =>\n row.kind === decl.kind &&\n row.key === decl.key &&\n row.host === (decl.host ?? null) &&\n row.mcp_server_url === (decl.mcp_server_url ?? null),\n );\n if (current) return { name, action: \"unchanged\", id: current.id };\n // `from`, NOT `process.env` — the same environment `apps.ts` resolves an app's `{ from_env }`\n // against, and for a stronger reason. In a Worker, `nodejs_compat` populates `process.env` from\n // the deploy's OWN vars and secrets, so a hosted apply reading it would resolve\n // `{ from_env: \"OPENROUTER_API_KEY\" }` to the PLATFORM's key and write it into a customer's vault\n // as their credential. On a laptop `from` is the author's shell and nothing changes.\n const value = from[decl.value.from_env];\n if (value === undefined) throw new Error(`credential ${decl.key} reads local variable ${decl.value.from_env}, which is not set`);\n if (dryRun || vault.id === undefined) return { name, action: \"created\" };\n const created = await client.vaults.credentials.create(vault.id, {\n kind: decl.kind,\n key: decl.key,\n value,\n ...(decl.host !== undefined ? { host: decl.host } : {}),\n ...(decl.mcp_server_url !== undefined ? { mcp_server_url: decl.mcp_server_url } : {}),\n });\n return { name, action: \"created\", id: created.id };\n}\n","/**\n * An identity's wallets in `naive up` (`canonical-spec §44.5`): each declaration IS\n * `POST /v1/identities/{id}/wallet`'s body and names one network (the testnet when it does not).\n * Created if absent on that network, its policy PATCHed when a declared cap differs, and nothing\n * else — `up` never funds, freezes or sweeps a wallet, and the persona's wallet on the other\n * network is never read or touched (money may be sitting in it).\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { DEFAULT_WALLET_NETWORK, type CreateWallet, type WalletPolicy } from \"@vetta/core\";\nimport { absent, changed } from \"./report\";\nimport type { ResourceReport } from \"./report\";\n\nconst declaredPolicy = (decl: CreateWallet, live: WalletPolicy): Partial<WalletPolicy> =>\n Object.fromEntries(\n Object.entries(decl.policy ?? {}).filter(([key, value]) => value !== undefined && changed(value, live[key as keyof WalletPolicy])),\n );\n\n/** `Ava / wallet` for the testnet one; a mainnet declaration carries its network so the two rows read apart. */\nexport const walletName = (identity: string, decl: CreateWallet): string =>\n decl.network === undefined || decl.network === DEFAULT_WALLET_NETWORK ? `${identity} / wallet` : `${identity} / wallet ${decl.network}`;\n\nexport async function reconcileWallet(\n client: VettaClient,\n identity: { name: string; id: string | undefined },\n decl: CreateWallet,\n dryRun: boolean,\n): Promise<ResourceReport> {\n const name = walletName(identity.name, decl);\n const network = decl.network ?? DEFAULT_WALLET_NETWORK;\n if (identity.id === undefined) {\n if (dryRun) return { name, action: \"created\" };\n return { name, action: \"refused\", reason: `identity \"${identity.name}\" was not provisioned in this run` };\n }\n const current = await absent(client.identities.wallet.get(identity.id, { network }));\n if (!current) {\n if (dryRun) return { name, action: \"created\" };\n const created = await client.identities.wallet.create(identity.id, decl);\n return { name, action: \"created\", id: created.id };\n }\n const patch = declaredPolicy(decl, current.policy);\n if (Object.keys(patch).length === 0) return { name, action: \"unchanged\", id: current.id };\n if (current.status !== \"active\") {\n return { name, action: \"refused\", id: current.id, reason: `wallet is ${current.status}; unfreeze it on the platform before changing its policy` };\n }\n if (!dryRun) await client.identities.wallet.updatePolicy(identity.id, patch, { network });\n return { name, action: \"updated\", id: current.id };\n}\n","/**\n * ONE TEMPLATE, TWICE IN ONE ORGANIZATION (`canonical-spec §29.6`, ADR-1104).\n *\n * Everything `up()` provisions is keyed by name in the organization, and ADR-0785 refuses a name\n * another project holds — so a second install of a template found every agent taken and hired no\n * one. An install that must share the organization with those names takes its own: every agent,\n * app, identity and vault name, and every reference to one, starts with the install's prefix. The\n * API decides the prefix once, when the install row is created, and passes it here on every apply.\n *\n * `config.name` becomes the install's `project`, so app ownership (ADR-0375), `NAIVE_PROJECT` and\n * the board's card keys (`<project>:<key>`) are the install's own and never another install's.\n *\n * Prose is not rewritten. A system prompt that says \"hand the script to the editor\" still says it;\n * the agent is told, in one generated line at the end of its `system`, what each name is here.\n */\nimport type { AgentDecl, ProjectConfig } from \"./define\";\nimport { hasRoster } from \"./roster\";\n\n/**\n * The config an install with `prefix` applies. `\"\"` renames nothing and only files it under `project`.\n * Skills stay shared by slug, so no install's `removed` deletes one another install's crew runs.\n */\nexport function scoped(config: Readonly<ProjectConfig>, prefix: string, project: string): ProjectConfig {\n const removed = { ...config.removed, skills: [] };\n if (prefix === \"\") return { ...config, name: project, removed };\n const as = (name: string): string => prefix + name;\n const apps = new Set(config.apps.map((app) => app.name));\n // An app's MCP tools are `<app>.<tool>` (§29.5); an app name is a DNS label, so it has no dot.\n const tool = (key: string): string => {\n const app = key.split(\".\")[0] ?? \"\";\n return key.includes(\".\") && apps.has(app) ? as(key) : key;\n };\n const team = teamLine(config, as);\n const agent = (decl: AgentDecl): AgentDecl => ({\n ...decl,\n name: as(decl.name),\n system: decl.system === undefined ? team : `${decl.system}\\n\\n${team}`,\n ...(decl.tools === undefined\n ? {}\n : { tools: { ...decl.tools, configs: Object.fromEntries(Object.entries(decl.tools.configs).map(([key, one]) => [tool(key), one])) } }),\n ...(decl.allowed_apps === undefined ? {} : { allowed_apps: decl.allowed_apps.map(as) }),\n ...(decl.identity === undefined ? {} : { identity: as(decl.identity) }),\n ...(Array.isArray(decl.handoffs) ? { handoffs: decl.handoffs.map(as) } : {}),\n ...(hasRoster(decl.multiagent)\n ? { multiagent: { ...decl.multiagent, agents: decl.multiagent.agents.map((one) => (one.type === \"agent\" ? { ...one, name: as(one.name) } : one)) } }\n : {}),\n ...(decl.schedules === undefined\n ? {}\n : { schedules: decl.schedules.map((one) => (one.identity === undefined ? one : { ...one, identity: as(one.identity) })) }),\n });\n return {\n ...config,\n name: project,\n identities: config.identities.map((one) => ({ ...one, name: as(one.name) })),\n vaults: config.vaults.map((one) => ({ ...one, name: as(one.name), ...(one.identity === undefined ? {} : { identity: as(one.identity) }) })),\n apps: config.apps.map((one) => ({ ...one, name: as(one.name) })),\n agents: config.agents.map(agent),\n tasks: config.tasks.map((one) => (one.assignee === undefined ? one : { ...one, assignee: as(one.assignee) })),\n removed: {\n ...removed,\n apps: config.removed.apps.map(as),\n agents: config.removed.agents.map(as),\n identities: config.removed.identities.map(as),\n vaults: config.removed.vaults.map(as),\n },\n kept: { agents: config.kept.agents.map(as) },\n };\n}\n\n/** The one line each agent is told: what every crew member and app of the template is called here. */\nfunction teamLine(config: Readonly<ProjectConfig>, as: (name: string) => string): string {\n const names = [\n ...config.agents.map((one) => `${one.name} is ${as(one.name)}`),\n ...config.apps.map((one) => `the app ${one.name} is ${as(one.name)} (its tools are ${as(one.name)}.*)`),\n ];\n return `Your team's names here: ${names.join(\"; \")}.`;\n}\n"],"mappings":";AAqGA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,KAAK,aAAa,KAAK;AAkC/D,SAAS,KAAK,QAAkB,OAAwB;AAC7D,QAAMA,QAAO,GAAG,MAAM;AACtB,MAAI,CAAC,MAAM,WAAWA,KAAI,EAAG,QAAO;AACpC,SAAO,eAAe,KAAK,MAAM,MAAMA,MAAK,MAAM,EAAE,YAAY,CAAC;AACnE;;;AC/HA,IAAM,QAAQ;AAAA,EACZ,oBAAoB,CAAC,mBAAmB,GAAG;AAAA,EAC3C,mBAAmB,CAAC,mBAAmB,GAAG;AAAA,EAC1C,cAAc,CAAC,kBAAkB,GAAG;AAAA,EACpC,WAAW,CAAC,cAAc,GAAG;AAAA,EAC7B,WAAW,CAAC,aAAa,GAAG;AAAA;AAAA,EAE5B,oBAAoB,CAAC,mBAAmB,GAAG;AAAA,EAC3C,iBAAiB,CAAC,SAAS,GAAG;AAAA,EAC9B,sBAAsB,CAAC,SAAS,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,uBAAuB,CAAC,SAAS,GAAG;AAAA,EACpC,kBAAkB,CAAC,YAAY,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlC,eAAe,CAAC,YAAY,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ/B,mBAAmB,CAAC,YAAY,GAAG;AAAA,EACnC,sBAAsB,CAAC,YAAY,GAAG;AAAA;AAAA;AAAA;AAAA;AAA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;AAAA,IACZ,GAAG,OAAO,OAAO,IAAI,CAAC,QAAQ,GAAG,IAAI,IAAI,OAAO,GAAG,IAAI,IAAI,CAAC,EAAE;AAAA,IAC9D,GAAG,OAAO,KAAK,IAAI,CAAC,QAAQ,WAAW,IAAI,IAAI,OAAO,GAAG,IAAI,IAAI,CAAC,mBAAmB,GAAG,IAAI,IAAI,CAAC,KAAK;AAAA,EACxG;AACA,SAAO,2BAA2B,MAAM,KAAK,IAAI,CAAC;AACpD;","names":["head","message","message","z","z","z","z","z","z","z","z","message","z","z","z","z","z","z","z","z","z","z","z","z","z","message","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","Count","sources","spec","refuse","message","element","z","z","z","z","z","z","z","z","z","Day","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","encoder","z","z","z","words","z","line","z","list","message","message","readFileSync","join","createHash","readFileSync","resolve","createHash","resolve","readFileSync","readdirSync","join","resolve","applied","createHash","resolve","tree","values","note","scoped","row","resolve","readFileSync","createHash","latest","report","line","scoped"]}
|
|
1
|
+
{"version":3,"sources":["../../core/src/id.ts","../../core/src/errors.ts","../../core/src/money.ts","../../core/src/schema/audit-actions.ts","../../core/src/schema/common.ts","../../core/src/schema/harness.ts","../../core/src/schema/agent.ts","../../core/src/schema/browser.ts","../../core/src/schema/org.ts","../../core/src/schema/model-selection.ts","../../core/src/schema/session.ts","../../core/src/schema/social.ts","../../core/src/schema/event.ts","../../core/src/schema/board.ts","../../core/src/schema/identity.ts","../../core/src/schema/resource.ts","../../core/src/schema/files-library.ts","../../core/src/schema/comms.ts","../../core/src/schema/app.ts","../../core/src/schema/install.ts","../../core/src/schema/blueprint.ts","../../core/src/schema/mini-app.ts","../../core/src/schema/show.ts","../../core/src/schema/catalog.ts","../../core/src/schema/vault.ts","../../core/src/schema/handoff.ts","../../core/src/schema/compose.ts","../../core/src/schema/media.ts","../../core/src/schema/app-data.ts","../../core/src/schema/stock-photo.ts","../../core/src/schema/creator.ts","../../core/src/schema/legal.ts","../../core/src/schema/wallet.ts","../../core/src/schema/cards.ts","../../core/src/schema/proxy-trace.ts","../../core/src/schema/review.ts","../../core/src/schema/ads.ts","../../core/src/session-token.ts","../../core/src/logo-svg.ts","../../core/src/brand-kit.ts","../../core/src/file-url.ts","../src/define.ts","../src/roster.ts","../src/report.ts","../src/load.ts","../src/files.ts","../src/up.ts","../src/apps.ts","../src/buckets.ts","../src/migrations.ts","../src/agents.ts","../src/reconcile-cards.ts","../src/reconcile-legal.ts","../src/tasks.ts","../src/vaults.ts","../src/reconcile-wallet.ts","../src/scoped.ts"],"sourcesContent":["/** Identifiers — one prefix per type, `prefix_` + Crockford base32 (canonical-spec §2). */\n\nexport type IdPrefix =\n | \"org\"\n | \"usr\"\n | \"key\"\n | \"agt\"\n | \"ses\"\n | \"evt\"\n | \"cmp\"\n | \"skl\"\n | \"fil\"\n | \"dep\"\n | \"whk\"\n | \"run\"\n | \"led\"\n | \"snp\"\n | \"vol\"\n | \"whd\"\n | \"aud\"\n /** Computer workspace (`canonical-spec §41`): one recorded command, one managed browser session. */\n | \"cmd\"\n | \"brw\"\n /**\n * P2 identity (`canonical-spec §22`–`§25`): a persona an agent acts as, a vault bound to it and one\n * credential in that vault, and the persona's endpoints — a domain, an email inbox, a phone\n * number, an inbound message, and one it sent (§24.1, ADR-1076).\n */\n | \"idn\"\n | \"vlt\"\n | \"vcr\"\n | \"dom\"\n | \"eml\"\n | \"pho\"\n | \"inb\"\n | \"out\"\n /**\n * The team board (`canonical-spec §28`): one board per coordinator session, a card on it, and one\n * comment on a card.\n */\n | \"brd\"\n | \"crd\"\n | \"bcm\"\n /** Support surface (`apps/central`): a ticket and one message on it. Not control-plane objects. */\n | \"tkt\"\n | \"spm\"\n /** Apps (`canonical-spec §29`): a hosted web application and one deployment of it. */\n | \"app\"\n | \"apd\"\n /** One applied blueprint declaration, per organization and project (`canonical-spec §29.6`). */\n | \"bpi\"\n /** A video clipping job (`canonical-spec §30`). */\n | \"clj\"\n /**\n * One published blueprint artifact (`canonical-spec §31`): the built tree of one blueprint ×\n * template × released version. The only id here that names a row belonging to no organization.\n */\n | \"bpa\"\n // core-gaps: contracts (`canonical-spec §32–§37`)\n /** An async media job — video, clip, transcription (§33, D5). */\n | \"med\"\n /** One open managed browser, one saved login (identity-scoped, D4), one grant on it (§32.1). */\n | \"brw\"\n | \"bct\"\n | \"bgr\"\n /** One migration applied to an app's own database (§37.1). */\n | \"dbm\"\n /**\n * The creator program (`canonical-spec §42`): a creator, an application to become one, a referred\n * organization, one commission, one payout, and a creator template. Like `bpa`, rows belonging\n * to no organization; a template *version* has no id and is keyed `(template, version)`.\n */\n | \"crt\"\n | \"cra\"\n | \"crf\"\n | \"crc\"\n | \"crp\"\n | \"ctp\"\n /** A budget hold. Internal only: it is never a field on any wire object (`canonical-spec §2`). */\n | \"res\"\n /** One priced tool call. Internal only, and the settlement's idempotency key (`§11`, ADR-0272). */\n | \"tol\"\n /**\n * Identity-owned legal, wallet and cards (`canonical-spec §43`–`§45`): a verification and one of\n * its members, a company and one of its documents; a wallet and one transaction; a card and one\n * logged card transaction.\n */\n | \"lgv\"\n | \"lgm\"\n | \"lgc\"\n | \"lgd\"\n | \"wlt\"\n | \"wtx\"\n | \"vcd\"\n | \"vct\"\n /** A person's verdict on agent work given outside the approval box (`canonical-spec §47`). */\n | \"rev\"\n /** Not a stored object: the per-request id echoed in `x-request-id` and every envelope (§3). */\n | \"req\";\n\n/** Crockford base32, lowercase on the wire. Decoding is case-insensitive (i/l/o/u excluded). */\nconst ALPHABET = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst SUFFIX_LENGTH = 26;\nconst SUFFIX_PATTERN = new RegExp(`^[${ALPHABET}]{${SUFFIX_LENGTH},}$`);\n\n/** `${prefix}_` + 26 random Crockford base32 chars (130 bits). */\nexport function newId(prefix: IdPrefix): string {\n return idFromBytes(prefix, crypto.getRandomValues(new Uint8Array(SUFFIX_LENGTH)));\n}\n\n/**\n * `${prefix}_` + one Crockford char per byte of `bytes` (at least 26). Deterministic: the same\n * bytes name the same id, which is how a retried `Idempotency-Key` names the same `med_` job.\n */\nexport function idFromBytes(prefix: IdPrefix, bytes: Uint8Array): string {\n if (bytes.length < SUFFIX_LENGTH) throw new Error(`an id needs ${SUFFIX_LENGTH} bytes`);\n let suffix = \"\";\n for (const byte of bytes.subarray(0, SUFFIX_LENGTH)) suffix += ALPHABET[byte & 31];\n return `${prefix}_${suffix}`;\n}\n\n/**\n * The same shape, **derived** rather than drawn: one seed always names one id.\n *\n * For work that can be redone — a render collected again because the wake that collected it died\n * before it could say so — a random id makes the retry a second object with a second row. Deriving\n * the id from the work's own idempotency key makes the retry name what is already there, so the\n * upsert behind it lands once and the bytes overwrite themselves (ADR-0514).\n */\nexport async function derivedId(prefix: IdPrefix, seed: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(seed));\n let suffix = \"\";\n for (const byte of new Uint8Array(digest, 0, SUFFIX_LENGTH)) suffix += ALPHABET[byte & 31];\n return `${prefix}_${suffix}`;\n}\n\n/** True when `value` is a well-formed id of exactly this prefix (aliases such as `agent_` fail). */\nexport function isId(prefix: IdPrefix, value: string): boolean {\n const head = `${prefix}_`;\n if (!value.startsWith(head)) return false;\n return SUFFIX_PATTERN.test(value.slice(head.length).toLowerCase());\n}\n","/** The one error envelope and the one code taxonomy (canonical-spec §3). */\n\nexport type ErrorType =\n | \"invalid_request\"\n | \"authentication\"\n | \"permission\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limit\"\n | \"quota\"\n | \"api_error\"\n | \"not_implemented\";\n\n/** Every P1 code, with its coarse `type` and HTTP status. Adding one is a spec change. */\nconst CODES = {\n window_unavailable: [\"invalid_request\", 400],\n validation_failed: [\"invalid_request\", 400],\n unauthorized: [\"authentication\", 401],\n forbidden: [\"permission\", 403],\n not_found: [\"not_found\", 404],\n /** The path exists; the method does not. The response carries `Allow` (§3). */\n method_not_allowed: [\"invalid_request\", 405],\n budget_exceeded: [\"quota\", 402],\n insufficient_credits: [\"quota\", 402],\n /**\n * The organization holds no active plan, so it may not be used. `402`, alongside the other two\n * money codes, because the remedy is a payment — not `403`, which reads as \"your credential is\n * wrong\" and would send a customer to rotate a perfectly good key. Distinct from\n * `insufficient_credits`: that one means \"fund the balance\", this one means \"start the plan\".\n */\n subscription_required: [\"quota\", 402],\n version_conflict: [\"conflict\", 409],\n /**\n * The name is taken by a resource another project owns, and the request did not ask to take it\n * (ADR-0375). Nothing existing fits: `validation_failed` says the request is malformed and it is\n * not, `forbidden` reads as \"your credential is wrong\" and sends a customer to rotate a good key,\n * and `version_conflict` means optimistic concurrency.\n */\n name_conflict: [\"conflict\", 409],\n /**\n * A shared declaration moved underneath the applier: the install's `revision` is not the\n * `expected_revision` the apply carried (`§29.6`). Not `version_conflict`, which is one\n * immutable-versioned object's optimistic concurrency and whose remedy is to re-read that\n * object — this one carries a set of drifted PATHS and its remedy is a merge, and a client that\n * cannot tell them apart shows a config diff for a stale agent version.\n */\n revision_conflict: [\"conflict\", 409],\n idempotency_conflict: [\"conflict\", 409],\n /**\n * A lifecycle action asked of an object whose status does not admit it (§43–§45): forming a\n * company on an unverified verification, funding a `frozen` wallet, cancelling a card that is not\n * `active`. Not `version_conflict` — nothing raced; the remedy is to read the status.\n */\n state_conflict: [\"conflict\", 409],\n session_running: [\"conflict\", 409],\n session_terminal: [\"conflict\", 409],\n computer_unavailable: [\"conflict\", 409],\n /**\n * Two P2 additions (ADR-0118). Both mean \"not an error — retry later\", and no existing code\n * carries that: `feature_not_configured` is permanent, `computer_unavailable` is about a\n * sandbox, and `validation_failed` would tell a durable runtime to give up on something that\n * will succeed once verification or carrier approval clears.\n */\n job_not_ready: [\"conflict\", 409],\n compliance_pending: [\"conflict\", 409],\n // core-gaps: contracts (`canonical-spec §32`, §37; ADR-0448)\n /** `--app` omitted and the org has more than one fullstack app to resolve it to (§37.2). */\n ambiguous_app: [\"conflict\", 409],\n /** A saved browser login is held by a human-login flow for the next 15 minutes (§32.6). */\n context_locked: [\"conflict\", 409],\n rate_limited: [\"rate_limit\", 429],\n feature_not_configured: [\"not_implemented\", 501],\n internal_error: [\"api_error\", 500],\n /**\n * A configured upstream answered with a failure of its own — a 5xx, or a browser automation that\n * did nothing (§32.5). Not `internal_error`: the remedy is a retry, and nothing of ours broke.\n */\n provider_error: [\"api_error\", 502],\n} as const satisfies Record<string, readonly [ErrorType, number]>;\n\nexport type ErrorCode = keyof typeof CODES;\n\nexport interface ErrorEnvelope {\n error: {\n type: ErrorType;\n code: ErrorCode;\n message: string;\n request_id: string;\n param?: string;\n };\n}\n\n/** How much of an error's own words one log line may carry (`faultOf`). */\nconst FAULT_MAX_CHARS = 2_000;\n\n/**\n * One error, as one **operator log line**. Never a customer-facing message — that is `toEnvelope` —\n * and never the error *object*.\n *\n * WHY NOT `console.error(prefix, error)`, which is what this replaces. Handed the object, the\n * runtime serialises whatever the thrower hung on it: a vendor client's `response`, `request` or\n * `config`, and with them the `authorization` header that carried our key (`CLAUDE.md §2`). It also\n * loses the one part worth reading — in production a media job failed every seven seconds for hours\n * and the captured line held stack frames with no message at all (ADR-0733). A derived string is\n * both safer and more legible.\n *\n * WHAT IS SAFE HERE is the same judgement `media-openrouter/src/wire.ts` already makes: that adapter\n * repeats a failed call's **status** and never its **body**, precisely because a body may quote the\n * request. So a vendor body never becomes a `message` in the first place, and a `message` is already\n * held repeatable — `providerFailure` puts an arbitrary `Error.message` into a *customer-facing*\n * `VettaError`. The cap is the backstop for the message we did not author.\n *\n * The name and the message are guaranteed rather than left to the stack: a `DOMException` carries its\n * whole answer in its name, and a workerd stack does not always repeat either of them — which is\n * exactly how the production line came out with frames and no reason at all.\n */\nexport function faultOf(error: unknown): string {\n if (!(error instanceof Error)) return `a non-Error ${typeof error} was thrown`;\n const head = `${error.name}: ${error.message}`;\n const stack = error.stack ?? \"\";\n const cause =\n error.cause instanceof Error\n ? ` | caused by ${error.cause.name}: ${error.cause.message}`\n : \"\";\n const body = stack.startsWith(head) ? stack : `${head}\\n${stack}`.trimEnd();\n // THE CAUSE IS RESERVED ITS ROOM BEFORE THE BODY SPENDS IT. Capping `body + cause` as one string\n // drops from the END, and the end is the cause — so on the one shape that most needs it, a\n // bundled worker's stack (every frame a one-line `index.js:1:NNNNN`, thousands of characters\n // before the first word of ours), the most diagnostic half was the first thing lost. The cause is\n // itself capped at half the line so that neither half can crowd the other out entirely: a real\n // cause is tens of characters and survives whole, and one long enough to be a payload still\n // leaves `head` and the top frames legible. The total is `FAULT_MAX_CHARS` either way.\n const room = cause.slice(0, FAULT_MAX_CHARS / 2);\n return `${body.slice(0, FAULT_MAX_CHARS - room.length)}${room}`;\n}\n\n/** The only error thrown across a boundary. SDKs subclass on `type`, branch on `code`. */\nexport class VettaError extends Error {\n readonly type: ErrorType;\n readonly code: ErrorCode;\n readonly httpStatus: number;\n readonly param: string | undefined;\n\n constructor(code: ErrorCode, message: string, param?: string) {\n super(message);\n this.name = \"VettaError\";\n const [type, httpStatus] = CODES[code];\n this.type = type;\n this.code = code;\n this.httpStatus = httpStatus;\n this.param = param;\n }\n\n toEnvelope(requestId: string): ErrorEnvelope {\n return {\n error: {\n type: this.type,\n code: this.code,\n message: this.message,\n request_id: requestId,\n ...(this.param === undefined ? {} : { param: this.param }),\n },\n };\n }\n}\n","/** Money — integer micro-USD everywhere on the wire and in storage (canonical-spec §1). */\n\nimport { VettaError } from \"./errors\";\n\nexport type MicroUsd = number & { readonly __brand: \"MicroUsd\" };\n\n/** 1 USD = 1_000_000 micro-USD. */\nexport const USD = 1_000_000;\n\nconst DECIMAL_USD = /^-?\\d+(?:\\.\\d+)?$/;\n\nfunction invalid(message: string): never {\n throw new VettaError(\"validation_failed\", message);\n}\n\n/** Brand a number as micro-USD. Rejects anything that is not a safe integer. */\nexport function microUsd(value: number): MicroUsd {\n if (!Number.isSafeInteger(value)) invalid(`micro-USD must be an integer within range, got ${value}`);\n return value as MicroUsd;\n}\n\nfunction fromBigInt(value: bigint): MicroUsd {\n if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {\n invalid(`micro-USD amount out of range: ${value}`);\n }\n return microUsd(Number(value));\n}\n\n/**\n * Decimal USD string -> integer micro-USD, rounding half-up (ties away from zero) exactly once.\n * `\"2.00\"` -> `2_000_000`. Clients convert here; a float dollar never reaches the wire.\n */\nexport function microFromDecimalString(usd: string): MicroUsd {\n const text = usd.trim();\n if (!DECIMAL_USD.test(text)) invalid(`not a decimal USD amount: ${usd}`);\n const negative = text.startsWith(\"-\");\n const [whole = \"0\", fraction = \"\"] = (negative ? text.slice(1) : text).split(\".\");\n const digits = fraction.padEnd(7, \"0\");\n let micro = BigInt(whole) * BigInt(USD) + BigInt(digits.slice(0, 6));\n if (Number(digits[6]) >= 5) micro += 1n;\n return fromBigInt(negative ? -micro : micro);\n}\n\n/** Integer micro-USD -> decimal USD string, for display only. Round-trips exactly. */\nexport function decimalStringFromMicro(amount: MicroUsd): string {\n const absolute = BigInt(Math.abs(amount));\n const fraction = (absolute % BigInt(USD))\n .toString()\n .padStart(6, \"0\")\n .replace(/0+$/, \"\")\n .padEnd(2, \"0\");\n return `${amount < 0 ? \"-\" : \"\"}${absolute / BigInt(USD)}.${fraction}`;\n}\n\nexport function addMicro(a: MicroUsd, b: MicroUsd): MicroUsd {\n return fromBigInt(BigInt(a) + BigInt(b));\n}\n\nexport function subMicro(a: MicroUsd, b: MicroUsd): MicroUsd {\n return fromBigInt(BigInt(a) - BigInt(b));\n}\n","/**\n * The audit action vocabulary (`canonical-spec.md §17`, PRODUCTION-READINESS #18).\n *\n * The compliance claim is \"every control-plane mutation is attributed to a principal and filed\".\n * Before this file the vocabulary held 11 P1 actions and zero P2 ones, so creating an agent, a\n * computer, a file, a webhook or a deployment — and the whole identity-and-credentials half of the\n * product — left no trace at all. A log that is trusted and incomplete is worse than no log.\n *\n * Two rules keep this list honest:\n * 1. **Never re-spell an action that has already been written.** Rows exist in customers' logs and\n * `?action=` filters exist in their queries. `agent.rolled_back` is therefore kept as a\n * deprecated alias of `agent.rollback` rather than renamed away.\n * 2. **Every action here is claimed by a route** in `coverage.ts`, and every mutating route either\n * claims an action or is listed there as deliberately unfiled. The gate proves both.\n */\n\n/** Actions already written by the deploy of 2026-08-22. Removing or re-spelling one breaks a query. */\nexport const AUDIT_ACTIONS_SHIPPED = [\n \"agent.updated\",\n \"agent.rolled_back\", // deprecated alias of `agent.rollback`; kept so historic rows still validate\n \"api_key.created\",\n \"api_key.rotated\",\n \"api_key.revoked\",\n \"member.role_changed\",\n \"member.removed\",\n \"policy.denied\",\n \"credits.topped_up\",\n \"webhook.secret_rotated\",\n \"session.interrupted\",\n] as const;\n\n/** P1: the control plane a customer pays for and an auditor asks about first. */\nexport const AUDIT_ACTIONS_P1 = [\n \"agent.created\",\n \"agent.deleted\",\n \"agent.rollback\",\n \"computer.created\",\n \"computer.deleted\",\n \"computer.paused\",\n \"computer.resumed\",\n \"computer.snapshot_created\",\n \"computer.updated\",\n \"computer.taken_over\",\n \"computer.handed_back\",\n \"browser.live_view_opened\",\n \"deployment.created\",\n \"deployment.updated\",\n \"deployment.deleted\",\n \"deployment.paused\",\n \"deployment.resumed\",\n \"deployment.run\",\n \"file.created\",\n \"file.published\",\n \"file.deleted\",\n \"member.invited\",\n \"org.updated\",\n \"subscription.updated\",\n \"subscription.canceled\",\n \"subscription.plan_changed\",\n \"session.budget_updated\",\n \"session.cancelled\",\n \"skill.created\",\n \"skill.version_created\",\n \"skill.deleted\",\n \"webhook.created\",\n \"webhook.updated\",\n \"webhook.deleted\",\n] as const;\n\n/** P2: identity and credentials. Not one of these was recorded anywhere before this change. */\nexport const AUDIT_ACTIONS_P2 = [\n \"identity.created\",\n \"identity.updated\",\n \"identity.deleted\",\n \"identity.granted\",\n \"identity.revoked\",\n \"vault.created\",\n \"vault.deleted\",\n \"credential.sealed\",\n \"credential.destroyed\",\n \"connection.created\",\n \"connection.disconnected\",\n \"connection.auth_config_created\",\n \"connection.auth_config_deleted\",\n \"domain.created\",\n \"domain.purchased\",\n \"domain.purchase_refunded\",\n \"domain.verified\",\n \"domain.deleted\",\n \"email.created\",\n \"email.deleted\",\n \"phone.created\",\n \"phone.deleted\",\n \"social.activated\",\n \"social.post_created\",\n \"social.post_deleted\",\n] as const;\n\n/**\n * P3: apps — hosted web applications (`canonical-spec §29`), and the install that applies a\n * declaration across them (§29.6). The install's row is the only trace of *which writer* moved a\n * whole organization's configuration, so it is exactly the kind of mutation §17 exists for.\n */\nexport const AUDIT_ACTIONS_P3 = [\n \"app.created\",\n \"app.updated\",\n \"app.deleted\",\n \"app.deployed\",\n \"app.secret_set\",\n \"app.secret_deleted\",\n \"app.domain_connected\",\n \"app.domain_disconnected\",\n \"app.db_queried\",\n /** A ticket was minted that lets one browser past an app's own operator gate (§29.7). */\n \"app.entered\",\n /** The dashboard password was read — the one audited reveal of an app secret (§29.7, ADR-0656). */\n \"app.access_read\",\n /** The dashboard password was regenerated (and a lost `DASHBOARD_TOKEN` copy repaired). */\n \"app.access_rotated\",\n /** A link was minted that serves one file's bytes to anyone holding it, for seven days (§40). */\n \"file.linked\",\n \"blueprint.installed\",\n /** An install's answers were rewritten — what a template's crew is told about the business (§31.8). */\n \"blueprint.context_updated\",\n /** The one creator-program effect inside a tenant: a new organization attributed to a creator (§42.6). */\n \"referral.attributed\",\n] as const;\n\n/** Identity-owned legal, wallet and cards (`canonical-spec §43.4`, `§44.3`, `§45.3`). */\nexport const AUDIT_ACTIONS_PRIMITIVES = [\n \"ad_campaign.created\",\n \"ad_campaign.activated\",\n \"ad_campaign.paused\",\n \"legal_verification.started\",\n \"legal_member.completed\",\n \"legal_member.link_resent\",\n \"legal_company.created\",\n \"legal_company.submitted\",\n \"wallet.created\",\n \"wallet.policy_updated\",\n \"wallet.frozen\",\n \"wallet.unfrozen\",\n \"wallet.funded\",\n \"wallet.transferred\",\n \"wallet.swept\",\n \"wallet.paid\",\n \"card.issued\",\n \"card.retried\",\n \"card.cancelled\",\n \"card.refunded\",\n /** The one read that files: a credential left the vault for a caller (§45.3). */\n \"card.credentials_revealed\",\n] as const;\n\n// core-gaps: contracts — the mutations §32, §36–§38 make audit rows of (REST passthrough and object\n// puts/gets are audit rows, not stream events).\nexport const AUDIT_ACTIONS_CORE_GAPS = [\n \"browser.context_saved\",\n \"browser.context_granted\",\n \"browser.context_revoked\",\n \"browser.credential_stored\",\n // core-gaps: U2-browser-api — §32.8's session events, audit-only when no session drove them.\n \"browser.session_opened\",\n \"browser.session_closed\",\n \"file.imported\",\n \"app.db_rest\",\n \"app.db_migrated\",\n \"app.bucket_created\",\n \"app.bucket_deleted\",\n \"app.storage_put\",\n \"app.storage_get\",\n // core-gaps: U9-storage\n \"app.storage_deleted\",\n] as const;\n\nexport const AUDIT_ACTIONS = [\n ...AUDIT_ACTIONS_SHIPPED,\n ...AUDIT_ACTIONS_P1,\n ...AUDIT_ACTIONS_P2,\n ...AUDIT_ACTIONS_P3,\n ...AUDIT_ACTIONS_PRIMITIVES,\n ...AUDIT_ACTIONS_CORE_GAPS,\n] as const;\n\nexport type AuditAction = (typeof AUDIT_ACTIONS)[number];\n\n/** `agent.rolled_back` reads as `agent.rollback`; nothing else is aliased. */\nexport const AUDIT_ACTION_ALIASES: Readonly<Record<string, AuditAction>> = {\n \"agent.rolled_back\": \"agent.rollback\",\n};\n\n/** The spelling a filter should match on, collapsing a deprecated alias onto its canonical name. */\nexport function canonicalAction(action: string): string {\n return AUDIT_ACTION_ALIASES[action] ?? action;\n}\n","/** Shared wire primitives — every canonical object is built from these (canonical-spec §§1-2, §9, §11, §17). */\n\nimport { z } from \"zod\";\nimport { AUDIT_ACTIONS } from \"./audit-actions\";\nimport { isId, type IdPrefix } from \"../id\";\n\n/** A string that is a well-formed id of exactly this prefix. */\nexport const idOf = (prefix: IdPrefix): z.ZodString =>\n z.string().refine((value) => isId(prefix, value), { error: `expected a ${prefix}_ id` });\n\n/** RFC 3339 UTC, `_at` suffix on the wire (§9). */\nexport const Timestamp = z.iso.datetime({ offset: true });\n\n/** Integer micro-USD (§1). The `MicroUsd` brand is for arithmetic in `core`; the wire is an integer. */\nexport const MicroUsdField = z.number().int();\n\nexport const Metadata = z.record(z.string(), z.unknown());\n\n/**\n * A JSON Schema document for a session's answer (`output_schema`, §16).\n *\n * Constrained to an object schema with at least one property, because the schema *becomes* the\n * `submit_output` tool's parameters and a tool call's arguments are always a JSON object: a\n * `{\"type\":\"string\"}` schema can never be satisfied by any call, and a `{}` schema is satisfied by\n * everything. Both would end the session with a silent `structured_output: null` (or an empty\n * document) that `structured_output_required` cannot even catch — the exact failure §16 exists to\n * delete. Refuse them at the boundary instead.\n */\nexport const JsonSchemaDocument = z\n .record(z.string(), z.unknown())\n .refine((schema) => schema.type === \"object\", {\n error: 'an output schema must be a JSON Schema with \"type\": \"object\"',\n })\n .refine(\n (schema) =>\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n Object.keys(schema.properties).length > 0,\n { error: \"an output schema must declare at least one property\" },\n );\n\n/** Completion window — these three strings, everywhere (§4). */\nexport const WindowSchema = z.enum([\"immediate\", \"priority\", \"loose\"]);\nexport type Window = z.infer<typeof WindowSchema>;\n\n/** The five metered token tiers (§11). */\nexport const TOKEN_TIERS = [\"input\", \"cache_write\", \"cache_read\", \"output\", \"reasoning\"] as const;\nexport const TokenTierSchema = z.enum(TOKEN_TIERS);\n\n/**\n * The tiers a **non-model** call bills under (§11). `search` is one priced retrieval call, `media`\n * one priced media job — the tier name IS the component on `GET /v1/agents/{id}/spend?by=component`,\n * so these are capability names a customer reads, never vendor names.\n */\n// core-gaps: contracts — `browser` (minutes + hosted actions, §32.8), `storage` (bucket-days, §38.3).\n// `email` is one outbound email send (§11, ADR-0818); `voice` is live voice call minutes (§35.5, ADR-1151).\nexport const TOOL_TIERS = [\"search\", \"media\", \"social\", \"browser\", \"storage\", \"email\", \"voice\"] as const;\nexport type ToolTier = (typeof TOOL_TIERS)[number];\n\n/**\n * Every tier a ledger line item can carry: the five token tiers, the sandbox (`computer`), and the\n * priced tool tiers. `packages/billing` has emitted `computer` since ADR-0160 while this enum still\n * only admitted the five, so a sandbox debit failed validation on `GET /v1/credits/ledger` — the\n * wire schema was narrower than the money the ledger already stored.\n */\nexport const LINE_ITEM_TIERS = [...TOKEN_TIERS, \"computer\", ...TOOL_TIERS] as const;\nexport const LineItemTierSchema = z.enum(LINE_ITEM_TIERS);\nexport type LineItemTier = z.infer<typeof LineItemTierSchema>;\nexport const TokenUsageSchema = z.object({\n input: z.number().int().nonnegative(),\n cache_write: z.number().int().nonnegative(),\n cache_read: z.number().int().nonnegative(),\n output: z.number().int().nonnegative(),\n reasoning: z.number().int().nonnegative(),\n});\nexport type TokenUsage = z.infer<typeof TokenUsageSchema>;\n\n/**\n * The acting actor, threaded through auth → every mutation, audit entry and ledger row (§17).\n *\n * `system` names an effect no API principal caused — a credit reconciled from a verified payment\n * webhook, the initial test-tier grant, a debit committed by the durable loop. Its `id` names the\n * subsystem (`\"payment_webhook\"`, `\"bootstrap\"`), never a stored object (ADR-0065).\n */\nexport const PrincipalSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"user\"), id: idOf(\"usr\") }),\n z.object({ type: z.literal(\"key\"), id: idOf(\"key\") }),\n z.object({ type: z.literal(\"system\"), id: z.string().min(1) }),\n]);\nexport type Principal = z.infer<typeof PrincipalSchema>;\n\n/**\n * The audited actions (§17). The list is `./audit-actions`: one definition, so what the wire\n * validates and what the emitters write cannot diverge.\n */\nexport const AuditActionSchema = z.enum(AUDIT_ACTIONS);\n\n/** Cursor pagination envelope (§9). */\nexport const page = <T extends z.ZodType>(item: T) =>\n z.object({ data: z.array(item), has_more: z.boolean(), next_cursor: z.string().nullable() });\nexport const PAGE_LIMIT_DEFAULT = 20;\nexport const PAGE_LIMIT_MAX = 100;\n\n/** The one supported API version; every surface reads it from here rather than re-declaring it (§9). */\nexport const API_VERSION = \"2026-09-30\";\n\n/**\n * Every `Vetta-Version` date a caller may pin, oldest first (§9). A date outside this list is a\n * typo or a guess, and answering it with a 200 served under some *other* version is exactly the\n * quiet-success class this surface exists to refuse — so `readVersion` 400s on it.\n */\nexport const API_VERSIONS = [\"2026-01-01\", \"2026-09-01\", API_VERSION] as const;\n\n/**\n * From this pin onward the request contract is **strict**: unknown body keys and unknown query\n * parameters are rejected rather than silently dropped (readiness entry 7). Older pins keep the\n * lenient behaviour so a client already sending junk is not broken by a deploy.\n */\nexport const STRICT_REQUEST_VERSION = \"2026-09-01\";\n\n/**\n * From this pin onward a question's fields may be `connect` (ADR-1102) and `media` (ADR-1103). An\n * older pin parses only `text` and `choice`, and strictly: one new field in one parked question\n * threw on its whole session list. So an older pin is served each new field as `text` (ADR-1105).\n */\nexport const QUESTION_KINDS_VERSION = \"2026-09-30\";\n\n/** Published event-replay window (§8). */\nexport const EVENT_RETENTION_HOURS = 72;\n","/**\n * The harness catalog — the one layer a customer selects at agent create (§19).\n *\n * `billing` is how the loop is paid for. `location` is where it can run. Hosted\n * sessions start only a hosted harness; a local one is stored and fails closed.\n */\n\nimport { z } from \"zod\";\n\nexport const HARNESS_IDS = [\"pi\", \"claude_code\", \"vetta\", \"hermes\"] as const;\nexport type HarnessId = (typeof HARNESS_IDS)[number];\n\nexport const HarnessIdSchema = z.enum(HARNESS_IDS);\n\n/**\n * The four facts an admission check can act on **today**, and no more (`CLAUDE.md §3`):\n *\n * - `approvals` — the loop can hold a tool call and wait for a decision on\n * `POST /v1/sessions/{id}/tool_confirmations` (§6). A loop without it cannot serve a toolset\n * whose permission is `ask`.\n * - `structuredOutput` — it can honour `structured_output_required` (§16).\n * - `streamingDeltas` — it emits incremental deltas rather than only a completed message (§8).\n * - `injectedTools` — THE PLATFORM'S TOOLS REACH THIS LOOP'S MODEL. Semantics, not mechanism: it\n * says the team tools (`send_to_agent`, `wait_for_agents`, `list_agents`, `board_read`,\n * `board_write`), an agent's `mcp_servers`, a connected account's tools, the Passport tools,\n * `social`, the app-declared MCP tools and `apps` are all offered to the model, governed by\n * `tools.configs`. There are TWO delivery mechanisms behind that one answer, and a caller should\n * not have to know which:\n * · an IN-ISOLATE loop reads `RuntimePort.runTurn`'s `input.tools` (`harness-pi/src/harness.ts`,\n * `harness-vetta/src/index.ts`);\n * · a PROCESS loop — a CLI in a micro-VM that carries its own toolset and could never read that\n * array — dials the session-scoped MCP bridge, `POST /v1/sandbox/mcp`, with the door token\n * already in its box. Which mechanism a harness uses is `RUNS_AS_A_PROCESS` below, and that\n * is the predicate `apps/runtime-do` gates its decorators on; it is NOT this field.\n * A `false` here is therefore still one fact with the same consequences — a coordinator cannot\n * run on such a loop, because its model would never be shown `send_to_agent` — but no published\n * harness declares it today.\n *\n * A `false` here is what lets a start refuse up front instead of promising behaviour the loop\n * cannot produce — the same fail-closed rule §4 applies to windows. Field names are TS\n * identifiers; the wire spells them `snake_case` like every other object (`code-standards §6`).\n */\nexport interface HarnessCapabilities {\n approvals: boolean;\n structuredOutput: boolean;\n streamingDeltas: boolean;\n injectedTools: boolean;\n}\n\n/**\n * Maturity, not place. `preview` says the loop runs but its contract may still move.\n *\n * `claude_code` is `ga` rather than a third `\"local\"` value: where a harness runs is already\n * `location`, and a `status` that answered the same question would be two fields to keep in\n * agreement — the day one changed, one of them would be wrong.\n */\nexport type HarnessStatus = \"ga\" | \"preview\";\n\n/**\n * WHAT A PARKED SESSION COSTS, WHICH IS NOT THE SAME QUESTION AS WHERE THE LOOP RUNS.\n *\n * `isolate` runs the loop in the session object itself: its workspace is rows in that object's own\n * storage, so a session between turns holds no sandbox and bills storage only. `sandbox` runs the\n * agent as a process on a micro-VM, which the session holds across turns — the same profile `pi`\n * has, and unavoidable for a harness that is a process rather than a loop we host.\n *\n * Published because it is a real difference in what a customer pays for an idle session, and\n * without it they would discover it from a bill rather than from the catalogue.\n */\nexport type HarnessExecution = \"isolate\" | \"sandbox\" | \"local\";\n\n/**\n * WHETHER THE HOSTED RUNTIME HAS A DISPATCHER FOR THIS LOOP — separate from `status`, and from\n * `location`, because it answers a different question: not \"how settled is the contract\" and not\n * \"whose machine runs it\", but \"will a session on it actually run today\".\n *\n * `vetta` is `preview` AND runnable; `hermes` is neither. Without this a session on a loop the\n * runtime refuses is admitted, queued, and then burns the turn engine's five-attempt retry ladder\n * on an error that can never succeed before parking as `failed` — minutes of a customer's time to\n * reach an answer we knew at start.\n */\n\nexport const HARNESSES = {\n pi: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Pi\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"ga\",\n capabilities: {\n approvals: true,\n structuredOutput: true,\n streamingDeltas: true,\n injectedTools: true,\n },\n },\n claude_code: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Claude Code\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /**\n * `approvals` IS THE LOAD-BEARING FALSE. The turn runs with `--permission-mode\n * bypassPermissions`, which is not a preference: measured, without it every tool call in\n * one-shot mode is DENIED outright — not prompted — and the turn still exits 0 having done\n * nothing. So nothing can hold a call for a decision, and `true` here would admit an `ask`\n * toolset and then bypass it in silence, which is the failure the catalogue exists to prevent.\n * `structured_output`: no schema is passed. `streaming_deltas`: the stream carries whole\n * assistant messages, never token deltas.\n *\n * `injectedTools` IS TRUE, AND NOT BECAUSE THE CLI LEARNED TO READ `input.tools` — it still\n * does not, and never will. `harness-claude-code-hosted` writes a per-turn MCP config in the\n * session's folder naming the session-scoped bridge and joins `--mcp-config …\n * --strict-mcp-config` to the command, so the platform's tools reach the model as MCP tools\n * of one server. `tools.configs` still governs them, by the same `server.tool` /\n * `<connector>.<tool>` names: the bridge applies `permissionOf` before it answers\n * `tools/list`, so a `deny` is never emitted and cannot be called. `approvals` staying\n * `false` is what makes an `ask` OMITTED rather than gated — nothing under\n * `bypassPermissions` can hold a call, so omission is the only honest enforcement, and\n * `startSession` still refuses an explicit `ask` toolset here outright.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n vetta: {\n execution: \"isolate\",\n runnable: true,\n label: \"Vetta\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /** `injectedTools`: `index.ts:284` spreads `input.tools` into the toolset it builds. */\n capabilities: {\n approvals: false,\n structuredOutput: true,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n hermes: {\n execution: \"sandbox\",\n runnable: true,\n label: \"Hermes\",\n billing: \"usage\",\n location: \"hosted\",\n status: \"preview\",\n /**\n * BOTH `false`, AND BOTH WERE OPTIMISTIC. `approvals` claimed a gate that does not exist:\n * nothing connects `POST …/tool_confirmations` to the agent's own in-box prompt, and that\n * prompt is now closed with `</dev/null` so it fails immediately and SILENTLY. Declaring\n * `true` admitted an `ask` toolset and then dropped every approval with no event — the exact\n * \"quiet best effort\" the catalogue exists to prevent. `false` refuses such a session at start,\n * naming the field.\n *\n * `streamingDeltas` was true of an earlier invocation. The command now captures the agent's\n * answer and re-emits it as ONE `text` frame (`spec.ts`), because `chat -Q` writes a terminal\n * transcript rather than JSONL — so a caller gets `message.completed`, never a delta.\n *\n * `injectedTools` WAS THE THIRD FALSE AND IS NOW TRUE. It was never declared at all until it\n * had to be: the runtime wrapped this loop in `withTeamTools` like every other, and the five\n * team tools were registered against an adapter that never reads `input.tools`. A coordinator\n * on hermes was admitted, billed, and shown a toolset with no `send_to_agent` in it. The array\n * still goes nowhere — what changed is that `harness-hermes` now writes `$HERMES_HOME/\n * config.yaml` naming the session-scoped bridge (`POST /v1/sandbox/mcp`), so the platform's\n * tools reach the model as MCP tools of one server. `tools.configs` governs them by the same\n * names, because the bridge applies `permissionOf` before answering `tools/list` and a denied\n * tool is never emitted. `approvals` stays `false`, so an `ask` tool is omitted rather than\n * gated — the prompt in the box is closed with `</dev/null` and nothing can hold a call.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: true,\n },\n },\n} as const satisfies Record<\n HarnessId,\n {\n execution: HarnessExecution;\n runnable: boolean;\n label: string;\n billing: \"usage\" | \"account\";\n location: \"hosted\" | \"local\";\n status: HarnessStatus;\n capabilities: HarnessCapabilities;\n }\n>;\n\n/**\n * Harnesses whose AGENT IS A PROCESS IN THE BOX, rather than a loop we host that merely uses one.\n * They need a box whatever the tool policy says, and they need their own image — a stock one has no\n * agent installed on it.\n *\n * It lives beside the table rather than in `apps/api` because it is a fact about the harness, and\n * because the two places that provision a box now sit in different workers: `startSession` for a\n * session a customer starts, and the spawn path for a delegated member with no box to borrow (§28).\n *\n * IT IS ALSO THE MECHANISM GATE. `apps/runtime-do` asks this — not `capabilities.injectedTools` —\n * before it wraps a loop in `withTeamTools` and the other tool decorators, because those decorators\n * fill `RuntimePort.runTurn`'s `input.tools` and only an in-isolate loop reads it. A process loop\n * is served the same tools out of band, over the session-scoped MCP bridge. The two questions used\n * to have the same answer and no longer do: this set is the mechanism, `injectedTools` is whether\n * the tools arrive at all, and it is now `true` for every published harness.\n */\nexport const RUNS_AS_A_PROCESS = new Set<HarnessId>([\"hermes\", \"claude_code\"]);\n\n/** Picker-only. Not on the wire until an adapter exists. */\nexport const COMING_SOON = [\n { id: \"codex\", label: \"Codex\" },\n { id: \"cursor\", label: \"Cursor\" },\n { id: \"opencode\", label: \"OpenCode\" },\n] as const;\n\nexport function parseHarness(value: string): HarnessId | undefined {\n const parsed = HarnessIdSchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nexport function isHosted(id: HarnessId): boolean {\n return HARNESSES[id].location === \"hosted\";\n}\n\nexport function harnessOption(id: HarnessId): string {\n const spec = HARNESSES[id];\n const bill = spec.billing === \"usage\" ? \"Vetta usage-based\" : \"your logged-in account\";\n const place = spec.location === \"hosted\" ? \"hosted\" : \"local CLI\";\n return `${spec.label} — ${bill}, ${place}`;\n}\n","/**\n * Agents, immutable agent versions, and the one toolset schema (canonical-spec §6, §12, §13).\n * The layer an agent selects is its **harness** — never its runtime, which is the metered\n * infrastructure we provide and not a parameter (canonical-spec §19).\n */\n\nimport { z } from \"zod\";\nimport {\n JsonSchemaDocument,\n Metadata,\n MicroUsdField,\n PrincipalSchema,\n Timestamp,\n WindowSchema,\n idOf,\n} from \"./common\";\nimport { BrowserOptionsSchema } from \"./browser\";\nimport { HarnessIdSchema } from \"./harness\";\nimport { ModelSelectionPolicySchema } from \"./model-selection\";\nimport type { SessionMode } from \"./session\";\n\n/** `allow` runs silently · `ask` pauses · `deny` never offers the tool to the model (§6). */\nexport const ToolPermissionSchema = z.enum([\"allow\", \"ask\", \"deny\"]);\nexport type ToolPermission = z.infer<typeof ToolPermissionSchema>;\n\n/**\n * Built-in P1 tools — the names an agent's `configs` may govern. External tools register through\n * the same shape (§6). `bash`, `read`, `write`, `edit`, `ls` and `find` are the harness's own\n * sandbox tools; `browser`, `read_skill`, `publish_file`, `web_search`, `web_fetch`,\n * `generate_image` and `generate_video` are Vetta's (ADR-0102, ADR-0275, ADR-0277). A customer can\n * only deny a tool it can name, so this list is the tool surface, not a subset of it — and that is\n * why the six team tools (§28) are here even though only an agent with a roster or a room seat is\n * ever offered one: a name that cannot be written into `configs` cannot be denied.\n *\n * It is also what makes a built-in **default-on**: the runtime never reads this constant, but the\n * CLI and the dashboard write `enabled:false` for every name *not* in it, so a tool omitted here is\n * silently denied everywhere except the raw API.\n */\nexport const BUILTIN_TOOLS = [\n \"bash\",\n \"read\",\n \"write\",\n \"edit\",\n \"ls\",\n \"find\",\n \"browser\",\n \"read_skill\",\n \"publish_file\",\n \"web_search\",\n \"web_fetch\",\n \"generate_image\",\n \"generate_video\",\n \"clip_video\",\n \"apps\",\n \"send_to_agent\",\n \"wait_for_agents\",\n \"list_agents\",\n \"post_to_channel\",\n \"board_read\",\n \"board_write\",\n \"ask_operator\",\n \"request_tools\",\n \"project_context\",\n // core-gaps: contracts — names only (`canonical-spec §35.3`, §36.3, §39); U6/U7/U10 add the modules.\n \"transcribe_audio\",\n \"generate_speech\",\n \"find_files\",\n // The read half of the library: `find_files` answers WHICH images exist, this one shows them\n // (§16.2, ADR-0758). Separate names because only one of the two costs context.\n \"view_image\",\n // The write half: `view_image` shows the model a file, this one puts it on the box's DISK so\n // bash can work on the bytes (ffmpeg joining a long-form render, say). The exact inverse of\n // `publish_file`, and the first way anything the platform itself produced could be read back.\n \"fetch_file\",\n \"find_stock_photo\",\n \"session_spend\",\n // A view the chat draws — spend, post views, the roadmap, the week ahead — read by code (§48).\n \"show\",\n // A card the model lays out, every number bound to a source code reads (§49).\n \"compose\",\n // Plan mode's two (§7.5): offered only to a session in plan mode or holding a plan.\n \"write_plan\",\n \"propose_plan\",\n] as const;\n\n/**\n * The tools the Effect ledger (`canonical-spec §19`, ADR-0822) runs again on a replay instead of\n * answering from its record, because the record would describe a world the replay has changed:\n *\n * - the effect is held by the turn and written at its commit, so a failed attempt lost it — the\n * thread `send_to_agent` queues, the park `wait_for_agents` asks for;\n * - the effect depends on state the arguments do not name, which the replay may have rewritten —\n * the box's files `publish_file` and `apps` read, the live page `browser` acts on.\n */\nexport const UNJOURNALED_TOOLS: ReadonlySet<string> = new Set([\n \"send_to_agent\",\n \"wait_for_agents\",\n \"publish_file\",\n \"apps\",\n \"browser\",\n]);\n\n/**\n * The platform's own namespaced tools — Vetta's, not a declared server's or a connected app's. They\n * ride on the session's identity and are offered only when it owns what they reach: an inbox\n * (§24.9), a social workspace (§27), the connections layer (§25). Named here so a dashboard can\n * tell them from an external `server.tool` it cannot enumerate; `isToolName` already admits them\n * by shape, so this list widens nothing on the wire.\n */\nexport const PLATFORM_TOOLS = [\n \"email.inboxes\",\n \"email.read\",\n \"email.send\",\n \"social.accounts\",\n \"social.post\",\n \"social.status\",\n \"social.post_metrics\",\n \"connections.search\",\n \"connections.connect\",\n \"connections.status\",\n \"legal.verifications\",\n \"legal.verification\",\n \"legal.companies\",\n \"legal.company\",\n \"legal.documents\",\n \"legal.naics\",\n \"legal.verify\",\n \"legal.resend_link\",\n \"legal.form\",\n \"legal.submit\",\n \"wallet.balance\",\n \"wallet.transactions\",\n \"wallet.receipts\",\n \"wallet.quote\",\n \"wallet.pay\",\n \"wallet.transfer\",\n \"card.list\",\n \"card.show\",\n \"card.quote\",\n \"card.transactions\",\n \"card.spend\",\n \"card.issue\",\n \"card.credentials\",\n \"card.cancel\",\n // The company's timezone (§20.6, ADR-0904): offered to every session; asks unless the owner sets it to allow.\n \"company.set_timezone\",\n // The company's logo (§20.7, ADR-1085): offered to every session; asks unless the owner sets it to allow.\n \"company.set_logo\",\n // The company's brand kit (ADR-1163): offered to every session; always asks, like the logo.\n \"company.set_brand\",\n // An app's key (§29.10, ADR-1004): minted only when a person approves the card that lists it.\n \"apps.request_access\",\n] as const;\n\n/**\n * Platform tools that publish, spend, file, reveal or change the company's settings, and therefore\n * default to `ask` unless the toolset says otherwise (§20.6, §27, §43.5, §44.4, §45.4). One list, so a bridge and a harness agree.\n */\nexport const ASK_BY_DEFAULT_TOOLS: ReadonlySet<string> = new Set([\n \"social.post\",\n \"email.send\",\n \"legal.verify\",\n \"legal.resend_link\",\n \"legal.form\",\n \"legal.submit\",\n \"wallet.pay\",\n \"wallet.transfer\",\n \"card.issue\",\n \"card.credentials\",\n \"card.cancel\",\n \"company.set_timezone\",\n \"company.set_logo\",\n \"company.set_brand\",\n \"apps.request_access\",\n]);\n\n/**\n * The control plane's tools that spend money, move value or act in the outside world: the `SPENDS`\n * routes of `apps/api/src/mcp-tools.ts`, by tool name (a test there keeps the two equal).\n */\nexport const SPENDS_OR_PUBLISHES: ReadonlySet<string> = new Set([\n \"ads_activate_campaign\",\n \"ads_create_search_campaign\",\n \"connections_connect\",\n \"creator_publish_template\",\n \"creator_request_payout\",\n \"credits_change_subscription_plan\",\n \"credits_create_subscription\",\n \"credits_create_topup\",\n \"domains_purchase\",\n \"identities_cancel_card\",\n \"identities_create_company\",\n \"identities_create_post\",\n \"identities_issue_card\",\n \"identities_pay\",\n \"identities_resend_member_link\",\n \"identities_reveal_credentials\",\n \"identities_send_email\",\n \"identities_send_sms\",\n \"identities_start_verification\",\n \"identities_submit_company\",\n \"identities_transfer\",\n \"media_create_clip\",\n \"media_create_conversation\",\n \"media_create_speech\",\n \"media_create_transcription\",\n \"media_generate_image\",\n \"media_generate_video\",\n]);\n\n/** A control-plane call each person sees: it spends money or acts in the outside world. Any server's name. */\nconst seenEachTime = (name: unknown): boolean =>\n typeof name === \"string\" && [...SPENDS_OR_PUBLISHES].some((tool) => name === tool || name.endsWith(`.${tool}`) || name.endsWith(`__${tool}`));\n\n/**\n * Whether a tool may be granted for the rest of a chat (§7.3). Not one that publishes, pays or\n * files: a grant runs every later call with no card, and the model rewrites the arguments (ADR-0810).\n * That holds for the control plane's own such tools too, called directly or through the invoker\n * (`args.tool`). Nor a pause\n * (`asksAPerson`): a question, a toolset change or a plan is answered each time. Nor a template\n * install: each one hires a crew, so each is its own card (ADR-1104).\n */\nexport const grantable = (name: string, args: Record<string, unknown> = {}): boolean =>\n !ASK_BY_DEFAULT_TOOLS.has(name) &&\n !asksAPerson(name) &&\n !namesInstall(name) &&\n !seenEachTime(name) &&\n !(invokesAnyTool(name) && (namesInstall(args[\"tool\"]) || seenEachTime(args[\"tool\"])));\n\n/**\n * Tools no policy can set to `allow` (`permissionOf`): each call is a signed-in owner's or admin's\n * decision. The logo is here because its API write is admin-only (ADR-1086): a member must not\n * change what every member sees by approving the agent's call.\n */\nexport const ALWAYS_ASKS: ReadonlySet<string> = new Set([\"apps.request_access\", \"company.set_logo\", \"company.set_brand\"]);\n\n/**\n * The tool that asks a person something (§7.1). Named here rather than spelled inline at each of\n * its reading sites, because `permissionOf` below has to recognise it and a typo there would\n * silently hand a model a tool that runs without ever asking anyone.\n */\nexport const ASK_OPERATOR = \"ask_operator\";\n\n/** The tool that proposes a change to this agent's own toolset (§7.4). Same rule, same reason. */\nexport const REQUEST_TOOLS = \"request_tools\";\n\n/** Plan mode's tools (§7.5): the compare-and-set on the plan, and the card that asks to build it. */\nexport const WRITE_PLAN = \"write_plan\";\nexport const PROPOSE_PLAN = \"propose_plan\";\n\n/**\n * The built-ins that ARE a pause: a person answers them, so none can ever be `allow`. `propose_plan`\n * is here because its allow is what leaves plan mode (§7.5): run unasked, it would record an\n * approval nobody gave and leave the session planning.\n */\nexport const asksAPerson = (name: string): boolean =>\n name === ASK_OPERATOR || name === REQUEST_TOOLS || name === PROPOSE_PLAN;\n\n/**\n * The control plane's tool invoker (`apps/api/src/mcp-meta.ts`): ONE tool that runs any of the\n * catalogue's 240, chosen by an argument, so it is enabled `allow` and the card is decided per\n * call from what it is invoking. Named here because two layers must recognise it and neither may\n * guess: the harness asks before a write (`harness-pi/src/catalogue.ts`), and a `scope: \"session\"`\n * grant for it is keyed on the TARGET in `args.tool` (`harness-pi/src/approvals.ts`) — a grant is\n * one tool name, and this name is every tool, so a grant for the bare invoker is dropped rather\n * than read as a standing licence to write anything for the rest of the chat with no card at all.\n *\n * Namespaced, because an MCP tool is `server.tool` and the server is the customer's to name.\n */\nexport const TOOLS_EXECUTE = \"tools_execute\";\n\n/** Its other half: the catalogue, searched instead of carried (`apps/api/src/mcp-meta.ts`). */\nexport const TOOLS_SEARCH = \"tools_search\";\n\n/**\n * The control-plane tools the CEO carries directly, beside the two above; the rest of the catalogue\n * it reaches only through `TOOLS_EXECUTE`. Why each one is here is `apps/web/app/lib/orchestrator.server.ts`.\n * It lives here because the catalogue's own descriptions have to agree with it: a carried tool's\n * description that names a sibling the CEO cannot call directly reads as \"call it directly\", and\n * the model did — `vetta__blueprints_list_installs`, answered \"not found\" (ADR-1025). The API's test\n * reads this list against the published descriptions (`apps/api/src/mcp-meta.test.ts`).\n */\nexport const ORCHESTRATOR_CORE_TOOLS = [\n \"agents_list\",\n \"agents_get\",\n \"sessions_create\",\n \"sessions_get\",\n \"sessions_list\",\n \"sessions_list_events\",\n \"files_list\",\n \"credits_get_balance\",\n \"blueprints_list_artifacts\",\n \"blueprints_list_installs\",\n \"blueprints_get_context\",\n] as const;\n\n/**\n * THE BUILT-INS A CEO CARRIES WHILE ITS COMPANY IS SET UP (ADR-1108): asking, showing, planning and\n * reading what is set up. None of them needs a box, so a setup chat never buys one; everything that\n * does — a shell, files, a browser, apps, media — waits for activation. The control plane itself is\n * reached through the platform's own tool server, each call held to its route's `setup` flag. The API\n * refuses a setup CEO wired with anything else (`apps/api/src/setup-gate.ts`); the dashboard wires\n * it with exactly these (`apps/web/app/lib/orchestrator.server.ts`).\n */\nexport const SETUP_CEO_TOOLS: readonly string[] = [\n \"ask_operator\",\n \"show\",\n \"compose\",\n \"project_context\",\n \"list_agents\",\n \"write_plan\",\n \"propose_plan\",\n // The company's look, made in the chat once onboarding has the name (ADR-1163): each asks a person.\n \"company.set_logo\",\n \"company.set_brand\",\n];\n\nexport const invokesAnyTool = (name: string): boolean =>\n name === TOOLS_EXECUTE || name.endsWith(`.${TOOLS_EXECUTE}`) || name.endsWith(`__${TOOLS_EXECUTE}`);\n\n/** The template install (§31): the one held call whose `answers` a person may edit as they approve it (ADR-1030). */\nexport const INSTALL_TOOL = \"blueprints_apply_install\";\n\n/** Bare, namespaced (`vetta.…`) or in the MCP spelling (`vetta__…`) the invoker also runs (`bareToolName`). */\nconst namesInstall = (name: unknown): boolean =>\n typeof name === \"string\" && (name === INSTALL_TOOL || name.endsWith(`.${INSTALL_TOOL}`) || name.endsWith(`__${INSTALL_TOOL}`));\n\n/**\n * A held call read as a template install — called directly or through the invoker, whose target's\n * arguments sit in `arguments` — or `null` for any other call. `answered` is the same call with its\n * `answers` replaced and nothing else touched: the one edit an approval may carry (§7, ADR-1030).\n */\nexport function installCall(\n name: string,\n args: Record<string, unknown>,\n): { args: Record<string, unknown>; answered: (answers: Record<string, unknown>) => Record<string, unknown> } | null {\n if (namesInstall(name)) return { args, answered: (answers) => ({ ...args, answers }) };\n const inner = args[\"arguments\"];\n if (!invokesAnyTool(name) || !namesInstall(args[\"tool\"]) || typeof inner !== \"object\" || inner === null || Array.isArray(inner)) return null;\n const own = inner as Record<string, unknown>;\n return { args: own, answered: (answers) => ({ ...args, arguments: { ...own, answers } }) };\n}\n\n/**\n * Is this a tool name a `configs` key may govern?\n *\n * A built-in, or a **namespaced** `<namespace>.<tool>` — the form every tool that is not built in\n * registers under: a connection contributes `<connector>.<tool>` (`tracker.get_issue`) and an MCP\n * server contributes `<server>.<tool>` (`vetta.agents_create`), both documented as `tools.configs`\n * keys (`docs/capabilities/tools.mdx`). The namespace cannot be enumerated ahead of time — it comes\n * from the org's live connections — so the check is on the *shape*, which is still enough to catch\n * the typo it exists for: a bare name that is not a built-in is refused.\n */\nexport const isToolName = (name: string): boolean =>\n (BUILTIN_TOOLS as readonly string[]).includes(name) || /^[a-z0-9_-]+(\\.[a-z0-9_-]+)+$/i.test(name);\n\nexport const ToolConfigSchema = z.object({\n enabled: z.boolean(),\n permission: ToolPermissionSchema,\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\n/**\n * The toolset wrapper — the only `tools` schema (§6).\n *\n * Every tool's `config` is open — the web filters, the media pins and `apps.allowed_apps` are all\n * read leniently at the catalogue — except `browser`'s, which is the browser option object\n * (§32.2, `BrowserOptionsSchema`): the runtime answers a malformed one with a browser that reaches\n * nothing, a refusal the author would never see, so it is refused here, by field, wherever a toolset\n * is written (`POST/PATCH /v1/agents`, the CLI, a blueprint). Validated, not parsed: the stored\n * config keeps exactly the keys the author wrote, and the defaults are applied where it is read.\n */\nexport const ToolsetSchema = z\n .object({\n default_config: z.object({ permission: ToolPermissionSchema }),\n configs: z.record(z.string(), ToolConfigSchema),\n })\n .superRefine((tools, ctx) => {\n const config = tools.configs[\"browser\"]?.config;\n if (config === undefined) return;\n for (const issue of BrowserOptionsSchema.safeParse(config).error?.issues ?? []) {\n ctx.addIssue({ code: \"custom\", message: issue.message, path: [\"configs\", \"browser\", \"config\", ...issue.path] });\n }\n });\nexport type Toolset = z.infer<typeof ToolsetSchema>;\n\n/**\n * The agent's policy for one tool. An unlisted tool takes `default_config.permission`, so a tool a\n * harness builds itself is governed by the same rule as one the platform injects (§6).\n *\n * IT LIVES IN `core` BECAUSE THREE DELIVERY PATHS APPLY IT and a tool reaching a model outside this\n * filter is a security hole: `harness-pi`'s catalogue gates its own tools with it, the session tool\n * bridge (`apps/runtime-do/src/bridge.ts`) filters what a boxed CLI is offered with it, and\n * `harness-vetta` filters the modules it is handed with it. Three copies is how one of them comes\n * to disagree, so there is one.\n */\nexport function permissionOf(toolset: Toolset): (name: string) => ToolPermission {\n return (name) => {\n const config = toolset.configs[name];\n if (config?.enabled === false) return \"deny\";\n /**\n * `ask_operator` HAS NO `allow`, and that one line is what makes it safe everywhere else.\n * The tool *is* the pause: running it without stopping the turn would be a tool that asked\n * nobody and returned nothing, so `allow` is not a coherent policy for it and collapses to\n * `ask`. `deny` still forbids an agent to ask at all, from either level.\n *\n * The other two delivery paths keep only what this function calls `allow` — the session tool\n * bridge (`apps/runtime-do/src/bridge.ts`) and `harness-vetta`'s `injected` — so they drop it\n * without either of them naming it. That is the point: neither can hold a `tools/call` open\n * for the hours an answer takes (ADR-0400), and being unable to say `allow` here is a stronger\n * guarantee than a second copy of the rule in each of them.\n */\n if (asksAPerson(name)) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // A key for an app is approved one card at a time, whatever the policy says (ADR-1009): with\n // `allow` an agent would mint its own keys with no person asked. `deny` still forbids it.\n if (ALWAYS_ASKS.has(name)) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // Publishing, spending, filing and revealing default to approval; an explicit per-tool policy still wins.\n return config?.permission ?? (ASK_BY_DEFAULT_TOOLS.has(name) ? \"ask\" : toolset.default_config.permission);\n };\n}\n\n/**\n * What plan mode offers besides a tool whose module published `readOnly: true` (§7.5): asking,\n * the plan's two tools, and reading — the box, the web, the board, the roster, the library.\n */\nexport const PLAN_READ_ONLY: ReadonlySet<string> = new Set([\n ASK_OPERATOR,\n WRITE_PLAN,\n PROPOSE_PLAN,\n \"read\",\n \"ls\",\n \"find\",\n \"web_search\",\n \"web_fetch\",\n \"board_read\",\n \"list_agents\",\n \"read_skill\",\n \"find_files\",\n \"view_image\",\n \"session_spend\",\n \"project_context\",\n]);\n\n/**\n * PLAN MODE, AS A POLICY OVER THE AGENT'S OWN (§7.5). It only narrows: in plan mode a tool that is\n * neither on `PLAN_READ_ONLY` nor read-only by its own published hint is `deny`, which every\n * delivery path already reads as \"never built, never offered\". Everything else answers to `policy`\n * unchanged, so an agent that denies `web_search` still has none while planning.\n *\n * A FUNCTION, NOT A TOOLSET. A narrowed `Toolset` would be written back into the session's pin\n * (`runtime-do loop.ts` keeps a grant that way) and read off storage by the bridge, so plan mode\n * would outlive itself. Applied at each `permissionOf` site: the pi catalogue, the bridge and\n * `harness-vetta`. `readOnly` is the site's own knowledge of its modules.\n */\nexport function planPolicy(\n mode: SessionMode,\n policy: (name: string) => ToolPermission,\n readOnly: (name: string) => boolean,\n): (name: string) => ToolPermission {\n return (name) => {\n // THE PLAN'S OWN TWO ANSWER TO NO DEFAULT. An agent whose default is `deny` would otherwise plan\n // with no way to write the plan or put it to anyone, and one whose default is `ask` would park a\n // card on every write. They are only offered where a plan applies (`runtime-do plan.ts`).\n if (name === WRITE_PLAN) return \"allow\";\n if (name === PROPOSE_PLAN) return \"ask\";\n if (mode === \"build\") return policy(name);\n return PLAN_READ_ONLY.has(name) || readOnly(name) ? policy(name) : \"deny\";\n };\n}\n\n/**\n * Does this toolset carry an `ask_operator` a harness with no approval seam would have to serve?\n *\n * Read by NAME, and only when the toolset NAMES IT. `permissionOf` collapses `allow` to `ask` for\n * this tool, so a toolset that never mentions it still answers `ask` — and a gate that read the\n * bare answer would refuse every session and every roster on `hermes` and `claude_code` over a\n * capability their loops never publish (`bridge.ts` and `harness-vetta` keep only `allow`).\n *\n * It lives here because two gates ask it — `startSession` before any spend, and roster admission\n * one save earlier — and they were written apart: the roster's asked only about a literal\n * `permission: \"ask\"`, which `ask_operator` never carries, so a member configured with it saved\n * clean and then had the tool silently dropped at delegation instead of being refused. Two gates\n * asking one question is how one of them comes to answer it differently.\n */\nexport const asksOperator = (toolset: Toolset): boolean =>\n [ASK_OPERATOR, REQUEST_TOOLS].some(\n (name) => toolset.configs[name] !== undefined && permissionOf(toolset)(name) !== \"deny\",\n );\n\n/**\n * The `computerId` a session's tools are built against before its sandbox exists. A box is bought\n * by the first tool call that needs one, never at `POST /v1/sessions` (ADR-0099 → `box.ts`), so\n * until then this stands in for the id and the gated compute port swaps it for the real one. A\n * tool that only *records* the id (the browser) must treat it as \"no box yet\", not as a box.\n */\nexport const PENDING_BOX = \"pending\";\n\nexport const BudgetSchema = z.object({\n cap_micro_usd: MicroUsdField.nonnegative(),\n max_task_micro_usd: MicroUsdField.nonnegative(),\n period: z.enum([\"day\", \"week\", \"month\"]),\n});\n\n/**\n * `slug` floats to the latest version at session start; `slug@N` is an immutable pin (§13). A\n * `naive/` prefix addresses the platform's catalogue (§31.9) instead of the organization's skills;\n * `naive/` alone names nothing.\n */\nexport const SkillRefSchema = z.string().regex(/^(naive\\/)?[a-z0-9][a-z0-9-]*(@\\d+)?$/, {\n error: \"expected `slug`, `slug@N`, `naive/slug` or `naive/slug@N`\",\n});\n\nconst SECRET_HEADER = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)$/i;\n\nexport const McpServerSchema = z\n .object({\n name: z.string().min(1).max(64),\n url: z.url().startsWith(\"https://\", { error: \"an MCP server URL must be HTTPS\" }),\n headers: z.record(z.string().max(128), z.string().max(4096)).optional(),\n })\n .superRefine((server, ctx) => {\n let url: URL | null = null;\n try {\n url = new URL(server.url);\n } catch {\n // The field-level URL validator reports the malformed value.\n }\n if (url && (url.username !== \"\" || url.password !== \"\")) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"url\"],\n message: \"credentials belong in a vault-bound MCP credential, not the server URL\",\n });\n }\n for (const name of Object.keys(server.headers ?? {})) {\n if (SECRET_HEADER.test(name)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"headers\", name],\n message: \"credentials belong in a vault-bound MCP credential, not agent config\",\n });\n }\n }\n });\n\n/**\n * Historical versions are data, not new configuration. They retain the schema that was valid when\n * written so a stricter create/patch boundary cannot turn an existing agent into a runtime 500.\n * The MCP transport still refuses plaintext before opening a socket or sending a credential.\n */\nexport const StoredMcpServerSchema = z.object({\n name: z.string(),\n url: z.url(),\n headers: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * One roster member of a team (§28). Four forms, and the bare `agt_…` string normalises to the\n * object form **at parse**, so exactly one shape reaches storage, validation and the response —\n * nothing downstream has to ask \"which spelling is this\".\n *\n * `self` is the coordinator delegating to a copy of itself; `advisor` is a bare model with no agent\n * behind it, so it names a `model` instead of an `id`.\n */\nexport const RosterEntrySchema = z.union([\n idOf(\"agt\").transform((id) => ({ type: \"agent\" as const, id })),\n z.object({\n type: z.literal(\"agent\"),\n id: idOf(\"agt\"),\n version: z.number().int().positive().optional(),\n }),\n z.object({ type: z.literal(\"self\") }),\n z.object({ type: z.literal(\"advisor\"), model: z.string().min(1) }),\n]);\nexport type RosterEntry = z.infer<typeof RosterEntrySchema>;\n\n/** A roster names at most one of each of these: they are singletons, not addressable members. */\nconst SINGLETON_ENTRIES = [\"self\", \"advisor\"] as const;\n\n/** The coordinator declaration. `board` opts into the shared board; its columns are fixed (§28). */\nexport const MultiagentSchema = z.object({\n type: z.literal(\"coordinator\"),\n agents: z\n .array(RosterEntrySchema)\n .min(1)\n .max(20)\n .refine(\n (roster) => SINGLETON_ENTRIES.every((t) => roster.filter((e) => e.type === t).length <= 1),\n { error: \"a roster carries at most one `self` and at most one `advisor` entry\" },\n ),\n board: z.boolean().optional(),\n});\nexport type Multiagent = z.infer<typeof MultiagentSchema>;\n\n/**\n * `multiagent` on the wire. `null` is required, not cosmetic: the coordinator echoes\n * `\"multiagent\": null` on every non-coordinator agent, and a `PATCH` of `null` is how a roster is\n * cleared — which `false` cannot say, because `false` is also the create-time default.\n */\nexport const MultiagentField = z.union([z.boolean(), MultiagentSchema, z.null()]);\nexport type MultiagentConfig = z.infer<typeof MultiagentField>;\n\n/** The one reading of the three arms: is there a team here, and what is it? */\nexport function normaliseMultiagent(value: MultiagentConfig): Multiagent | null {\n if (value === true) return { type: \"coordinator\", agents: [], board: false };\n if (value === false || value === null) return null;\n return value;\n}\n\n/**\n * `handoffs` on the wire (§28.12): who this agent may `send_to_agent`. `true` — any agent of\n * the organization; `false` — nobody, and none of the agent tools are offered; `\"team\"` — the agents\n * on its own `multiagent` roster; a list of agent **names** — those. Every policy but `false` also\n * reaches the CEO (`handoffAllows`). The create-time default is `true`, and a version minted before\n * the field existed reads as `true` (`handoffsOf`), so an agent nobody configured can reach anyone.\n */\nexport const HandoffsField = z.union([z.boolean(), z.literal(\"team\"), z.array(z.string().min(1)).max(50)]);\nexport type Handoffs = z.infer<typeof HandoffsField>;\n\n/** The field as every reader takes it: absent is `true`. */\nexport const handoffsOf = (config: { handoffs?: Handoffs | undefined }): Handoffs => config.handoffs ?? true;\n\n/** Whether the agent tools are offered at all: only `false` opts out, since `[]` still reaches the CEO. */\nexport const handoffsEnabled = (handoffs: Handoffs): boolean => handoffs !== false;\n\n/**\n * Whether `name` is a seat this policy lets the agent reach — never itself (§28.15). `team` is the\n * roster as names, which only the caller can resolve; under any other policy it is not read. `ceo`\n * is the name of the org's agent marked `ORCHESTRATOR_ROLE` (or `null` if there is none): every\n * policy but `false` reaches it, named or not (§28.12, ADR-0842).\n */\nexport const handoffAllows = (\n handoffs: Handoffs,\n self: string,\n name: string,\n team: readonly string[],\n ceo: string | null,\n): boolean =>\n name !== self &&\n handoffs !== false &&\n (handoffs === true || name === ceo || (handoffs === \"team\" ? team : handoffs).includes(name));\n\n/** The config carried by an agent and frozen into every version (§12). */\nconst agentConfigShape = {\n model: z.string(),\n window: WindowSchema,\n system: z.string(),\n tools: ToolsetSchema,\n mcp_servers: z.array(StoredMcpServerSchema),\n skills: z.array(SkillRefSchema),\n multiagent: MultiagentField,\n /** Optional on the type so a version minted before §28.15 still parses; read it through `handoffsOf`. */\n handoffs: HandoffsField.optional(),\n /** §46.6: when set, every turn picks one of its options and `model` is the default. Absent before it existed. */\n model_selection: ModelSelectionPolicySchema.nullable().optional(),\n budget: BudgetSchema,\n output_schema: JsonSchemaDocument.nullable(),\n structured_output_required: z.boolean(),\n description: z.string().nullable(),\n metadata: Metadata,\n};\n\n/** An immutable agent version. A no-op change mints nothing (§12). */\nexport const AgentVersionSchema = z.object({\n version: z.number().int().positive(),\n created_at: Timestamp,\n created_by: PrincipalSchema,\n ...agentConfigShape,\n});\nexport type AgentVersion = z.infer<typeof AgentVersionSchema>;\n\nexport const AgentSchema = z.object({\n id: idOf(\"agt\"),\n object: z.literal(\"agent\"),\n name: z.string(),\n /** The agent loop this agent runs (§19). Chosen at create; the catalog lives in `harness.ts`. */\n harness: HarnessIdSchema,\n current_version: z.number().int().positive(),\n created_at: Timestamp,\n ...agentConfigShape,\n});\nexport type Agent = z.infer<typeof AgentSchema>;\n","/**\n * core-gaps: contracts — the managed browser's wire objects (`canonical-spec §32`). One option\n * object read by `POST /v1/computers`, the `browser` tool's config and `browser_session`.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\nimport { RoleSchema } from \"./org\";\n\n/** D2: the cap stays 360 minutes. */\nexport const BROWSER_MAX_TIMEOUT_MINUTES = 360;\nexport const BROWSER_REGIONS = [\"us-west\", \"us-east\", \"eu-central\", \"ap-southeast\"] as const;\nexport const BROWSER_OS = [\"windows\", \"mac\", \"linux\", \"mobile\", \"tablet\"] as const;\n/** The `browser` tool's `action` names (§32.7): the §32.4 page actions plus the saved-login flows. */\nexport const BROWSER_TOOL_ACTIONS = [\n \"goto\",\n \"click\",\n \"type\",\n \"extract\",\n \"act\",\n \"observe\",\n \"links\",\n \"screenshot\",\n \"login\",\n \"signup\",\n \"save_context\",\n] as const;\n\n/**\n * `allowed_domains` is a *narrowing* control, not a grant: omit it and the browser reaches the whole\n * public web. It is not what keeps the browser off private infrastructure — `isBlockedHost` bars\n * loopback, private, link-local and cloud-metadata hosts on every action regardless of this list, so\n * the open default widens reach to the public internet only. An explicit `[]` is still refused: a\n * caller who names the field means to bound it, and silently reaching nothing is the trap this\n * default exists to avoid.\n *\n * `proxy: true` with a `\"*\"` allowlist is refused: residential egress needs a bounded destination,\n * and because `\"*\"` is now the default, a proxied browser must name its domains outright.\n * `ask_actions` is read by the `browser` tool alone: with the tool at `allow`, a call whose action is\n * listed pauses for approval and every other one runs (§32.7).\n */\nexport const BrowserOptionsSchema = z\n .object({\n allowed_domains: z.array(z.string().min(1)).min(1).default([\"*\"]),\n timeout_minutes: z.number().int().min(1).max(BROWSER_MAX_TIMEOUT_MINUTES).default(15),\n region: z.enum(BROWSER_REGIONS).default(\"us-west\"),\n keep_alive: z.boolean().default(false),\n viewport: z\n .object({ width: z.number().int().positive(), height: z.number().int().positive() })\n .optional(),\n os: z.enum(BROWSER_OS).optional(),\n block_ads: z.boolean().default(false),\n solve_captchas: z.boolean().default(true),\n stealth: z.boolean().default(false),\n allow_writes: z.boolean().default(false),\n allow_extract: z.boolean().default(false),\n context_name: z.string().min(1).max(64).optional(),\n persist_context: z.boolean().default(false),\n human_login: z.boolean().default(false),\n proxy: z.boolean().default(false),\n ask_actions: z.array(z.enum(BROWSER_TOOL_ACTIONS)).default([\"signup\"]),\n })\n .refine((options) => !(options.proxy && options.allowed_domains.includes(\"*\")), {\n error: \"a proxied browser needs a bounded allow-list, not *\",\n path: [\"proxy\"],\n });\nexport type BrowserOptions = z.infer<typeof BrowserOptionsSchema>;\n// core-gaps: U2-browser-api — what a caller sends: every field may be omitted.\nexport type BrowserOptionsInput = z.input<typeof BrowserOptionsSchema>;\n\nexport const BrowserSessionStatusSchema = z.enum([\"creating\", \"active\", \"closed\", \"error\"]);\n\nexport const BrowserSessionSchema = z.object({\n id: idOf(\"brw\"),\n object: z.literal(\"browser_session\"),\n computer_id: idOf(\"cmp\").nullable(),\n /** The agent session that opened it, if an agent did; a REST caller's browser carries `null`. */\n session_id: idOf(\"ses\").nullable(),\n status: BrowserSessionStatusSchema,\n allowed_domains: z.array(z.string()),\n region: z.enum(BROWSER_REGIONS),\n context_id: idOf(\"bct\").nullable(),\n context_backed: z.boolean(),\n timeout_at: Timestamp,\n opened_at: Timestamp,\n closed_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type BrowserSession = z.infer<typeof BrowserSessionSchema>;\n\n/** A bearer credential for one browser (§32.3): minted for a person, never stored, never in another object. */\nexport const BrowserLiveViewSchema = z.object({\n object: z.literal(\"browser_live_view\"),\n url: z.url(),\n expires_at: Timestamp,\n});\nexport type BrowserLiveView = z.infer<typeof BrowserLiveViewSchema>;\n\n/** A saved login, identity-scoped like a vault (D4). */\nexport const BrowserContextSchema = z.object({\n id: idOf(\"bct\"),\n object: z.literal(\"browser_context\"),\n identity_id: idOf(\"idn\"),\n name: z.string(),\n service: z.string().nullable(),\n created_at: Timestamp,\n last_used_at: Timestamp.nullable(),\n});\nexport type BrowserContext = z.infer<typeof BrowserContextSchema>;\n\nexport const BrowserGranteeTypeSchema = z.enum([\"agent\", \"role\"]);\n\nexport const BrowserGrantSchema = z.object({\n id: idOf(\"bgr\"),\n object: z.literal(\"browser_grant\"),\n context_id: idOf(\"bct\"),\n grantee_type: BrowserGranteeTypeSchema,\n grantee_id: z.union([idOf(\"agt\"), RoleSchema]),\n created_at: Timestamp,\n});\nexport type BrowserGrant = z.infer<typeof BrowserGrantSchema>;\n\nexport const SaveBrowserContextSchema = z.object({\n name: z.string().min(1).max(64),\n identity_id: idOf(\"idn\"),\n service: z.string().min(1).optional(),\n});\n\nexport const CreateBrowserGrantSchema = z.object({\n identity_id: idOf(\"idn\"),\n grantee_type: BrowserGranteeTypeSchema,\n grantee_id: z.union([idOf(\"agt\"), RoleSchema]),\n});\n\nconst Selector = z.string().min(1);\nconst Instruction = z.string().min(1).max(4_096);\n\n/** §32.4 — the discriminant is `action`, the same word the tool uses. */\nexport const BrowserActionRequestSchema = z.discriminatedUnion(\"action\", [\n z.object({ action: z.literal(\"goto\"), url: z.string().url() }),\n z.object({ action: z.literal(\"click\"), selector: Selector }),\n z.object({ action: z.literal(\"type\"), selector: Selector, text: z.string() }),\n z.object({\n action: z.literal(\"extract\"),\n instruction: Instruction.optional(),\n selector: Selector.optional(),\n schema: z.record(z.string(), z.unknown()).optional(),\n }),\n z.object({\n action: z.literal(\"act\"),\n instruction: Instruction,\n variables: z.record(z.string(), z.string()).optional(),\n }),\n z.object({ action: z.literal(\"observe\"), instruction: Instruction }),\n z.object({\n action: z.literal(\"links\"),\n contains: z.string().optional(),\n limit: z.number().int().min(1).max(200).default(50),\n }),\n z.object({ action: z.literal(\"screenshot\") }),\n]);\nexport type BrowserActionRequest = z.infer<typeof BrowserActionRequestSchema>;\nexport const BROWSER_ACTIONS = BrowserActionRequestSchema.options.map(\n (option) => option.shape.action.value,\n);\n\nexport const BrowserActionResultSchema = z.object({\n object: z.literal(\"browser_action\"),\n action: z.enum(BROWSER_ACTIONS),\n url: z.string(),\n text: z.string().nullable(),\n data: z.unknown().nullable(),\n links: z.array(z.object({ href: z.string(), text: z.string() })).nullable(),\n elements: z.array(z.object({ selector: z.string(), description: z.string() })).nullable(),\n file_id: idOf(\"fil\").nullable(),\n performed: z.boolean(),\n});\nexport type BrowserActionResult = z.infer<typeof BrowserActionResultSchema>;\n\n/** `login`/`signup` bodies (§32.3). The password never appears on the wire except in `credentials`. */\nexport const BrowserLoginSchema = z.object({\n service: z.string().min(1),\n url: z.string().url(),\n identity_id: idOf(\"idn\"),\n});\nexport const BrowserSignupSchema = BrowserLoginSchema.extend({ email: z.string().email() });\nexport const BrowserCredentialSchema = z.object({\n identity_id: idOf(\"idn\"),\n service: z.string().min(1),\n email: z.string().email(),\n password: z.string().min(1),\n username: z.string().min(1).optional(),\n});\n\nexport const LiveViewSchema = z.object({ url: z.string().url(), expires_at: Timestamp });\n","/** Org, members, keys, credits ledger, webhooks, audit log (canonical-spec §10, §11, §14, §17). */\n\nimport { z } from \"zod\";\nimport {\n AuditActionSchema,\n Metadata,\n MicroUsdField,\n PrincipalSchema,\n Timestamp,\n LineItemTierSchema,\n idOf,\n} from \"./common\";\n\n/** Where every company starts (the owner's choice, ADR-0904); migration 0088's column default. */\nexport const DEFAULT_ORG_TIMEZONE = \"America/New_York\";\n\n/** The IANA name `Intl` resolves `name` to, or `undefined` when it is not one zone's name. */\nfunction canonicalZone(name: string): string | undefined {\n // `Intl` also takes `EST`, `PST` and `+05:00`: an abbreviation or an offset, not a place's zone.\n if (!name.includes(\"/\") && name !== \"UTC\") return undefined;\n try {\n const zone = new Intl.DateTimeFormat(\"en-US\", { timeZone: name }).resolvedOptions().timeZone;\n // `supportedValuesOf` lists every canonical zone but `UTC`, and none of `Etc/GMT+5`'s kind.\n return zone === \"UTC\" || Intl.supportedValuesOf(\"timeZone\").includes(zone) ? zone : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A company's timezone as written (§20.6, ADR-0904): an IANA name, stored as the canonical one\n * `Intl` resolves, so `US/Eastern` is kept as `America/New_York`. The API's `PATCH` and the agent's\n * `company.set_timezone` both parse through it.\n */\nexport const TimezoneSchema = z.string().transform((name, ctx) => {\n const zone = canonicalZone(name);\n if (zone === undefined) {\n ctx.addIssue({ code: \"custom\", message: \"not a timezone; use an IANA name such as America/Los_Angeles\" });\n return z.NEVER;\n }\n return zone;\n});\n\n/** The typefaces a brand kit names, each a stack every browser already has (ADR-1163). */\nexport const BRAND_TYPEFACES = [\"grotesk\", \"serif\", \"rounded\", \"mono\"] as const;\n\n/**\n * THE COMPANY'S BRAND KIT (ADR-1163): a palette, a typeface and a tagline, set beside the logo in\n * the setup chat and read by whoever makes things in the company's look. Its colours are drawn in\n * code from the logo; nothing here is a model's.\n */\nexport const BrandKitSchema = z\n .object({\n palette: z\n .array(z.object({ name: z.string().trim().min(1).max(24), hex: z.string().regex(/^#[0-9a-f]{6}$/) }).strict())\n .min(3)\n .max(6),\n typeface: z.enum(BRAND_TYPEFACES),\n tagline: z.string().trim().max(80),\n })\n .strict();\n\nexport type BrandKit = z.infer<typeof BrandKitSchema>;\n\nexport const OrganizationSchema = z.object({\n id: idOf(\"org\"),\n object: z.literal(\"organization\"),\n name: z.string(),\n balance_micro_usd: MicroUsdField,\n /**\n * The company's timezone, an IANA name (`America/New_York`, §20.6). Times the company chooses or\n * reads are in it: a new routine's zone, when a post goes out. `America/New_York` until changed.\n * Defaulted so a reply from a control plane older than 0088 (or a rolled-back Worker) still parses\n * in a newer SDK/CLI rather than throwing on every `orgs.get/list/update`.\n */\n timezone: z.string().min(1).default(DEFAULT_ORG_TIMEZONE),\n /**\n * The company's logo, an SVG a person or an agent drew (§20.7), passed by `checkLogoSvg`. `null`\n * until one is set. Defaulted so a reply from a control plane older than 0093 still parses.\n */\n logo_svg: z.string().nullable().default(null),\n /** Its brand kit (ADR-1163), `null` until one is set. Defaulted so an older control plane parses. */\n brand: BrandKitSchema.nullable().default(null),\n /**\n * Still being set up: made in a chat with its CEO and not yet activated by a payment (ADR-1108).\n * Defaulted `false`, so a reply from a control plane older than 0101 reads as an ordinary company.\n */\n setting_up: z.boolean().default(false),\n /** The `blueprint/template` a link named when the company was made, else `null` (ADR-1108). */\n start_template: z.string().nullable().default(null),\n created_at: Timestamp,\n});\n\nexport type Organization = z.infer<typeof OrganizationSchema>;\n\nexport const RoleSchema = z.enum([\"owner\", \"admin\", \"member\"]);\n\nexport type Role = z.infer<typeof RoleSchema>;\n\n/** Member ids are not in the `canonical-spec.md §2` prefix table; see the owed doc-fix in decisions. */\nexport const MemberSchema = z.object({\n id: z.string(),\n object: z.literal(\"member\"),\n email: z.email(),\n role: RoleSchema,\n invited_by: z.string().nullable(),\n created_at: Timestamp,\n});\n\nexport type Member = z.infer<typeof MemberSchema>;\n\nexport const SCOPES = [\n \"agents:read\",\n \"agents:write\",\n \"sessions:read\",\n \"sessions:write\",\n /**\n * THE MODEL DOOR AND NOTHING ELSE. `/v1/proxy/*` used to take `sessions:write`, which also opens\n * session create and cancel — so a credential handed to a customer's micro-VM, if it leaked, could\n * start sessions for the whole organization. This scope buys exactly one capability, so a sandbox\n * token can be minted with it alone.\n *\n * The proxy routes accept EITHER this or `sessions:write`: narrowing an already-published route\n * would break every key that reaches it today (§17).\n */\n \"proxy:write\",\n \"computers:write\",\n \"files:read\",\n \"files:write\",\n \"billing:read\",\n \"billing:write\",\n \"webhooks:*\",\n \"audit:read\",\n \"admin\",\n] as const;\nexport const ScopeSchema = z.enum(SCOPES);\n\nexport type Scope = z.infer<typeof ScopeSchema>;\n\nexport const ApiKeySchema = z.object({\n id: idOf(\"key\"),\n object: z.literal(\"api_key\"),\n name: z.string(),\n prefix: z.string(),\n scopes: z.array(ScopeSchema),\n created_by: PrincipalSchema,\n last_used_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\n\nexport type ApiKey = z.infer<typeof ApiKeySchema>;\n\n/**\n * Every inference debit records all five token tiers (§11) and its actor (§17). `line_items[].tier`\n * is the **whole** tier enum, not just the token five: a sandbox (`computer`) or a priced tool line\n * is a line item like any other, and narrowing this to the token tiers 500'd the ledger route on\n * every session that ran a box.\n */\nexport const LedgerEntrySchema = z.object({\n id: idOf(\"led\"),\n type: z.enum([\"debit\", \"credit\"]),\n amount_micro_usd: MicroUsdField,\n balance_after_micro_usd: MicroUsdField,\n actor: PrincipalSchema,\n session_id: idOf(\"ses\").nullable(),\n agent_id: idOf(\"agt\").nullable(),\n deployment_id: idOf(\"dep\").nullable(),\n line_items: z.array(z.object({ tier: LineItemTierSchema, amount_micro_usd: MicroUsdField })),\n created_at: Timestamp,\n});\n\nexport type LedgerEntry = z.infer<typeof LedgerEntrySchema>;\n\n/** Top-up ids are not in the `canonical-spec.md §2` prefix table; see the owed doc-fix in decisions. */\nexport const TopupSchema = z.object({\n id: z.string(),\n object: z.literal(\"topup\"),\n amount_micro_usd: MicroUsdField.positive(),\n status: z.enum([\"pending\", \"requires_action\", \"succeeded\", \"failed\"]),\n action_url: z.url().nullable(),\n balance_after_micro_usd: MicroUsdField.nullable(),\n created_at: Timestamp,\n});\n\nexport type Topup = z.infer<typeof TopupSchema>;\n\nexport const WebhookEndpointSchema = z.object({\n id: idOf(\"whk\"),\n object: z.literal(\"webhook_endpoint\"),\n url: z.url(),\n events: z.array(z.string()),\n enabled: z.boolean(),\n created_at: Timestamp,\n});\n\nexport type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;\n\nexport const WebhookDeliverySchema = z.object({\n id: idOf(\"whd\"),\n event_id: idOf(\"evt\"),\n event_type: z.string(),\n status: z.enum([\"pending\", \"succeeded\", \"failed\"]),\n attempts: z.number().int().nonnegative(),\n response_status: z.number().int().nullable(),\n response_snippet: z.string().nullable(),\n delivered_at: Timestamp.nullable(),\n next_retry_at: Timestamp.nullable(),\n});\n\nexport type WebhookDelivery = z.infer<typeof WebhookDeliverySchema>;\n\nexport const AuditEntrySchema = z.object({\n id: idOf(\"aud\"),\n object: z.literal(\"audit_entry\"),\n actor: PrincipalSchema,\n action: AuditActionSchema,\n resource_type: z.string(),\n resource_id: z.string(),\n request_id: z.string(),\n metadata: Metadata,\n created_at: Timestamp,\n});\n","/**\n * Model auto-selection (`canonical-spec §46`, ADR-0722): a caller names a few catalogue ids with a\n * one-line brief each and gets one of them back. Field-shape rules live here; the two rules that\n * need the catalogue (every option key is an exact entry id) or the ledger (the price) belong to\n * the route.\n *\n * The same `options`/`min_confidence` pair is a **policy** (§46.6, ADR-0723) when it rides beside a\n * `model` on a proxy call or an agent — there the sibling `model` is the default.\n *\n * A plain `z.object` with refinements, not a `.transform`/pipe: `parseBody` reads `.shape` to\n * refuse unknown keys under strict bodies.\n */\n\nimport { z } from \"zod\";\n\nexport const MODEL_SELECTION_MIN_OPTIONS = 2;\nexport const MODEL_SELECTION_MAX_OPTIONS = 16;\nexport const MODEL_SELECTION_MAX_MESSAGES = 32;\n/** Summed `content` length across every message — nothing is silently trimmed to fit. */\nexport const MODEL_SELECTION_MAX_CONTENT_CHARS = 32_000;\n\nexport const ModelSelectionMessageSchema = z.object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().min(1),\n});\nexport type ModelSelectionMessage = z.infer<typeof ModelSelectionMessageSchema>;\n\nconst OptionsSchema = z\n .record(z.string().min(1), z.string().trim().min(1).max(500))\n .refine((options) => Object.keys(options).length >= MODEL_SELECTION_MIN_OPTIONS, {\n message: `at least ${MODEL_SELECTION_MIN_OPTIONS} options are required`,\n })\n .refine((options) => Object.keys(options).length <= MODEL_SELECTION_MAX_OPTIONS, {\n message: `at most ${MODEL_SELECTION_MAX_OPTIONS} options are allowed`,\n });\n\n/** §46.6: the selector's inputs minus the conversation and the default, which the carrier supplies. */\nexport const ModelSelectionPolicySchema = z.object({\n options: OptionsSchema,\n min_confidence: z.number().gt(0).max(1).optional(),\n});\nexport type ModelSelectionPolicy = z.infer<typeof ModelSelectionPolicySchema>;\n\n/** The one rule a policy cannot check alone: its default (`model`) must be one of its options. */\nexport const policyNamesDefault = (policy: ModelSelectionPolicy, model: string): boolean =>\n Object.hasOwn(policy.options, model);\n\n/**\n * The most recent turns that fit §46.2's caps, oldest first, for a conversation the caller cannot\n * be asked to shorten (§46.6). Every message is kept whole except the newest, which keeps its\n * tail when it alone is over the limit.\n */\nexport function selectionTail(messages: readonly ModelSelectionMessage[]): ModelSelectionMessage[] {\n const out: ModelSelectionMessage[] = [];\n let chars = 0;\n for (const message of [...messages].reverse()) {\n if (out.length === MODEL_SELECTION_MAX_MESSAGES) break;\n if (chars + message.content.length > MODEL_SELECTION_MAX_CONTENT_CHARS) {\n if (out.length === 0) {\n out.push({ role: message.role, content: message.content.slice(-MODEL_SELECTION_MAX_CONTENT_CHARS) });\n }\n break;\n }\n chars += message.content.length;\n out.push(message);\n }\n return out.reverse();\n}\n\nexport const ModelSelectionRequestSchema = z\n .object({\n options: OptionsSchema,\n messages: z.array(ModelSelectionMessageSchema).min(1).max(MODEL_SELECTION_MAX_MESSAGES),\n default: z.string().min(1).optional(),\n min_confidence: z.number().gt(0).max(1).optional(),\n })\n .superRefine((body, ctx) => {\n const total = body.messages.reduce((sum, message) => sum + message.content.length, 0);\n if (total > MODEL_SELECTION_MAX_CONTENT_CHARS) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"messages\"],\n message: `total message content exceeds ${MODEL_SELECTION_MAX_CONTENT_CHARS} characters`,\n });\n }\n if (body.default !== undefined && !Object.hasOwn(body.options, body.default)) {\n ctx.addIssue({ code: \"custom\", path: [\"default\"], message: \"default must be one of the options\" });\n }\n if (body.min_confidence !== undefined && body.default === undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"min_confidence\"],\n message: \"min_confidence requires a default to fall back to\",\n });\n }\n });\nexport type ModelSelectionRequest = z.infer<typeof ModelSelectionRequestSchema>;\n\nexport const ModelSelectionSchema = z.object({\n object: z.literal(\"model_selection\"),\n model: z.string().min(1),\n confidence: z.number().min(0).max(1).nullable(),\n probabilities: z.record(z.string(), z.number()).nullable(),\n defaulted: z.boolean(),\n spent_micro_usd: z.number().int().nonnegative(),\n usage: z.object({ input_tokens: z.number().int().nonnegative() }),\n});\nexport type ModelSelection = z.infer<typeof ModelSelectionSchema>;\n","/** Sessions, the transcript message, and tool results (canonical-spec §5, §7, §10, §16). */\n\nimport { z } from \"zod\";\nimport { SocialPlatformSchema } from \"./social\";\nimport {\n JsonSchemaDocument,\n Metadata,\n MicroUsdField,\n Timestamp,\n TokenUsageSchema,\n WindowSchema,\n idOf,\n} from \"./common\";\n\n/** `idle` = resumable, `completed` = the agent declared done; both are non-`running` (§5). */\nexport const SessionStatusSchema = z.enum([\n \"queued\",\n \"running\",\n \"idle\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\nexport type SessionStatus = z.infer<typeof SessionStatusSchema>;\n\n/**\n * Plan mode (§7.5, ADR-0905). `build` is every session that never entered plan mode. Session state,\n * never agent config: it rides a send and is changed back only by a person.\n */\nexport const SessionModeSchema = z.enum([\"plan\", \"build\"]);\nexport type SessionMode = z.infer<typeof SessionModeSchema>;\n\n/** A plan's words are capped where a board card's body is (`runtime-do board-tools.ts`). */\nexport const PLAN_MAX_CHARS = 20_000;\n\n/**\n * The living plan (§7.5). Kept by the runtime beside the session's state, never in the transcript.\n * `version` 0 is no plan yet, and only then is `by` null.\n */\nexport const PlanSchema = z.object({\n object: z.literal(\"plan\"),\n markdown: z.string().max(PLAN_MAX_CHARS),\n version: z.number().int().nonnegative(),\n by: z.enum([\"agent\", \"owner\"]).nullable(),\n});\nexport type Plan = z.infer<typeof PlanSchema>;\n\n/** `write_plan`'s arguments and `PUT /v1/sessions/{id}/plan`'s body: one compare-and-set (§7.5). */\nexport const PlanWriteSchema = z.object({\n markdown: z.string().max(PLAN_MAX_CHARS),\n base_version: z.number().int().nonnegative(),\n});\nexport type PlanWrite = z.infer<typeof PlanWriteSchema>;\n\n/** `propose_plan`'s arguments (§7.5). `version` is hashed into the card's id, so a denied plan is written again before it is proposed again. */\nexport const ProposePlanSchema = z.object({\n version: z.number().int().positive(),\n spends_or_publishes: z.array(z.string().min(1).max(200)).max(10).optional(),\n});\n\n/** Set whenever a turn yields control — never treat `idle` as success (§5). */\nexport const StopReasonSchema = z.enum([\n \"end_turn\",\n \"awaiting_input\",\n \"awaiting_approval\",\n \"budget_paused\",\n \"interrupted\",\n \"error\",\n \"max_iterations\",\n /** A turn produced no message and no tool call — honest failure, never `end_turn` (entry 4). */\n \"context_exhausted\",\n /**\n * A coordinator yielded because every delegated child it is waiting on is still running (§28).\n * Distinct from `awaiting_input`: nobody is being asked for anything, so no human can unblock it —\n * the child's completion does. Reporting `idle`/`end_turn` here would claim the task was finished.\n */\n \"awaiting_delegation\",\n /**\n * The turn yielded because the agent asked the operator a question and cannot proceed without\n * the answer (§7.1). Distinct from all three neighbours, and none can stand in: `awaiting_input`\n * says only that there is nothing left to do, so a client reading it renders a bare composer\n * where a specific answer is owed; `awaiting_approval` says the block is a tool call to allow or\n * deny, and its route carries a verb and no payload; `awaiting_delegation` says no human can\n * unblock it at all. What is being asked is the parked `pending_actions` row.\n */\n \"awaiting_answer\",\n]);\nexport type StopReason = z.infer<typeof StopReasonSchema>;\n\n/**\n * THE STOPS THAT PARK A TURN ON A PERSON, in one place because four things must agree about them.\n *\n * A question is a `pending_actions` row exactly as an unapproved call is (§7.1); the two differ\n * only in which door the person answers through, and nothing that reads this cares about doors.\n * Everything here keeps the parked rows across the commit, cross-posts a member's rows to its\n * coordinator, renders the card, and — in the sandbox reaper — refuses to TTL the filesystem the\n * question is about out from under a session waiting on a human.\n *\n * This existed as three hand-written copies of `stop === \"awaiting_approval\"`, in\n * `apps/runtime-do/src/loop.ts`, `apps/web/app/lib/events.ts` and the reaper's SQL. Adding\n * `awaiting_answer` reached exactly one of them, and the other two silently answered a session\n * parked on a question as though nobody were waiting. `budget_paused` is deliberately NOT here: a\n * person unblocks it too, but there is no parked row and nothing renders a card.\n */\nexport const PARKED_STOP_REASONS = [\"awaiting_approval\", \"awaiting_answer\"] as const;\n\n/** Is this stop one a person has to clear? `null`/`undefined` — never ran, never parked. */\nexport const isParked = (stop: string | null | undefined): boolean =>\n stop !== null && stop !== undefined && (PARKED_STOP_REASONS as readonly string[]).includes(stop);\n\n/**\n * THE STOP THAT IS NOT A REST. `max_iterations` says a turn ran out of model calls, not that the\n * work stopped: `schedule` (`apps/runtime-do/src/loop.ts`) arms the alarm at once, so the next\n * turn's `session.running` follows that `session.idle` in milliseconds. A reader that treats this\n * idle as the end stops reading, and the answer arrives on a socket nobody is holding — measured on\n * staging as a CEO chat still showing `Working…` 21.7 s after the reply was in the log, with only a\n * reload to reveal it. Nobody is asked for anything either, so it is not a park.\n */\nexport const RESUMING_STOP_REASONS = [\"max_iterations\"] as const;\n\n/** Does the runtime wake itself from this stop? `null`/`undefined` — never ran, never stopped. */\nexport const isResuming = (stop: string | null | undefined): boolean =>\n stop !== null && stop !== undefined && (RESUMING_STOP_REASONS as readonly string[]).includes(stop);\n\n/** Where a session sits in a team (§28). `null` on every ordinary, undelegated session. */\nexport const ThreadRoleSchema = z.enum([\"coordinator\", \"member\"]);\nexport type ThreadRole = z.infer<typeof ThreadRoleSchema>;\n\nexport const MessageSchema = z.object({\n role: z.enum([\"system\", \"user\", \"assistant\", \"tool\"]),\n content: z.string(),\n tool_call_id: z.string().optional(),\n});\nexport type Message = z.infer<typeof MessageSchema>;\n\n/**\n * ONE IMAGE A TOOL HANDS BACK TO THE MODEL (§16.2) — **a link to it, never its bytes.**\n *\n * *** THIS EXISTS BECAUSE EVERY IMAGE THIS PLATFORM MAKES WAS INVISIBLE TO THE AGENT THAT MADE\n * IT. *** `ToolResult.content` is a string, so a tool that produced pixels could only describe\n * them: the browser's `screenshot` stored a PNG and returned the sentence \"screenshot of <url>\n * saved as fil_…\". The model was told a file existed and could never look at it. Measured on the\n * `media` blueprint (ADR-0758): asked to study a reference video it could read the caption,\n * hashtags and transcript of, and never a frame, the crew planned the wrong genre outright.\n *\n * IT CARRIED BASE64 FOR ONE RELEASE, AND THAT WAS THE WRONG SHAPE (ADR-0761). A tool result is not\n * a one-off payload: it lands in session history and is replayed to the provider on *every\n * subsequent turn*. At the shipped bound — 5 MB of base64 each, twelve per result — a single\n * screenshot-heavy turn could park 60 MB in a context that is then re-sent for the rest of the\n * session, and the mitigation ADR-0758 named (pi resizing oversized images as they enter history)\n * is `processImage`, a wasm image backend that does not exist in the session isolate, so it fails\n * open and passes the original block through. Every image a tool returns is already written to\n * storage and already has a `fil_`; the addressable form of it costs ~200 bytes and never grows.\n *\n * `url` is a **short-lived signed §40 read** at this deployment's own origin — the same mint the\n * social publish hands a provider to fetch once (`files.ts` `signedFileUrl`), not a presigned\n * object-store URL, because the Worker holds no S3 credential. It expires; a later turn that needs\n * to look again asks `view_image` again, which is cheaper than what it replaces.\n *\n * `media_type` is the wire's spelling of the same field the providers use, and it is restricted to\n * what they accept — a model cannot look at a PDF or an SVG, and a tool that sends one has made a\n * mistake worth refusing at the boundary rather than at the provider.\n *\n * There is no byte cap here any more because there are no bytes here any more. The one bound left\n * is the COUNT, on `ToolResult.images` below, and it is the only one this contract needs.\n */\nexport const ToolImageSchema = z.object({\n file_id: idOf(\"fil\"),\n url: z.string().url().describe(\"A short-lived signed read for the file's bytes.\"),\n media_type: z.enum([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]),\n});\nexport type ToolImage = z.infer<typeof ToolImageSchema>;\n\n/**\n * Normative tool result — the plugin contract depends on this shape (§16).\n *\n * `images` is OPTIONAL and additive: a result carrying none is byte-identical to one written\n * before the field existed, which is why no tool, plugin or stored row needed changing for it.\n * A tool that returns images SHOULD still set `content`, because the text is what a reader without\n * vision — a transcript, a log, an operator scrolling the session — is left with.\n *\n * At most 12, because this is a tool result and not an album: a turn that needs more frames than\n * that is sampling, and the sampling belongs in the tool. Since ADR-0761 this count is the ONLY\n * bound on the field — each entry is a link of fixed size, so there is no payload left to cap.\n */\nexport const ToolResultSchema = z.object({\n output: z.unknown(),\n is_error: z.boolean().optional(),\n content: z.string().optional(),\n images: z.array(ToolImageSchema).max(12).optional(),\n});\nexport type ToolResult = z.infer<typeof ToolResultSchema>;\n\n/**\n * One field of a parked question (§7.1). `key` is the name the answer comes back under; the rest is\n * how it is asked. The union is discriminated on `type` so a renderer branches on one word rather\n * than sniffing which optional properties happen to be present.\n */\nconst QuestionFieldBase = {\n key: z.string().min(1).max(64),\n label: z.string().min(1).max(200),\n help: z.string().max(500).optional(),\n /**\n * A field that may be left blank, and it defaults to **false** — the rule \"every field must be\n * answered\" (`assertAnswers`) is still the rule, and this is the one documented way out of it.\n *\n * It exists for the question whose answer genuinely improves the work and does not gate it: a\n * template's setup form asking for a reference to imitate, say. Before the flag the only way to\n * ask such a thing was to make it mandatory — which forces an answer out of someone who has none,\n * and an invented answer is worse than an absent one, because the crew cannot tell them apart.\n *\n * Nothing downstream needs an \"if absent\" branch: `projectContextFor` already lists only the\n * questions that were answered, so an unanswered optional key is simply not in the context.\n *\n * ABSENT rather than `false`, which is why it is `.optional()` and not `.default(false)` like the\n * `multiple` and `other` beside it. Those two sit on the `choice` branch, where a renderer has to\n * branch on them and a definite value earns its place; this sits on the base, next to `help`,\n * which is absent-by-default for the same reason. A default here would make `optional: boolean`\n * required on the OUTPUT type — so every hand-written `QuestionField` in the codebase, and every\n * one written after it, would have to spell out the flag it does not use.\n */\n optional: z.boolean().optional(),\n};\n\nexport const QuestionFieldSchema = z.discriminatedUnion(\"type\", [\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"text\"),\n placeholder: z.string().max(200).optional(),\n }),\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"choice\"),\n /**\n * Plain strings: the option is both the value and the label, because the answer is read back by\n * a model, which wants the words and not an id. Fewer than two is not a choice, and more than\n * twelve is a list — which belongs in the prompt.\n */\n options: z.array(z.string().min(1).max(200)).min(2).max(12),\n multiple: z.boolean().default(false),\n /**\n * The free-text escape, and it defaults to **true** on purpose: the agent wrote the options and\n * the agent is the one that does not know the answer, so an operator must always be able to say\n * something it did not think of. A question that truly admits only its list opts out explicitly.\n */\n other: z.boolean().default(true),\n /**\n * A PICTURE OR A LINE FOR AN OPTION (ADR-1103): a template's \"how it looks\" shows its looks, and\n * a niche says what it means in one line. Each names its option by its words; one naming no\n * option is ignored, never refused. With a picture on any option the dashboard draws the choice\n * as a grid of pictures. `image` is `https://`, or a path on the dashboard itself. An array\n * and not a map, because a model's tool schema cannot always take a map. An older reader drops\n * it and draws the plain list.\n */\n details: z\n .array(\n z.object({\n option: z.string().min(1).max(200),\n note: z.string().min(1).max(120).optional(),\n image: z.string().max(500).regex(/^\\/(?!\\/)/, \"an image is a path on the dashboard\").optional(),\n }),\n )\n .max(12)\n .optional(),\n }),\n /**\n * THE PERSON'S OWN MEDIA (ADR-1103): \"show us what you like\". The dashboard offers an upload for\n * images or a video, which land in the organization's files, and a box for a link. The answer is\n * the list: `fil_` ids and `https://` links, which an agent opens with `files_get`, `view_image`\n * or the browser. `placeholder` is the link box's.\n */\n z.object({\n ...QuestionFieldBase,\n type: z.literal(\"media\"),\n placeholder: z.string().max(200).optional(),\n }),\n]);\nexport type QuestionField = z.infer<typeof QuestionFieldSchema>;\n\n/** One piece of a `media` answer: a stored file, or a public link. */\nexport const MEDIA_ANSWER = /^(fil_[0-9a-z]+|https:\\/\\/\\S+)$/;\n\n/** The most pieces a `media` answer holds: an answer list's own bound (`answersOf`). */\nexport const MEDIA_MAX = 12;\n\n/**\n * A CONNECT CARD (ADR-1102): the networks an agent needs a person to sign in to. The card draws a\n * row per network with its Connect, and one Not now. The answer is written by the card, never by\n * the person: `connected: YouTube (@handle)` once every network holds an account, or `not now`.\n *\n * An agent's question only, never a template's: a template asks before anything is provisioned,\n * when there is no persona yet to hold the account.\n */\nexport const ConnectFieldSchema = z.object({\n ...QuestionFieldBase,\n type: z.literal(\"connect\"),\n platforms: z.array(SocialPlatformSchema).min(1).max(6),\n});\n\n/** A field of an agent's question (§7.1): a template's kinds, and the connect card. */\nexport const AskFieldSchema = z.discriminatedUnion(\"type\", [...QuestionFieldSchema.options, ConnectFieldSchema]);\nexport type AskField = z.infer<typeof AskFieldSchema>;\n\n/**\n * A field as a client pinned before `QUESTION_KINDS_VERSION` reads it (ADR-1105): `text` and\n * `choice` as they are, and a connect card or a media field as a text field that says how to answer\n * it. The answer is still checked against the real field (`answerProblems`).\n */\nexport function legacyField(field: AskField): AskField {\n if (field.type !== \"connect\" && field.type !== \"media\") return field;\n const { key, label, help, optional } = field;\n const placeholder =\n field.type === \"connect\"\n ? `connect ${field.platforms.join(\", \")} on the dashboard, then answer \"connected\", or \"not now\"`\n : \"links or fil_ ids, separated by spaces\";\n return { key, label, type: \"text\", placeholder, ...(help === undefined ? {} : { help }), ...(optional === undefined ? {} : { optional }) };\n}\n\n/**\n * The whole question (§7.1). Exported rather than left inline in `PendingActionSchema` because it\n * is the `ask_operator` tool's argument schema *and* the parked row's `question` branch, and those\n * two have to be the same shape: the row is built by parsing the call's arguments, and the tool\n * call is replayed from the row. Two spellings of the bounds is how they come to disagree.\n */\n/**\n * The most a person answers in one sitting. It is three and not a template's four (ADR-0965): the\n * published SDK parses `pending_actions[].question.fields` with `.max(3)`, so one four-field\n * question made every `sessions.get` and `sessions.list` of an older client throw. A template with\n * four setup questions is asked as two questions.\n */\nexport const QUESTION_FIELDS_MAX = 3;\n\nexport const QuestionSchema = z.object({\n prompt: z.string().min(1).max(1000),\n fields: z.array(AskFieldSchema).min(1).max(QUESTION_FIELDS_MAX, {\n message: `a question has at most ${QUESTION_FIELDS_MAX} fields — ask the rest in a second question once these are answered`,\n }),\n}).refine((question) => question.fields.length === 1 || question.fields.every((field) => field.type !== \"connect\"), {\n // A connect card answers itself when the accounts land (ADR-1102); a field beside it would need\n // a Send the card does not have.\n message: \"a connect field is a question of its own: ask anything else in a separate question\",\n path: [\"fields\"],\n});\nexport type Question = z.infer<typeof QuestionSchema>;\n\n/**\n * What comes back (§7.1). Keyed by `QuestionField.key`; an array is a `multiple: true` choice, and\n * a string covers text, a single choice and whatever `other: true` let the person type instead.\n *\n * It is deliberately NOT validated against the question it answers. The agent wrote the question\n * and the agent reads the answer, so the only party that can judge \"that is not one of my options\"\n * is the model — and it can, because `other` means a free-text value was always legal. A schema\n * that rejected the operator's own words would be enforcing a rule §7.1 does not have.\n */\nconst answersOf = (max: number, message: string) =>\n z\n .record(\n z.string().min(1).max(64),\n z.union([z.string().max(2000), z.array(z.string().max(2000)).min(1).max(12)]),\n )\n .refine((answers) => Object.keys(answers).length <= max, { message });\n\nexport const AnswersSchema = answersOf(\n QUESTION_FIELDS_MAX,\n `a question has at most ${QUESTION_FIELDS_MAX} fields, so an answer has at most ${QUESTION_FIELDS_MAX} keys`,\n);\nexport type Answers = z.infer<typeof AnswersSchema>;\n\n/**\n * The most questions a template asks before anything is provisioned (ADR-0757). Four, one more than\n * a question holds (ADR-0965): the fourth is asked as a second question, but the install carries all\n * four answers at once.\n */\nexport const TEMPLATE_QUESTIONS_MAX = 4;\n\n/**\n * A template install's answers, as a person edits them on approval (ADR-1030). The same values as\n * `AnswersSchema`, capped at the template's questions and not at one question's fields, so a\n * four-question template's edit is not refused before `assertAnswers` checks its keys.\n */\nexport const InstallAnswersSchema = answersOf(\n TEMPLATE_QUESTIONS_MAX,\n `a template asks at most ${TEMPLATE_QUESTIONS_MAX} questions, so an install has at most ${TEMPLATE_QUESTIONS_MAX} answers`,\n);\n\n/** What is wrong with a `media` answer's pieces, or `null`: at most twelve files and https links. */\nfunction mediaProblem(key: string, values: readonly string[]): string | null {\n if (values.length > MEDIA_MAX) return `\\`${key}\\` takes at most ${MEDIA_MAX} files and links`;\n const odd = values.find((value) => !MEDIA_ANSWER.test(value));\n return odd === undefined ? null : `\\`${key}\\` takes \\`fil_\\` ids and https links, and \\`${odd}\\` is neither`;\n}\n\n/**\n * EVERYTHING WRONG WITH AN ANSWER SET, against the fields it answers (§7.1) — one rule, read by the\n * control plane before it files answers (`assertAnswers`) and by the studio before it puts an\n * install in front of a person (`InstallPlan`), so a card never offers to run what the control\n * plane will refuse. Empty means the answers stand.\n *\n * Every field must be answered unless it is `optional`, and an optional key that IS present is\n * checked like any other. A key the fields do not ask is wrong. A `choice` without `other` admits\n * only its options.\n */\nexport function answerProblems(\n fields: readonly AskField[],\n answers: Readonly<Record<string, unknown>>,\n): { key: string; message: string }[] {\n const problems: { key: string; message: string }[] = [];\n const asked = new Set(fields.map((field) => field.key));\n for (const key of Object.keys(answers)) {\n if (!asked.has(key)) problems.push({ key, message: `the question does not ask \\`${key}\\`` });\n }\n for (const field of fields) {\n const given = answers[field.key];\n if (given === undefined && field.optional) continue;\n const values = typeof given === \"string\" ? [given] : Array.isArray(given) ? given : [];\n if (values.length === 0 || values.some((value) => typeof value !== \"string\" || value.trim() === \"\")) {\n // A blank optional answer is refused too (an answer given is meant), but the fix is to leave\n // it out: measured, the CEO sent `reference: \"\"` for a question the person skipped.\n const message = field.optional ? `\\`${field.key}\\` was skipped, so leave it out rather than send it blank` : `\\`${field.key}\\` is unanswered`;\n problems.push({ key: field.key, message });\n continue;\n }\n if (field.type === \"text\" || field.type === \"connect\") {\n if (Array.isArray(given)) problems.push({ key: field.key, message: `\\`${field.key}\\` takes one string` });\n continue;\n }\n if (field.type === \"media\") {\n const problem = mediaProblem(field.key, values as string[]);\n if (problem !== null) problems.push({ key: field.key, message: problem });\n continue;\n }\n if (field.multiple !== Array.isArray(given)) {\n const shape = field.multiple ? \"an array of the options chosen\" : \"one option, as a string\";\n problems.push({ key: field.key, message: `\\`${field.key}\\` takes ${shape}` });\n continue;\n }\n // `other` is the free-text escape and defaults to true, so the closed check runs only on a\n // question that opted out of it — the one case where an unlisted answer is genuinely wrong.\n if (field.other) continue;\n const unlisted = (values as string[]).filter((value) => !field.options.includes(value));\n if (unlisted.length > 0) {\n problems.push({\n key: field.key,\n message: `\\`${field.key}\\` admits only the options it listed, and \\`${unlisted[0]}\\` is not one of them`,\n });\n }\n }\n return problems;\n}\n\n/**\n * What a parked session is blocked on (§6 `ask` permission, §7.1). Historically this was only the\n * tool calls an `ask` permission stopped; a question the agent asked the operator is now the second\n * kind, and it is **a row in this same array** rather than a new object, table or list — the park,\n * the sleep, the inbox wake, the transcript fold and the replay are all reused unmodified.\n *\n * `kind` defaults to `\"tool\"`, which is what makes the widening free: every row already sitting in\n * the `pending_actions` jsonb column predates the tag and keeps parsing, so there is no data\n * migration. Carrying an optional tag on this shape has precedent — `ThreadAction`\n * (`apps/runtime-do/src/team.ts`) already extends it with a DO-local `thread_id`.\n */\nexport const PendingActionSchema = z.object({\n kind: z.enum([\"tool\", \"question\"]).default(\"tool\"),\n tool_call_id: z.string(),\n name: z.string(),\n args: z.record(z.string(), z.unknown()),\n /**\n * Present iff `kind` is `\"question\"`, and it is the parse of `args` rather than a second source\n * of truth: `args` is what the model called and therefore what replays byte-identically, while\n * `question` is what a renderer reads without having to know that `ask_operator`'s arguments\n * happen to be the question. Same content, two jobs.\n */\n question: QuestionSchema.optional(),\n /**\n * The helper's thread a coordinator adopted this call from (§28, B-3; ADR-1101): the dashboard\n * marks that helper as waiting on you. Absent on the session's own calls.\n */\n thread_id: idOf(\"ses\").optional(),\n});\nexport type PendingAction = z.infer<typeof PendingActionSchema>;\n\nexport const SessionSchema = z.object({\n id: idOf(\"ses\"),\n object: z.literal(\"session\"),\n agent_id: idOf(\"agt\"),\n agent_version: z.number().int().positive(),\n deployment_id: idOf(\"dep\").nullable(),\n /**\n * The persona this session acts as (`canonical-spec §22`). Chosen per task from the personas the\n * agent holds a grant to, and `null` when the caller named none — an agent with several\n * identities is not silently given one.\n */\n identity_id: idOf(\"idn\").nullable(),\n /**\n * The sandbox this session provisioned, or `null` when its toolset needs none. It is a real\n * `Computer`: it lists under `GET /v1/computers`, takes `exec`/`snapshot`, and is destroyed when\n * the session can no longer run a turn (ADR-0160).\n */\n computer_id: idOf(\"cmp\").nullable(),\n /**\n * The delegation lineage (§28). `parent_session_id` is the thread that delegated this one and\n * `root_session_id` the coordinator at the top of the tree; both `null` on a session a customer\n * started. A child is addressable on its own but is excluded from the default `GET /v1/sessions`\n * listing, so a team of ten does not bury the ten tasks the customer actually asked for.\n */\n parent_session_id: idOf(\"ses\").nullable(),\n root_session_id: idOf(\"ses\").nullable(),\n thread_role: ThreadRoleSchema.nullable(),\n /**\n * The model the latest send picked (§7 `model`), or `null` when none has and the session runs its\n * pinned version's model (§10, ADR-0832). Defaulted so a reply from an older control plane parses.\n */\n model: z.string().nullable().default(null),\n /** Plan mode (§7.5, §10): defaulted so a reply from an older control plane parses as `build`. */\n mode: SessionModeSchema.default(\"build\"),\n status: SessionStatusSchema,\n stop_reason: StopReasonSchema.nullable(),\n window: WindowSchema,\n budget_micro_usd: MicroUsdField.nonnegative(),\n consumed_micro_usd: MicroUsdField.nonnegative(),\n token_usage: TokenUsageSchema,\n pending_actions: z.array(PendingActionSchema),\n output_schema: JsonSchemaDocument.nullable(),\n structured_output: z.record(z.string(), z.unknown()).nullable(),\n last_seq: z.number().int().nonnegative(),\n metadata: Metadata,\n started_at: Timestamp.nullable(),\n ended_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\n/**\n * `POST /v1/sessions/{id}/messages` — one send contract (§7). `queue:true` holds the message in\n * the inbox of a `running` session for the turn after this one; `interrupt:true` stops this one.\n * Both at once is refused: the two name opposite answers to the same question.\n */\nexport const SendMessageSchema = z\n .object({\n message: z.string(),\n interrupt: z.boolean().optional(),\n queue: z.boolean().optional(),\n /** A catalogue id: this session runs on it from this message's turn on (§7, ADR-0832). */\n model: z.string().min(1).optional(),\n /** Plan mode from this message's turn on (§7.5, ADR-0905). */\n mode: SessionModeSchema.optional(),\n idempotency_key: z.string().optional(),\n })\n .refine((body) => !(body.interrupt === true && body.queue === true), {\n message: \"a send is either an interrupt or queued, not both\",\n path: [\"queue\"],\n });\n\n/**\n * `POST /v1/sessions/{id}/messages` → `202` (§7). The reply is the **acceptance**, not a session\n * snapshot: the turn has not run yet, so a snapshot could only report the state before the send.\n * `accepted_seq` is the event high-water mark at acceptance — every event this send produces has\n * `seq > accepted_seq`, which is what makes \"wait for my turn\" expressible (ADR-0108).\n */\nexport const SendAcceptedSchema = z.object({\n session_id: z.string(),\n status: SessionStatusSchema,\n accepted_seq: z.number().int().nonnegative(),\n});\nexport type SendAccepted = z.infer<typeof SendAcceptedSchema>;\n\n/**\n * `POST /v1/sessions/{id}/tool_confirmations` (§7).\n *\n * `scope` is HOW FAR THE ALLOW REACHES, and it is the one thing this body could not say. An\n * approval id is `tc_` + SHA-256 over the tool name and its canonical arguments\n * (`harness-pi/approvals.ts`), deliberately, so a decision survives the session sleeping — but that\n * makes every decision exactly one call, and a person setting an agent up answers the same tool\n * five times with different arguments, one model turn apart each. `scope: \"session\"` says \"this\n * TOOL, for the rest of THIS chat\": subsequent calls to that name run without a card.\n *\n * The bounds are the whole design and they are narrow on purpose. One session — it lives in that\n * session's transcript and nowhere else, so it cannot outlive the chat, cannot be read by another\n * session and is never written onto the agent. One tool NAME — never \"approve everything\", and\n * never a second tool. Opt-in per grant, so the default is still one card, one call. And it only\n * widens `allow`: a session-wide *deny* is a different feature nobody has asked for, and the route\n * refuses the pairing rather than inventing semantics for it.\n *\n * WHY THIS BODY AND NOT A SIBLING ROUTE, given `SessionAnswerSchema` below is a sibling for\n * looking like a widening: the objection there is that an optional `answers` would make the\n * REQUIRED field `decision` conditionally required, so neither body would be total any more.\n * `scope` does nothing of the kind. `tool_call_id` and `decision` stay required and mean exactly\n * what they meant; `scope` is a modifier on the verb, with a default that is today's behaviour, so\n * an omitted `scope` is byte-for-byte the request every existing client already sends.\n */\nexport const ToolConfirmationSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().optional(),\n scope: z.enum([\"call\", \"session\"]).default(\"call\"),\n /**\n * THE PERSON'S OWN ANSWERS for a template install they approve (ADR-1030): the call runs with\n * these in place of the `answers` the agent proposed, and with nothing else changed. A modifier on\n * `allow`, like `scope`: absent is the call as proposed. The route refuses it on a deny, on a session\n * grant, on any other tool, and on answers the template's questions refuse (`answerProblems`).\n */\n answers: InstallAnswersSchema.optional(),\n});\n\n/**\n * `POST /v1/sessions/{id}/answers` (§7.2) — a **sibling** of `ToolConfirmationSchema`, and\n * deliberately not a widening of it.\n *\n * The obvious-looking alternative is one route: add an optional `answers` to the confirmation body\n * and let `decision` go absent when it is present. That reads fine as a schema and badly as a\n * contract — `decision` becomes conditionally required, so every client has to know a rule the\n * type cannot state, and every server has to reject the two nonsense pairings (`decision` with\n * `answers`, neither with either) by hand. A second route costs one line in the route table and\n * one method on the client, and in exchange both bodies stay honest: each has exactly the fields\n * it always has, and each is required.\n *\n * `answers` is keyed by `QuestionField.key`. An array is a `choice` field with `multiple: true`;\n * everything else is a string, including the free text an `other: true` field admits. The values\n * are read back by a model, so they are the words a person chose and not an index into `options`.\n */\nexport const SessionAnswerSchema = z.object({\n tool_call_id: z.string(),\n answers: z.record(z.string(), z.union([z.string(), z.array(z.string())])),\n});\nexport type SessionAnswer = z.infer<typeof SessionAnswerSchema>;\n","/** Identity-owned social publishing (`canonical-spec.md §27`). */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const SOCIAL_PLATFORMS = [\n \"bluesky\",\n \"facebook\",\n \"instagram\",\n \"linkedin\",\n \"mastodon\",\n \"pinterest\",\n \"reddit\",\n \"threads\",\n \"tiktok\",\n \"x\",\n \"youtube\",\n] as const;\n\n/** The networks the social layer connects (§27); the catalogue's own id for X is `twitter`. */\nexport const SOCIAL_APPS: ReadonlySet<string> = new Set([...SOCIAL_PLATFORMS, \"twitter\"]);\nexport const isSocialApp = (connector: string): boolean =>\n SOCIAL_APPS.has(connector.trim().toLowerCase());\n\n/** Platforms whose provider contract accepts a text-only post. */\nexport const SOCIAL_TEXT_PLATFORMS = [\n \"bluesky\",\n \"facebook\",\n \"linkedin\",\n \"mastodon\",\n \"threads\",\n \"x\",\n] as const;\n\n/**\n * Platforms whose provider contract accepts a post of media plus a caption, and nothing\n * per-destination beyond it. Naming one is legal exactly when the post carries `media_urls` or\n * `file_ids` — a text-only post to a video network is one the provider would refuse.\n *\n * `pinterest` and `reddit` are in neither list on purpose: the provider requires a board name and\n * a subreddit respectively, per-post destinations `CreatePost` has no field for, so a post naming\n * one is refused here with that reason rather than at the provider (`canonical-spec.md §27`).\n */\nexport const SOCIAL_MEDIA_PLATFORMS = [\"instagram\", \"tiktok\", \"youtube\"] as const;\n\n/** Who may see a published post. Three words, because three is what the networks that have the\n * concept at all actually spell. */\nexport const SOCIAL_VISIBILITIES = [\"public\", \"unlisted\", \"private\"] as const;\n\n/**\n * Platforms whose provider contract carries a per-post visibility with all three of those\n * meanings. `linkedin` and `tiktok` have a privacy field too, but neither spells `unlisted` — a\n * post-to-connections and a post-to-self-only are a different axis — so mapping ours onto theirs\n * would be inventing a meaning. They are refused by name instead, like the media rule below.\n */\nexport const SOCIAL_VISIBILITY_PLATFORMS = [\"mastodon\", \"youtube\"] as const;\n\nexport const SocialVisibilitySchema = z.enum(SOCIAL_VISIBILITIES);\nexport type SocialVisibility = z.infer<typeof SocialVisibilitySchema>;\n\nexport const acceptsVisibility = (platform: string): boolean =>\n (SOCIAL_VISIBILITY_PLATFORMS as readonly string[]).includes(platform);\n\n/** What a caller is told about visibility, in the tool description and the field's own text. */\nexport const SOCIAL_VISIBILITY_RULE =\n `visibility is ${SOCIAL_VISIBILITIES.join(\", \")} and only ` +\n `${SOCIAL_VISIBILITY_PLATFORMS.join(\" and \")} accept it; omit it and the post publishes at ` +\n \"the account's own default, which on a video channel is normally public\";\n\n/**\n * The outcome metrics the platform measures on a published post (§27, ADR-0768). `follower_delta`\n * is derived by the sweep from two `followers` readings; every other name is parsed from the\n * provider's analytics by the adapter. The only writer of these rows is the platform's own sweep.\n */\nexport const SOCIAL_METRICS = [\n \"views\",\n \"impressions\",\n \"likes\",\n \"comments\",\n \"shares\",\n \"watch_through_rate\",\n \"followers\",\n \"follower_delta\",\n] as const;\nexport type SocialMetric = (typeof SOCIAL_METRICS)[number];\n\nexport const SocialPlatformSchema = z.enum(SOCIAL_PLATFORMS);\nexport type SocialPlatform = z.infer<typeof SocialPlatformSchema>;\n\nexport const SocialTextPlatformSchema = z.enum(SOCIAL_TEXT_PLATFORMS);\nexport type SocialTextPlatform = z.infer<typeof SocialTextPlatformSchema>;\n\nconst isText = (platform: string): boolean =>\n (SOCIAL_TEXT_PLATFORMS as readonly string[]).includes(platform);\nconst isMedia = (platform: string): boolean =>\n (SOCIAL_MEDIA_PLATFORMS as readonly string[]).includes(platform);\n\n/** What a caller is told about the lists, in the tool description and the field's own text. */\nexport const SOCIAL_PLATFORM_RULE =\n `${SOCIAL_TEXT_PLATFORMS.join(\", \")} take a text-only post; ` +\n `${SOCIAL_MEDIA_PLATFORMS.join(\", \")} may be named only when the post carries media_urls or ` +\n `file_ids; ${SOCIAL_PLATFORMS.filter((platform) => !isText(platform) && !isMedia(platform)).join(\", \")} ` +\n \"cannot be posted to\";\n\n/**\n * The create-post rule, shared verbatim by the REST route and the agent tool so the two doors\n * cannot drift. Both halves are relationships between `platforms` and another field — the two\n * media fields, and `visibility` — so they live on the object rather than on any one field, and\n * each refusal names the platform it is about.\n */\nexport function checkPostTargets(\n value: {\n platforms: readonly string[];\n media_urls?: readonly unknown[] | undefined;\n file_ids?: readonly unknown[] | undefined;\n visibility?: string | undefined;\n },\n ctx: z.RefinementCtx,\n): void {\n const named = [...new Set(value.platforms)];\n const unsupported = named.filter((platform) => !isText(platform) && !isMedia(platform));\n if (unsupported.length > 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"platforms\"],\n message:\n `${unsupported.join(\", \")} cannot be a post target: each needs a per-destination field ` +\n \"(a board, a subreddit) this post has no way to carry\",\n });\n return;\n }\n const needMedia = named.filter(isMedia);\n if (needMedia.length > 0 && (value.media_urls?.length ?? 0) + (value.file_ids?.length ?? 0) === 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"platforms\"],\n message:\n `${needMedia.join(\", \")} publishes media, not text: attach at least one media_urls or ` +\n \"file_ids entry, or drop the platform\",\n });\n }\n if (value.visibility === undefined) return;\n const deaf = named.filter((platform) => !acceptsVisibility(platform));\n if (deaf.length === 0) return;\n ctx.addIssue({\n code: \"custom\",\n path: [\"visibility\"],\n message:\n `${deaf.join(\", \")} has no per-post visibility to publish under: only ` +\n `${SOCIAL_VISIBILITY_PLATFORMS.join(\" and \")} accept one, so drop visibility or send those ` +\n \"targets as their own post\",\n });\n}\n\nexport const SocialAccountSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_account\"),\n identity_id: idOf(\"idn\"),\n platform: SocialPlatformSchema,\n username: z.string().nullable(),\n display_name: z.string().nullable(),\n avatar_url: z.url().nullable(),\n connected_at: Timestamp.nullable(),\n});\nexport type SocialAccount = z.infer<typeof SocialAccountSchema>;\n\nexport const SocialPostStatusSchema = z.enum([\n \"draft\",\n \"scheduled\",\n \"processing\",\n \"posted\",\n \"failed\",\n \"deleted\",\n]);\nexport type SocialPostStatus = z.infer<typeof SocialPostStatusSchema>;\n\nexport const SocialPostSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_post\"),\n identity_id: idOf(\"idn\"),\n title: z.string(),\n platforms: z.array(SocialPlatformSchema),\n status: SocialPostStatusSchema,\n scheduled_at: Timestamp.nullable(),\n posted_at: Timestamp.nullable(),\n error: z.string().nullable(),\n});\nexport type SocialPost = z.infer<typeof SocialPostSchema>;\n\nexport const SocialUploadSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_upload\"),\n identity_id: idOf(\"idn\"),\n type: z.enum([\"image\", \"video\", \"document\"]),\n url: z.url().nullable(),\n});\nexport type SocialUpload = z.infer<typeof SocialUploadSchema>;\n\nexport const SocialAnalyticsSchema = z.object({\n object: z.literal(\"social_analytics\"),\n identity_id: idOf(\"idn\"),\n resource_id: z.string().min(1),\n platform: SocialPlatformSchema.nullable(),\n data: z.unknown(),\n});\nexport type SocialAnalytics = z.infer<typeof SocialAnalyticsSchema>;\n\nexport const SocialCommentSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"social_comment\"),\n identity_id: idOf(\"idn\"),\n post_id: z.string().min(1),\n platforms: z.array(SocialPlatformSchema),\n status: SocialPostStatusSchema,\n posted_at: Timestamp.nullable(),\n data: z.unknown(),\n});\nexport type SocialComment = z.infer<typeof SocialCommentSchema>;\n\n/** Where a post stands in `GET /v1/posts` (§27.1): waiting on a person, due, out, or refused. */\nexport const POST_STATUSES = [\"pending\", \"scheduled\", \"posted\", \"failed\"] as const;\nexport const PostStatusSchema = z.enum(POST_STATUSES);\nexport type PostStatus = z.infer<typeof PostStatusSchema>;\n\n/**\n * One post as the posts view lists it (§27.1, ADR-0890): a parked `social.post` call (`pending`) or\n * a `social_post` row. A pending post has no provider id yet, so its `id` is\n * `<session_id>:<tool_call_id>`, the address a decision is posted to.\n */\nexport const PostSchema = z.object({\n object: z.literal(\"post\"),\n id: z.string().min(1),\n status: PostStatusSchema,\n identity_id: z.string().nullable(),\n agent_id: z.string().nullable(),\n session_id: z.string().nullable(),\n tool_call_id: z.string().nullable(),\n content: z.string().nullable(),\n platforms: z.array(z.string()),\n file_ids: z.array(z.string()),\n media_urls: z.array(z.string()),\n visibility: SocialVisibilitySchema.nullable(),\n scheduled_at: Timestamp.nullable(),\n posted_at: Timestamp.nullable(),\n url: z.string().nullable(),\n error: z.string().nullable(),\n /** The latest stored reading, `{metric: value}`; `null` before `social.post_metrics` read any. */\n metrics: z.record(z.string(), z.number()).nullable(),\n measured_at: Timestamp.nullable(),\n /** Pending only: the earlier post this call would repeat — same identity, network and file. */\n duplicate_of: z\n .object({\n id: z.string(),\n status: PostStatusSchema,\n platform: z.string(),\n at: Timestamp.nullable(),\n agent_id: z.string().nullable(),\n session_id: z.string().nullable(),\n })\n .nullable(),\n created_at: Timestamp,\n});\nexport type Post = z.infer<typeof PostSchema>;\n","/** Events — `{domain}.{action}` types on a gap-free `seq` (canonical-spec §8, §10, §15). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, TokenUsageSchema, idOf } from \"./common\";\nimport { AnswersSchema } from \"./session\";\n\nexport const EventTypeSchema = z.enum([\n \"message.delta\",\n /**\n * The agent's answer (no `role`), or a user row `{ role: \"user\", content, client_message_id? }` (§8).\n * A user row the runtime wrote itself — a media job's result, a tool grant — carries\n * `from: \"platform\"` and is the platform's notice, not a caller's words (§8, ADR-0870).\n */\n \"message.completed\",\n /** A caller's message, durable in the inbox and not yet admitted to a turn (§7, §8): `{ client_message_id, content }`. */\n \"message.accepted\",\n /** A person's fan-out, on the sender's log without waking it (§8, §28.16): `{ client_message_id, content, handoffs, refusals }`. */\n \"handoff.sent\",\n \"tool.started\",\n \"tool.completed\",\n \"tool.confirm\",\n /** A person's decision on a parked call, stamped with the inbox write that delivers it (§8, ADR-0764). */\n \"tool.confirm.resolved\",\n /** A person's answer to a parked question, stamped the same way (§7.1, §8, ADR-1049). */\n \"tool.confirm.answered\",\n \"session.running\",\n \"session.usage\",\n \"session.idle\",\n /** A failed attempt the loop will retry (§8): `{ attempt, in_ms, code }`. */\n \"session.retrying\",\n /** The session's mode changed (§7.5): `{ mode: \"plan\" | \"build\" }`. */\n \"session.mode\",\n /** A write to the session's plan, by the agent or its owner (§7.5): the plan object. */\n \"plan.updated\",\n /**\n * The turn ran, but without something it needed (§8): `{ reason, detail? }`.\n *\n * Emitted for a turn whose sandbox could not be woken. That turn used to be indistinguishable\n * from a success — the model was handed the failure as a tool result, answered around it from the\n * transcript, and the session ended `idle`/`end_turn` with no field anywhere saying the\n * filesystem had been unavailable. This is the field. `reason` is open on purpose; today it is\n * `\"sandbox_unavailable\"`, `\"vendor_resume_unavailable\"`, or `\"app_tools_unavailable\"` — an app the\n * agent's toolset names gave no tools this turn (§29.5, `runtime-do app-mcp-tools.ts`).\n *\n * `detail` is the boot failure's own message, and it is here because `reason` alone reads the\n * same for a vendor outage and for a fault of ours. Staging round 3 spent its whole budget\n * establishing with raw Connect RPC that the vendor was refusing every `ResumeSession` on the\n * account — a question the adapter could have answered, since its give-up names the vendor state\n * it last saw and how long it waited (`compute-tenki index.ts`). It is diagnostic prose, not a\n * contract: never parse it, and it may be absent.\n */\n \"session.degraded\",\n /**\n * The session let go of a sandbox that would not resume and will run the next turn on a fresh\n * one: `{ from, reason, failures, replacements }`.\n *\n * *** THE ONE TURN WHERE A FILESYSTEM ACTUALLY GOES MISSING USED TO BE THE SILENT ONE. ***\n * `session.degraded` marks the turns whose resume FAILED, and those turns lose nothing — the box\n * is still there and the next turn may still get it back. The turn that swaps the box is the\n * damaging one, and it has no failure to report: it provisions a replacement and runs normally.\n * Staging watched a session answer `cat: … No such file or directory` with nothing in its event\n * log to tell that apart from the file never having been written, and support could not tell\n * either. `from` is the box that was let go of, so a customer can still reach it through\n * `GET /v1/computers/:id` while it lives.\n *\n * `reason` is open like `session.degraded`'s, and it carries the one distinction an operator\n * cannot make any other way: `\"resume_refused\"` is the FIRST swap, where everything knowable here\n * says the fault is that box's, and `\"vendor_resume_unavailable\"` is a swap that follows one — a\n * fault that already outlived a fresh machine, so it is the account and not the box.\n * `replacements` counts them. There is no third swap: past `box.ts MAX_BOX_REPLACEMENTS` the\n * session keeps the box it holds and reports `session.degraded` under that same\n * `vendor_resume_unavailable` reason, rather than abandoning one more live micro-VM every cycle\n * for a fault a fresh one demonstrably does not fix.\n */\n \"session.computer_replaced\",\n \"budget.exceeded\",\n \"span.model_request.start\",\n \"span.model_request.end\",\n // Pre-model spans (§15): what the gap before the first model request was spent on.\n \"span.transcript_load.start\",\n \"span.transcript_load.end\",\n \"span.harness_load.start\",\n \"span.harness_load.end\",\n \"span.harness_build.start\",\n \"span.harness_build.end\",\n \"span.box_resume.start\",\n \"span.box_resume.end\",\n /**\n * A delegated thread's lifecycle, on the **coordinator's** stream (§28). The child's own\n * `ses_…` rides inside `data.thread_id` — the event schema gains no field and `vetta.event` gains\n * no column, so one reader of `{session_id, seq}` still sees every event in one order.\n */\n \"thread.created\",\n \"thread.running\",\n \"thread.idle\",\n \"thread.terminated\",\n // core-gaps: contracts (`canonical-spec §32.8`, §33.5, §36.3, §37.3, §38.3)\n \"browser.session.opened\",\n \"browser.session.closed\",\n \"browser.context.saved\",\n \"browser.context.granted\",\n \"browser.context.revoked\",\n \"media.job.queued\",\n \"media.job.completed\",\n \"media.job.failed\",\n \"file.imported\",\n \"app.db.migrated\",\n \"app.storage.bucket.created\",\n \"app.storage.bucket.deleted\",\n // identity money (`canonical-spec §44.3`, §45.3). Every one of these is driven over REST, which\n // has no session stream, so the org's webhook subscriptions are the only push a customer gets.\n \"wallet.created\",\n \"wallet.policy.updated\",\n \"wallet.transaction.confirmed\",\n \"wallet.swept\",\n \"card.issued\",\n \"card.failed\",\n \"card.cancelled\",\n \"card.refunded\",\n \"card.credentials_revealed\",\n]);\nexport type EventType = z.infer<typeof EventTypeSchema>;\n\nexport const EventSchema = z.object({\n id: idOf(\"evt\"),\n seq: z.number().int().positive(),\n type: EventTypeSchema,\n session_id: idOf(\"ses\"),\n data: z.record(z.string(), z.unknown()),\n created_at: Timestamp,\n});\nexport type Event = z.infer<typeof EventSchema>;\n\n/**\n * `thread.*` data. Loose on purpose: `thread_id` is the whole added contract, and each event is\n * free to carry more (which member, why it stopped) without a schema change per field.\n */\nexport const ThreadEventDataSchema = z.looseObject({ thread_id: idOf(\"ses\") });\n\n/**\n * `tool.confirm.resolved` data (§8, ADR-0764). `decision` and `scope` are the `tool_confirmations`\n * vocabulary (§7). `actor` is `null` only for a decision queued by a caller that predates it;\n * `proposed_args` is `null` when no parked row matched; `final_args` is what runs — the person's\n * edit of a template install's answers (ADR-1030), otherwise equal to `proposed_args`.\n */\nexport const ToolConfirmResolvedDataSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().nullable(),\n scope: z.enum([\"call\", \"session\"]),\n actor: PrincipalSchema.nullable(),\n decided_at: Timestamp,\n proposed_args: z.record(z.string(), z.unknown()).nullable(),\n final_args: z.record(z.string(), z.unknown()).nullable(),\n});\nexport type ToolConfirmResolvedData = z.infer<typeof ToolConfirmResolvedDataSchema>;\n\n/**\n * `tool.confirm.answered` data (§8, ADR-1049): the answers exactly as `POST …/answers` took them.\n * Without it an answer reached only the model's transcript, and no reader of the log could say what\n * the person had said.\n */\nexport const ToolConfirmAnsweredDataSchema = z.object({\n tool_call_id: z.string(),\n answers: AnswersSchema,\n answered_at: Timestamp,\n});\nexport type ToolConfirmAnsweredData = z.infer<typeof ToolConfirmAnsweredDataSchema>;\n\n/** `session.usage` data — emitted before every idle/terminal transition (§10, §15). */\nexport const SessionUsageDataSchema = z.object({\n token_usage: TokenUsageSchema,\n consumed_micro_usd: MicroUsdField.nonnegative(),\n active_seconds: z.number().nonnegative(),\n tool_calls: z.number().int().nonnegative(),\n});\n","/**\n * The team board — the shared, durable coordination surface a coordinator session and every thread\n * it delegates to read and write (canonical-spec §28).\n *\n * The statuses are **fixed**, not configurable columns. A per-team column list would make every\n * board tool's contract depend on the agent's config: `board_write` could not name a legal status\n * without first reading the board, and no two teams' transcripts would be comparable. Four states\n * cover the thing a board is for — what is queued, what is being worked, what is stuck, what is\n * finished — and `blocked_by` carries the *reason* a card is stuck as data rather than as a lane.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const BOARD_STATUSES = [\"todo\", \"doing\", \"blocked\", \"done\"] as const;\nexport const BoardStatusSchema = z.enum(BOARD_STATUSES);\nexport type BoardStatus = z.infer<typeof BoardStatusSchema>;\n\n/**\n * How many cards stand in each column. Written out as four fields rather than a record keyed by\n * `BoardStatusSchema` for the same reason the statuses are fixed: a reader is owed all four keys\n * even when a column is empty, and a partial record would make `0` and \"absent\" the same answer.\n */\nexport const BoardCountsSchema = z.object({\n todo: z.number().int().nonnegative(),\n doing: z.number().int().nonnegative(),\n blocked: z.number().int().nonnegative(),\n done: z.number().int().nonnegative(),\n});\nexport type BoardCounts = z.infer<typeof BoardCountsSchema>;\n\n/**\n * One board per **agent** — `unique (org_id, agent_id)`, migration 0024 — so a team's cards outlive\n * the coordinator session that opened them. This said `session_id` until the board object reached\n * the wire, which was a description of a board nothing had ever stored.\n *\n * The counts are the whole reason the object is worth serving. Everything else on a board is\n * already on its cards; how many stand in each column is the one fact a page of cards cannot state,\n * because a page is truncated and a count is not.\n */\nexport const BoardSchema = z.object({\n id: idOf(\"brd\"),\n object: z.literal(\"board\"),\n agent_id: idOf(\"agt\"),\n cards: BoardCountsSchema,\n created_at: Timestamp,\n});\nexport type Board = z.infer<typeof BoardSchema>;\n\n/**\n * A unit of work. `assignee` is an agent's name — not an id — because that is what a coordinator\n * writes in a tool call and what a member recognises as itself; `null` is unclaimed.\n *\n * Assignment is the wake (§28.18): `woken_session_id` is the session the board started for the\n * assignee, `null` until it has — which is what makes the card *due*. `reported_status` is the\n * `done`/`blocked` the board's owner was last told about. Neither is writable by a client.\n */\nexport const BoardCardSchema = z.object({\n id: idOf(\"crd\"),\n object: z.literal(\"board_card\"),\n board_id: idOf(\"brd\"),\n title: z.string().min(1),\n /** The brief — what was asked. */\n body: z.string(),\n /** What the holder wrote back; a `done` carries one. */\n note: z.string().nullable().default(null),\n status: BoardStatusSchema,\n assignee: z.string().nullable(),\n /** The cards this one waits on. A `blocked` card with an empty list is stuck on the world. */\n blocked_by: z.array(idOf(\"crd\")),\n // The wake fields default on read: a reader whose API predates one still gets the card (§28.11).\n woken_session_id: idOf(\"ses\").nullable().default(null),\n reported_status: BoardStatusSchema.nullable().default(null),\n /** Sessions the board has started for this card; the third is its last (§28.18). */\n wake_count: z.number().int().nonnegative().default(0),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type BoardCard = z.infer<typeof BoardCardSchema>;\n\n/** The team's channel on a card: any thread can add one, the whole team reads it. */\nexport const BoardCommentSchema = z.object({\n id: idOf(\"bcm\"),\n object: z.literal(\"board_comment\"),\n card_id: idOf(\"crd\"),\n /**\n * Who wrote it, as an id the server derived — never a name the caller supplied. A member's\n * comment carries the `ses_` id of the thread that wrote it; a person's carries their `usr_` or\n * `key_` principal. The prefix is what lets a reader tell an agent's comment from a person's,\n * which is the distinction a free-text author field could not make and could be used to forge.\n */\n author: z.string(),\n body: z.string(),\n created_at: Timestamp,\n});\nexport type BoardComment = z.infer<typeof BoardCommentSchema>;\n","/**\n * Identities — the named personas an agent acts as (`canonical-spec §22`).\n *\n * An identity is a small durable record: a `name` and a `description` the model reads so it knows\n * *who it is being*, plus the concrete endpoints that persona owns. The endpoints are deliberately\n * **specific strings, never booleans** — an identity does not \"have email\", it owns\n * `ava@acme-mail.com` — because routing, policy scoping and inbound matching all key off the exact\n * address (`docs/identity/personas.mdx`).\n *\n * The four endpoint arrays are denormalised reads of four sub-resources this build does not serve:\n * domains, inboxes, numbers and connections each need a vendor credential that does not exist yet\n * (see `progress.md`). They are on the object because the wire contract publishes them and a caller\n * must be able to read `[]` and know the answer is \"none\", rather than have the field vanish and\n * not know whether it asked the wrong question. Nothing writes them today.\n */\n\nimport { z } from \"zod\";\nimport { Metadata, Timestamp, idOf } from \"./common\";\n\n/** Bounded because it is surfaced to the model verbatim, and an unbounded name is a prompt. */\nexport const IDENTITY_NAME_MAX = 128;\nexport const IDENTITY_DESCRIPTION_MAX = 1024;\n\nexport const IdentitySchema = z.object({\n id: idOf(\"idn\"),\n object: z.literal(\"identity\"),\n /** Human-facing persona name. Surfaced to the model so it acts in character. */\n name: z.string().min(1).max(IDENTITY_NAME_MAX),\n /** What the persona is for. The model reads it to choose tone, scope and endpoint. */\n description: z.string().max(IDENTITY_DESCRIPTION_MAX).nullable(),\n /** Inbox addresses (`localpart@domain`) this identity owns. */\n emails: z.array(z.string()),\n /** Provisioned numbers in E.164. */\n phones: z.array(z.string()),\n /** Verified web domains reachable through this identity's inboxes. */\n domains: z.array(z.string()),\n /** `conn_` ids of authorized third-party connections. */\n connections: z.array(z.string()),\n metadata: Metadata,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Identity = z.infer<typeof IdentitySchema>;\n","/** Computers, snapshots, volumes, skills, files, deployments (canonical-spec §2, §12, §13). */\n\nimport { z } from \"zod\";\nimport { BrowserOptionsSchema } from \"./browser\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, WindowSchema, idOf } from \"./common\";\nimport { FileLibraryFieldsSchema } from \"./files-library\";\nimport { SessionStatusSchema } from \"./session\";\n\nexport const ComputerStatusSchema = z.enum([\"creating\", \"running\", \"paused\", \"failed\", \"destroyed\"]);\nexport type ComputerStatus = z.infer<typeof ComputerStatusSchema>;\n\nexport const VolumeSchema = z.object({\n id: idOf(\"vol\"),\n size_gb: z.number().int().positive(),\n mount_path: z.string(),\n});\n\nexport const ComputerSchema = z.object({\n id: idOf(\"cmp\"),\n object: z.literal(\"computer\"),\n name: z.string(),\n vcpu: z.number().int().positive(),\n memory_mb: z.number().int().positive(),\n disk_gb: z.number().int().positive(),\n status: ComputerStatusSchema,\n // core-gaps: U2-browser-api — the whole option object (§32.2); `{ allowed_domains }` still parses.\n browser: BrowserOptionsSchema.nullable(),\n volume: VolumeSchema.nullable(),\n snapshot_id: idOf(\"snp\").nullable(),\n /**\n * The agent this computer belongs to (§41.8, ADR-0849); `null` for one made by `POST /v1/computers`.\n * Defaulted so a reply from an older control plane parses.\n */\n agent_id: idOf(\"agt\").nullable().default(null),\n created_at: Timestamp,\n});\nexport type Computer = z.infer<typeof ComputerSchema>;\n\nexport const SnapshotSchema = z.object({\n snapshot_id: idOf(\"snp\"),\n computer_id: idOf(\"cmp\"),\n created_at: Timestamp,\n});\n\n/** Computer workspace (§41): what a box is doing, what ran on it, what is on it, what browsed from it. */\n\n/** One in-VM sample (§41.1). `null` on the inspect of anything but a `running` box — a read never wakes one. */\nexport const ComputerProbeSchema = z.object({\n sampled_at: Timestamp,\n uptime_seconds: z.number().int().nonnegative(),\n processes: z.number().int().nonnegative(),\n load_1m: z.number().nonnegative(),\n memory_used_mb: z.number().int().nonnegative(),\n memory_total_mb: z.number().int().positive(),\n disk_used_gb: z.number().nonnegative(),\n disk_total_gb: z.number().positive(),\n});\nexport type ComputerProbe = z.infer<typeof ComputerProbeSchema>;\n\nexport const ComputerInspectSchema = z.object({\n object: z.literal(\"computer_inspect\"),\n id: idOf(\"cmp\"),\n status: ComputerStatusSchema,\n last_active_at: Timestamp.nullable(),\n /** Where the provider's file API is rooted (§41.1); `null` when it does not say. */\n home: z.string().min(1).nullable(),\n probe: ComputerProbeSchema.nullable(),\n});\nexport type ComputerInspect = z.infer<typeof ComputerInspectSchema>;\n\n/** Output cap per stream on a recorded command (§41.3); a cut sets `truncated`. */\nexport const COMMAND_OUTPUT_CAP = 65_536;\n\nexport const ComputerCommandSchema = z.object({\n id: idOf(\"cmd\"),\n object: z.literal(\"computer_command\"),\n computer_id: idOf(\"cmp\"),\n command: z.string(),\n exit_code: z.number().int().nullable(),\n timed_out: z.boolean(),\n duration_ms: z.number().int().nonnegative(),\n stdout: z.string().max(COMMAND_OUTPUT_CAP),\n stderr: z.string().max(COMMAND_OUTPUT_CAP),\n truncated: z.boolean(),\n actor: PrincipalSchema,\n created_at: Timestamp,\n});\nexport type ComputerCommand = z.infer<typeof ComputerCommandSchema>;\n\n/** One `data:` frame of `POST …/exec/stream` (§41.2): output as it arrives, then exactly one `exit`. */\nexport const ExecStreamFrameSchema = z.union([\n z.object({ stdout: z.string() }),\n z.object({ stderr: z.string() }),\n z.object({\n exit: z.object({\n exit_code: z.number().int().nullable(),\n timed_out: z.boolean(),\n duration_ms: z.number().int().nonnegative(),\n command_id: idOf(\"cmd\"),\n }),\n }),\n]);\nexport type ExecStreamFrame = z.infer<typeof ExecStreamFrameSchema>;\n\nexport const FileEntryTypeSchema = z.enum([\"file\", \"directory\", \"symlink\", \"other\"]);\nexport const FileEntrySchema = z.object({\n name: z.string().min(1),\n path: z.string().min(1),\n type: FileEntryTypeSchema,\n size_bytes: z.number().int().nonnegative(),\n /** POSIX `st_mode`. */\n mode: z.number().int().nonnegative(),\n modified_at: Timestamp.nullable(),\n});\nexport type FileEntry = z.infer<typeof FileEntrySchema>;\n\nexport const ComputerUpdateSchema = z.strictObject({ name: z.string().min(1).max(200) });\nexport type ComputerUpdate = z.infer<typeof ComputerUpdateSchema>;\n\nexport const SkillSchema = z.object({\n id: idOf(\"skl\"),\n object: z.literal(\"skill\"),\n name: z.string(),\n description: z.string().nullable(),\n latest_version: z.number().int().positive(),\n created_at: Timestamp,\n});\n\n/**\n * One of an agent's `skills[]` entries, resolved at session start (§13): `slug` took the latest\n * version *then*, `slug@N` is frozen at `N`, and neither moves for the life of the session.\n *\n * It travels API → session runtime because that is where the two things that need it live: the\n * harness advertises `name`/`description` to the model and serves the body from `storage_key` on\n * demand (ADR-0106.4), and `read_skill` reads the same key. Resolving again inside the runtime\n * would re-resolve a floating `slug` mid-session, which §13 forbids.\n */\nexport const ResolvedSkillRefSchema = z.object({\n /** The reference exactly as the agent version wrote it: `slug` or `slug@N`. */\n ref: z.string().min(1),\n slug: z.string().min(1),\n version: z.number().int().positive(),\n description: z.string(),\n storage_key: z.string().min(1),\n});\n\nexport type ResolvedSkillRef = z.infer<typeof ResolvedSkillRefSchema>;\n\n/** Skill versions are immutable and content-addressed (§13). */\nexport const SkillVersionSchema = z.object({\n version: z.number().int().positive(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n size_bytes: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\n\n/**\n * One version of a skill the PLATFORM ships (§31.9) — the `naive/slug` half of §13's grammar. No\n * `id` and no organization: the catalogue is identical for every tenant and is addressed by\n * `(slug, version)` and nothing else. `content_hash` is the same lowercase sha-256 an organization\n * skill version carries as `sha256`; identical bytes never mint a version.\n *\n * The list (`GET /v1/skills/catalog`) returns this, newest version per slug, WITHOUT the body — the\n * body is the expensive half and is read on the version route (§13's progressive disclosure).\n */\nexport const SkillCatalogEntrySchema = z.object({\n object: z.literal(\"skill_catalog_entry\"),\n slug: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),\n version: z.number().int().positive(),\n name: z.string().min(1),\n description: z.string(),\n tags: z.array(z.string().min(1)),\n content_hash: z.string().regex(/^[0-9a-f]{64}$/),\n published_at: Timestamp,\n});\nexport type SkillCatalogEntry = z.infer<typeof SkillCatalogEntrySchema>;\n\n/** `GET /v1/skills/catalog/{slug}/versions/{n}` — the entry with its `SKILL.md` body. */\nexport const SkillCatalogVersionSchema = SkillCatalogEntrySchema.extend({ content: z.string() });\nexport type SkillCatalogVersion = z.infer<typeof SkillCatalogVersionSchema>;\n\nexport const FileSchema = z.object({\n id: idOf(\"fil\"),\n object: z.literal(\"file\"),\n name: z.string(),\n content_type: z.string(),\n size_bytes: z.number().int().nonnegative(),\n scope: z.enum([\"session\", \"published\"]),\n session_id: idOf(\"ses\").nullable(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n created_at: Timestamp,\n // The asset-library fields (`canonical-spec §36.1`), all nullable or defaulted.\n ...FileLibraryFieldsSchema.shape,\n /** The agent of `session_id`, joined at read (§36.1, ADR-0887); a writer never sets it. */\n agent_id: idOf(\"agt\").nullable().optional(),\n});\n/** `File` is a DOM global on a Worker, so the wire object is `FileObject` in TypeScript. */\nexport type FileObject = z.infer<typeof FileSchema>;\n\n/**\n * Whether a schedule will actually fire, which `enabled` alone cannot say (ADR-0104):\n * `paused` is `enabled: false`, and `unscheduled` is an enabled schedule on a deploy that runs no\n * clock — its `next_run_at` is `null`, because a date no tick will ever honour is worse than none.\n */\nexport const ScheduleStatusSchema = z.enum([\"scheduled\", \"paused\", \"unscheduled\"]);\nexport type ScheduleStatus = z.infer<typeof ScheduleStatusSchema>;\n\n/** A cron deployment. `agent_version` pins the exact version that fires (§12). */\nexport const DeploymentSchema = z.object({\n id: idOf(\"dep\"),\n object: z.literal(\"deployment\"),\n agent_id: idOf(\"agt\"),\n /** A pin. `null` tracks the agent's `current_version` on every fire (§12). */\n agent_version: z.number().int().positive().nullable(),\n cron: z.string(),\n /** IANA zone the `cron` is read in. \"0 9 * * 1\" means 09:00 *here*, across DST (ADR-0074). */\n timezone: z.string(),\n input_template: z.string(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n window: WindowSchema,\n /**\n * URL POSTed with the `session.idle` envelope when a fire goes idle; `null` pushes nothing.\n *\n * `https` for the same reason `POST /v1/webhooks` requires it — setting this materialises one of\n * those endpoints, and a signed delivery over cleartext is not a delivery. Until the push was\n * wired this field went nowhere, so nothing can be relying on an `http://` value (ADR-0161).\n */\n on_idle: z.url().startsWith(\"https://\", { error: \"a webhook URL must be https\" }).nullable(),\n /**\n * The persona every fire speaks as, or `null` to run as nobody (§22). Written as an `idn_` id\n * **or** the persona's name, the way a session names one, and always echoed as the id: a fire at\n * 3am must not be silenced by someone renaming the persona at noon.\n */\n identity: idOf(\"idn\").nullable(),\n enabled: z.boolean(),\n /** Derived per deploy, never stored — the row cannot know whether a clock is watching it. */\n schedule_status: ScheduleStatusSchema,\n /** The next fire, or `null` when nothing will fire it (`schedule_status` says which). */\n next_run_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Deployment = z.infer<typeof DeploymentSchema>;\n\n/** The persisted half: everything but the derived `schedule_status` (ADR-0104). */\nexport type StoredDeployment = Omit<Deployment, \"schedule_status\">;\n\nexport const DeploymentRunSchema = z.object({\n id: idOf(\"run\"),\n session_id: idOf(\"ses\"),\n status: SessionStatusSchema,\n started_at: Timestamp.nullable(),\n});\nexport type DeploymentRun = z.infer<typeof DeploymentRunSchema>;\n","/**\n * core-gaps: contracts — the library fields a file gains (`canonical-spec §36`). U7 composes them\n * into `FileSchema` with `FileSchema.extend(FileLibraryFieldsSchema.shape)`; every field is\n * nullable or defaulted so each existing row and writer stays valid.\n */\n\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\n\nexport const FILE_KINDS = [\"image\", \"video\", \"audio\", \"document\", \"other\"] as const;\nexport const FileKindSchema = z.enum(FILE_KINDS);\nexport type FileKind = z.infer<typeof FileKindSchema>;\n\nexport const FILE_SOURCE_TYPES = [\n \"upload\",\n \"url_import\",\n \"image_generation\",\n \"video_generation\",\n \"video_clipping\",\n \"screenshot\",\n \"speech_generation\",\n] as const;\nexport const FileSourceTypeSchema = z.enum(FILE_SOURCE_TYPES);\nexport type FileSourceType = z.infer<typeof FileSourceTypeSchema>;\n\nexport const FileSourceSchema = z.object({\n type: FileSourceTypeSchema,\n job_id: z.union([idOf(\"med\"), idOf(\"clj\")]).nullable(),\n url: z.string().url().nullable(),\n /** What a generator was asked with (§36.1, ADR-0886); absent on every other writer's row. */\n model: z.string().nullable().optional(),\n prompt: z.string().nullable().optional(),\n});\nexport type FileSource = z.infer<typeof FileSourceSchema>;\n\nexport const FileTagsSchema = z.array(z.string().min(1).max(64)).max(32);\n\nexport const FileLibraryFieldsSchema = z.object({\n title: z.string().max(256).nullable().default(null),\n description: z.string().max(4_096).nullable().default(null),\n tags: FileTagsSchema.default([]),\n kind: FileKindSchema.default(\"other\"),\n source: FileSourceSchema.nullable().default(null),\n thumbnail_file_id: idOf(\"fil\").nullable().default(null),\n width: z.number().int().positive().nullable().default(null),\n height: z.number().int().positive().nullable().default(null),\n duration_seconds: z.number().nonnegative().nullable().default(null),\n});\nexport type FileLibraryFields = z.infer<typeof FileLibraryFieldsSchema>;\n\n/** `PATCH /v1/files/{id}` — the three fields a customer edits. */\nexport const UpdateFileSchema = z.object({\n title: z.string().max(256).nullable().optional(),\n description: z.string().max(4_096).nullable().optional(),\n tags: FileTagsSchema.optional(),\n});\n\n/** `POST /v1/files/imports` — the route refuses private hosts and bodies over the upload cap. */\nexport const ImportFileSchema = z.object({\n url: z.string().url().startsWith(\"http\"),\n title: z.string().max(256).optional(),\n description: z.string().max(4_096).optional(),\n tags: FileTagsSchema.optional(),\n});\n\n/** `content_type` → `kind`, decided once at write and stored. */\nexport function fileKindOf(contentType: string): FileKind {\n const lower = contentType.toLowerCase();\n const [type] = lower.split(\"/\");\n if (type === \"image\" || type === \"video\" || type === \"audio\") return type;\n if (type === \"text\" || lower.includes(\"pdf\") || lower.includes(\"document\")) {\n return \"document\";\n }\n return \"other\";\n}\n","/**\n * The three identity primitives that touch the outside world — a **web domain**, an **email\n * inbox** on it, and a **phone number** — plus the normalised **inbound message** that arrives at\n * either endpoint and the **outbound message** one sent (`canonical-spec §24`,\n * `docs/identity/{domains,email,phone,inbound}.mdx`).\n *\n * The gates at the bottom are the whole point of this file. A domain carries four independent\n * readiness tracks and each capability hangs off exactly one of them; a number cannot text until a\n * carrier has approved its campaign. Those rules are pure functions here, tested here, and called\n * from the routes — so \"deliverable\" is a computed fact and never an assumption. Sending mail from\n * a domain whose SPF/DKIM is not published is the worst outcome available to us: it does not fail,\n * it silently lands in spam.\n */\n\nimport { z } from \"zod\";\nimport { VettaError } from \"../errors\";\nimport { PrincipalSchema, Timestamp, idOf } from \"./common\";\n\n// ── Domain ────────────────────────────────────────────────────────────────────\n\n/**\n * Where the domain lives. A purchased domain uses the same mail/DNS readiness tracks, but its\n * creation is separately gated by `billing:write` and an explicit live-price ceiling.\n */\nexport const DomainKindSchema = z.enum([\"system\", \"external\", \"purchased\"]);\nexport type DomainKind = z.infer<typeof DomainKindSchema>;\n\n/** Email/company track. `failed` is ours: the docs give no terminal state and one is needed. */\nexport const DomainStatusSchema = z.enum([\"pending_dns\", \"active\", \"failed\"]);\n/** Mail DNS (SPF/DKIM) track — what **sending** hangs on. */\nexport const DomainDnsStatusSchema = z.enum([\"pending_verification\", \"provisioned\", \"failed\"]);\n/**\n * Inbound (MX) track — what **receiving** hangs on. Not in `docs/identity/domains.mdx`, which\n * gates receive on \"verified for inbound at the email layer\" in two tables and then exposes no\n * field for it, leaving the gate unqueryable. Doc-fix owed (ADR-0119).\n */\nexport const DomainInboundStatusSchema = z.enum([\"pending\", \"verified\", \"failed\"]);\n/** App/HTTP track, entirely independent of the three above. */\nexport const DomainAppConnectStatusSchema = z.enum([\"pending\", \"connected\", \"failed\"]);\n\nexport const DnsRecordSchema = z.object({\n type: z.enum([\"TXT\", \"CNAME\", \"MX\"]),\n host: z.string(),\n value: z.string(),\n priority: z.number().int().nullable(),\n /** Vetta owns this record: `_dmarc`, DKIM, inbound MX. The agent may read it, never write it. */\n managed: z.boolean(),\n});\nexport type DnsRecord = z.infer<typeof DnsRecordSchema>;\n\nexport const DomainSchema = z.object({\n id: idOf(\"dom\"),\n object: z.literal(\"domain\"),\n /** A domain belongs to the **organization**, not to one identity: two identities share one. */\n name: z.string(),\n kind: DomainKindSchema,\n status: DomainStatusSchema,\n dns_status: DomainDnsStatusSchema,\n inbound_status: DomainInboundStatusSchema,\n app_connect_status: DomainAppConnectStatusSchema,\n records: z.array(DnsRecordSchema),\n last_verified_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type Domain = z.infer<typeof DomainSchema>;\n\n/** A fully-qualified domain name, lowercase, no trailing dot. */\nexport const FQDN = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/;\n\n/**\n * Records the agent may never edit — DKIM, DMARC and the inbound MX keep mail working at all.\n *\n * Matched **label by label**, not by suffix: an email layer asked for a subdomain returns its\n * records relative to the registrable zone, so DKIM for `sub.example.com` arrives as the host\n * `sel._domainkey.sub`. A suffix test calls that editable and invites an agent to delete the key\n * that signs its own mail (observed live, 2026-08-22).\n */\nexport function isManagedHost(host: string): boolean {\n const h = host.toLowerCase().replace(/\\.$/, \"\");\n if (h === \"@\") return true;\n return h.split(\".\").some((label) => label === \"_dmarc\" || label === \"_domainkey\");\n}\n\n// ── Email inbox ───────────────────────────────────────────────────────────────\n\n/** Manual localparts: the documented character class, floored at 2 and capped at RFC 5321's 64. */\nexport const LOCALPART = /^[a-z0-9._-]{2,64}$/;\n/** Auto-provisioned localparts are derived from the agent name and capped at 32. */\nexport const AUTO_LOCALPART_MAX = 32;\n\nexport const EmailInboxSchema = z.object({\n id: idOf(\"eml\"),\n object: z.literal(\"email_inbox\"),\n identity_id: idOf(\"idn\"),\n domain_id: idOf(\"dom\"),\n address: z.string(),\n localpart: z.string(),\n /** Inbound routing keys off this: mail to the address wakes exactly this agent. */\n owning_agent_id: idOf(\"agt\"),\n status: z.enum([\"active\", \"disabled\"]),\n created_at: Timestamp,\n});\nexport type EmailInbox = z.infer<typeof EmailInboxSchema>;\n\n/** `\"Ava Sales\"` → `ava-sales`, then `ava-sales-2`, `ava-sales-3` … against what is already taken. */\nexport function autoLocalpart(agentName: string, taken: ReadonlySet<string>): string {\n const base =\n agentName\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, AUTO_LOCALPART_MAX)\n .replace(/-+$/, \"\") || \"agent\";\n if (!taken.has(base)) return base;\n for (let n = 2; ; n += 1) {\n const suffix = `-${n}`;\n const candidate = `${base.slice(0, AUTO_LOCALPART_MAX - suffix.length)}${suffix}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n\n// ── Phone number ──────────────────────────────────────────────────────────────\n\n/** `sole_prop`, not the docs' CLI `sole-prop`: every other enum on the wire is snake_case. */\nexport const PhoneTierSchema = z.enum([\"sole_prop\", \"standard\"]);\nexport const BrandStatusSchema = z.enum([\"none\", \"pending_verification\", \"verified\", \"rejected\"]);\nexport const CampaignStatusSchema = z.enum([\"none\", \"pending\", \"approved\", \"rejected\"]);\n\nexport const PhoneNumberSchema = z.object({\n id: idOf(\"pho\"),\n object: z.literal(\"phone_number\"),\n identity_id: idOf(\"idn\"),\n e164: z.string(),\n country: z.string(),\n capabilities: z.object({\n /** Live the moment the number is bought — inbound never waits on carrier registration. */\n sms_inbound: z.boolean(),\n /** True **iff** `campaign_status === \"approved\"`. Nothing else may set it. */\n sms_outbound: z.boolean(),\n /** Voice is not a P2 capability; the field exists so its absence is explicit. */\n voice: z.literal(false),\n }),\n tier: PhoneTierSchema,\n brand_status: BrandStatusSchema,\n campaign_status: CampaignStatusSchema,\n provisioned_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type PhoneNumber = z.infer<typeof PhoneNumberSchema>;\n\nexport const E164 = /^\\+[1-9]\\d{6,14}$/;\n\n// ── Inbound message ───────────────────────────────────────────────────────────\n\nexport const InboundMessageSchema = z.object({\n id: idOf(\"inb\"),\n object: z.literal(\"inbound_message\"),\n channel: z.enum([\"email\", \"sms\"]),\n identity_id: idOf(\"idn\"),\n /** The `eml_`/`pho_` endpoint it arrived at — the persona is decided by *where*, not by *who*. */\n endpoint_id: z.string(),\n from: z.string(),\n to: z.string(),\n subject: z.string().nullable(),\n text: z.string(),\n /** SPF/DKIM/DMARC for mail, carrier origin for SMS. Kept for the audit of why it was accepted. */\n auth: z.record(z.string(), z.string()),\n /** The session this message woke. Null until the wake seam lands (see ADR-0120). */\n session_id: idOf(\"ses\").nullable(),\n received_at: Timestamp,\n /**\n * When a person marked it read (`POST …/messages/{mid}/read`); `null` is unread. Defaulted so a\n * reply from an older control plane parses (ADR-1076).\n */\n read_at: Timestamp.nullable().default(null),\n});\nexport type InboundMessage = z.infer<typeof InboundMessageSchema>;\n\n// ── Outbound message ──────────────────────────────────────────────────────────\n\n/**\n * A message the persona sent, kept by us after the provider accepted it (ADR-1076). Written by\n * both doors that send: the API route (`actor` names the key or person) and the `email.send` tool\n * (`sent_by_agent_id` names the agent). Only mail is recorded today; `channel` is the inbound\n * enum because a text is the same kind of row.\n */\nexport const OutboundMessageSchema = z.object({\n id: idOf(\"out\"),\n object: z.literal(\"outbound_message\"),\n channel: InboundMessageSchema.shape.channel,\n identity_id: idOf(\"idn\"),\n /** The `eml_` endpoint it was sent from. */\n endpoint_id: z.string(),\n from: z.string(),\n to: z.array(z.string()),\n subject: z.string().nullable(),\n text: z.string(),\n sent_by_agent_id: idOf(\"agt\").nullable(),\n actor: PrincipalSchema.nullable(),\n sent_at: Timestamp,\n});\nexport type OutboundMessage = z.infer<typeof OutboundMessageSchema>;\n\n// ── The gates ─────────────────────────────────────────────────────────────────\n\n/**\n * Creating an inbox needs the company track cleared. `job_not_ready` and not `validation_failed`:\n * the caller did nothing wrong and the call will succeed once DNS propagates, so a durable runtime\n * must retry rather than give up (ADR-0118).\n */\nexport function assertInboxCreatable(domain: Domain): void {\n if (domain.status === \"active\") return;\n throw new VettaError(\n \"job_not_ready\",\n `domain ${domain.name} is ${domain.status}; an inbox needs status \"active\"`,\n \"domain_id\",\n );\n}\n\n/** Sending needs SPF/DKIM published and verified. Un-gated, mail silently lands in spam. */\nexport function assertSendable(domain: Domain): void {\n if (domain.dns_status === \"provisioned\") return;\n throw new VettaError(\n \"job_not_ready\",\n `domain ${domain.name} is not deliverable: dns_status is ${domain.dns_status}, sending needs \"provisioned\"`,\n );\n}\n\n/**\n * Receiving needs MX in place. Not an assert: an inbound message for a domain that cannot receive\n * is **dropped**, never bounced back at the sender and never turned into a wake.\n */\nexport function canReceive(domain: Domain): boolean {\n return domain.inbound_status === \"verified\";\n}\n\n/** Outbound SMS is refused until the carrier campaign is approved — this is a legal gate, not ours. */\nexport function assertSmsSendable(phone: PhoneNumber): void {\n if (phone.campaign_status === \"approved\") return;\n throw new VettaError(\n \"compliance_pending\",\n `outbound messaging for ${phone.e164} is not registered yet: campaign is ${phone.campaign_status}`,\n );\n}\n\n/** The one invariant tying the two together — nothing else may write `sms_outbound`. */\nexport function smsCapabilities(campaign: z.infer<typeof CampaignStatusSchema>): {\n sms_inbound: boolean;\n sms_outbound: boolean;\n voice: false;\n} {\n return { sms_inbound: true, sms_outbound: campaign === \"approved\", voice: false };\n}\n","/**\n * Hosted web applications (`canonical-spec §29`). An app is an **organization-level** resource —\n * a deployed site with, for `fullstack`, a managed backend provisioned per app. It is never owned\n * by an agent: agents are immutable versioned config, an app is production infrastructure that\n * outlives any agent or session. Provenance lives in the audit log (§17).\n *\n * Nothing provider-shaped appears here: the hosting and backend project handles are server\n * columns, and the wire object carries only what a customer may see.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\nimport type { Scope } from \"./org\";\n\nexport const AppTypeSchema = z.enum([\"frontend_only\", \"fullstack\"]);\nexport type AppType = z.infer<typeof AppTypeSchema>;\n\n/** `deleted` is computed off the soft-delete column, never stored in the status column. */\nexport const AppStatusSchema = z.enum([\"provisioning\", \"active\", \"error\"]);\nexport type AppStatus = z.infer<typeof AppStatusSchema>;\n\n/**\n * The path of the MCP endpoint an app serves (`§29.1`) — an absolute path, so the runtime can\n * resolve it as `url + mcp` whatever the app's current canonical URL is. Shared by the API and IaC.\n */\nexport const AppMcpPathSchema = z.string().regex(/^\\/\\S*$/, \"must be an absolute path beginning with /\").max(128);\n\nexport const AppSchema = z.object({\n id: idOf(\"app\"),\n object: z.literal(\"app\"),\n name: z.string(),\n description: z.string().nullable(),\n type: AppTypeSchema,\n /**\n * The customer's own project name that made this app, or `null` for one made outside a project\n * (ADR-0375). Customer-visible, unlike the provider handles: it is the word the customer typed,\n * and the refusal that guards a name quotes it.\n */\n project: z.string().nullable(),\n status: AppStatusSchema,\n /** The address the app answers on — platform hostname until a custom domain connects. */\n url: z.string().nullable(),\n /** White-label words when `status` is `error`; never the provider's. */\n error: z.string().nullable(),\n /** Where the app serves MCP, or `null`. The bearer token for it is a server column. */\n mcp: AppMcpPathSchema.nullable(),\n /**\n * Is this a gated blueprint dashboard — one the Studio opens through `/apps/{id}/open` rather\n * than linking its `url` (`§29.1`)? True when the platform holds the app's `DASHBOARD_TOKEN`\n * or a secret of that name exists on the app; derived on read, never stored.\n */\n dashboard: z.boolean(),\n created_at: Timestamp,\n});\nexport type App = z.infer<typeof AppSchema>;\n\nexport const AppDeploymentStatusSchema = z.enum([\"queued\", \"building\", \"ready\", \"error\"]);\nexport type AppDeploymentStatus = z.infer<typeof AppDeploymentStatusSchema>;\n\nexport const AppDeploymentSchema = z.object({\n id: idOf(\"apd\"),\n object: z.literal(\"app_deployment\"),\n app_id: idOf(\"app\"),\n status: AppDeploymentStatusSchema,\n url: z.string().nullable(),\n error: z.string().nullable(),\n /** The client's opaque digest of the files, echoed verbatim so it can skip an unchanged deploy. */\n content_hash: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type AppDeployment = z.infer<typeof AppDeploymentSchema>;\n\n/** The file-map a deployment was posted with, kept so an agent can open and re-ship it (§29.2). */\nexport const AppDeploymentFilesSchema = z.object({\n object: z.literal(\"app_deployment_files\"),\n deployment_id: idOf(\"apd\"),\n files: z.record(z.string().min(1), z.string()),\n});\nexport type AppDeploymentFiles = z.infer<typeof AppDeploymentFilesSchema>;\n\n/** Metadata only — the value goes to the host project's environment and is never readable back. */\nexport const AppSecretSchema = z.object({\n object: z.literal(\"app_secret\"),\n name: z.string(),\n /** The client's opaque digest of the value, echoed verbatim so it can skip an unchanged write. */\n value_hash: z.string().nullable(),\n created_at: Timestamp,\n});\nexport type AppSecret = z.infer<typeof AppSecretSchema>;\n\n/**\n * A one-click way into an app that gates itself with a platform-generated bearer (`§29.7`).\n *\n * `ticket` is a short-lived, signed statement of who is opening the app — an HMAC keyed by the\n * app's `DASHBOARD_TOKEN`, never the value (§29.10) — and `url` is the app's own endpoint that trades one for a session\n * cookie. It is posted, not linked: a credential in a query string lands in the app's server logs,\n * the browser's history and every later `Referer`.\n */\nexport const AppEntrySchema = z.object({\n object: z.literal(\"app_entry\"),\n url: z.string(),\n ticket: z.string(),\n});\nexport type AppEntry = z.infer<typeof AppEntrySchema>;\n\n/**\n * How a person gets into an app's dashboard without the Studio (`§29.2`, `§29.7`): the app's\n * address and its platform-generated `DASHBOARD_PASSWORD`, `null` until one is provisioned. The\n * one audited reveal of an app secret — the password exists to be typed by a human (ADR-0656).\n */\nexport const AppAccessSchema = z.object({\n object: z.literal(\"app_access\"),\n url: z.string().nullable(),\n password: z.string().nullable(),\n});\nexport type AppAccess = z.infer<typeof AppAccessSchema>;\n\nexport const AppDomainStatusSchema = z.enum([\"pending\", \"connected\", \"failed\"]);\n\nexport const AppDomainSchema = z.object({\n object: z.literal(\"app_domain\"),\n app_id: idOf(\"app\"),\n domain_id: idOf(\"dom\"),\n domain: z.string(),\n status: AppDomainStatusSchema,\n created_at: Timestamp,\n});\nexport type AppDomain = z.infer<typeof AppDomainSchema>;\n\n/** `A-Z0-9_`, not starting with a digit — what every runtime accepts as an env name. */\nexport const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;\n\n/**\n * App names become provider project names and platform hostnames, so the grammar is the\n * DNS-label one: lowercase alphanumerics and hyphens, no edge hyphens, 63 max.\n */\nexport const APP_NAME = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/**\n * WHAT AN APP'S OWN KEY MAY HOLD (`§29.10`, ADR-1004, ADR-1009). An app asks, the owner approves\n * on a card, and the key carries exactly the approved subset. Reads are the default ask.\n * `files:read` is the whole company library, not the app's own files; the card says so.\n *\n * THE AGENT THAT WRITES THE APP CAN READ ITS KEY: it writes the server code that holds it. So no\n * scope here may reach past what that agent already has. `sessions:write` answers approval cards\n * (`POST /v1/sessions/{id}/tool_confirmations`) and `agents:write` rewrites any agent's tool\n * policy and every app's secrets and entry tickets: either one lets the agent approve itself. Only\n * `files:write` is left to ask for. Never `admin`, `billing:write`, `webhooks:*`, `audit:read`,\n * `computers:write` or `proxy:write` either: a key baked into an app must not mint keys, spend,\n * redirect traffic or run code.\n */\nexport const APP_READ_SCOPES = [\"agents:read\", \"sessions:read\", \"billing:read\", \"files:read\"] as const satisfies readonly Scope[];\nexport const APP_WRITE_SCOPES = [\"files:write\"] as const satisfies readonly Scope[];\nexport type AppScope = (typeof APP_READ_SCOPES)[number] | (typeof APP_WRITE_SCOPES)[number];\n\n/**\n * WHAT AN APP'S OWN KEY LETS IT DO (`§29.10`, ADR-1048): the union of the scopes of every live key\n * linked to the app (`api_key.app_id`), in every mode — never a key id, a prefix or a name. Empty\n * when no linked key is live. A key set by hand, or minted before keys named their app, is not here:\n * the Studio reads the app's `NAIVE_API_KEY` secret to say so rather than claim \"no access\".\n */\nexport const AppPermissionsSchema = z.object({\n object: z.literal(\"app_permissions\"),\n app_id: idOf(\"app\"),\n scopes: z.array(z.string()),\n});\nexport type AppPermissions = z.infer<typeof AppPermissionsSchema>;\n\n/**\n * THE APP ENGINEER'S MARKER (`§29.8`). The engineer is an ordinary agent that *points at* one app\n * through `metadata.role`/`metadata.app_id`; the dashboard hides it from every roster it draws, so\n * the marker is the only thing that can find it — and the only thing that can reap it when its app\n * goes. It lives here rather than in the studio because the delete route is the other reader.\n */\nexport const APP_ENGINEER_MARKER = \"app-engineer\" as const;\n\n/** Is this agent the engineer of that app? Metadata only: the marker is the whole relationship. */\nexport const isAppEngineerOf =\n (appId: string) =>\n (agent: { metadata: Record<string, unknown> }): boolean =>\n agent.metadata[\"role\"] === APP_ENGINEER_MARKER && agent.metadata[\"app_id\"] === appId;\n","/**\n * The blueprint install (`canonical-spec §29.6`) — one applied declaration per\n * (organization, project), and the drift a `revision_conflict` names.\n *\n * `naive up` needed no server-side state while the only writer was a person with a clone: its\n * working tree was the manifest. The studio applying the same declaration makes two writers on one\n * organization, and neither can see the other. This row is what they share.\n *\n * It is not a second source of truth for what is provisioned — apps, agents, skills, identities and\n * vaults stay keyed by name on their own routes. It records *that* an apply happened, with what, by\n * whom, and against which revision.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\n/** Which of the two writers applied a revision. */\nexport const BlueprintInstallSourceSchema = z.enum([\"studio\", \"cli\"]);\nexport type BlueprintInstallSource = z.infer<typeof BlueprintInstallSourceSchema>;\n\n/**\n * Whether one revision's reconcile is finished (§29.6). `report: null` alone cannot say: an apply\n * that only recorded and a hosted apply that has not run yet look the same without it. A hosted apply\n * a signed-in person makes answers `pending` and runs after the response; the row moves to `applied`\n * when the report is stamped, or to `failed` with `failure` set when the run threw. An install\n * recorded for a company still being set up is `held`: nothing is built until it is activated, and\n * then it moves to `pending` (ADR-1108).\n */\nexport const BlueprintInstallStatusSchema = z.enum([\"held\", \"pending\", \"applied\", \"failed\"]);\nexport type BlueprintInstallStatus = z.infer<typeof BlueprintInstallStatusSchema>;\n\n/**\n * What one apply did to one resource. This is the vocabulary `naive up` has printed since it\n * existed; it is written HERE, and imported by `@usenaive-sdk/blueprints`, for the reason\n * `CLAUDE.md §2` gives: the hosted apply publishes the engine's report on the install (below), so\n * it is a wire shape, and a wire shape has exactly one definition. The engine re-exports these two\n * names unchanged, so nothing downstream of it learns a second word for the same thing.\n */\nexport const ResourceActionSchema = z.enum([\"created\", \"updated\", \"unchanged\", \"deleted\", \"refused\"]);\nexport type ResourceAction = z.infer<typeof ResourceActionSchema>;\n\n/** One line of an apply: what was named, what happened to it, and — for a refusal — why. */\nexport const ResourceReportSchema = z.object({\n name: z.string().min(1),\n action: ResourceActionSchema,\n /** The `agt_`/`app_`/`ses_`… the line resolved to. Absent on a refusal that never got an id. */\n id: z.string().optional(),\n /** An app's hostname once its build went live; `null` while it has none. Apps only. */\n url: z.string().nullable().optional(),\n /**\n * What a TASK is called and who owes it. `name` is the declaration key (`first-render`), which is\n * how a re-apply finds the same card and is not a sentence anybody wants read to them. The\n * dashboard's opening message lists the team's work, so it needs the title the board shows and the\n * seat that holds it. Tasks only.\n */\n title: z.string().optional(),\n assignee: z.string().optional(),\n /**\n * A SCHEDULE'S brief, in one short line — the opening sentence of its `input_template`. A\n * schedules line is named `<agent> @ <cron>`, which says when something runs and nothing at all\n * about what it does, so a roadmap built from these lines could only ever have been a timetable.\n * Written here rather than read back from the deployment so the receipt stays the one read the\n * welcome needs. Schedules only.\n */\n summary: z.string().optional(),\n reason: z.string().optional(),\n});\nexport type ResourceReportLine = z.infer<typeof ResourceReportSchema>;\n\n/**\n * What an apply DID — the engine's own `UpReport`, minus the two fields that are answers to a\n * question nobody asks a stored row (`dry_run`, and the pair naming the crew, which the install\n * already carries in `blueprint`/`template`).\n *\n * `intake` is its own list rather than a line under `agents` because an intake line's `id` is a\n * `ses_`: folding it in would put a session id in the field a reader uses to find an agent\n * (ADR-0410). `skipped` names live rows the engine could not parse and stepped over. `deselected`\n * names the agents and apps the operator's `selection` left out (§31.2) — a choice, kept apart from\n * `skipped` (a failure to read) and `refused` (a failure to do). Defaulted, because every report\n * stored before it was written without it and means \"nothing was left out\".\n */\nexport const BlueprintReportSchema = z.object({\n skills: z.array(ResourceReportSchema),\n identities: z.array(ResourceReportSchema),\n vaults: z.array(ResourceReportSchema),\n apps: z.array(ResourceReportSchema),\n agents: z.array(ResourceReportSchema),\n schedules: z.array(ResourceReportSchema),\n intake: z.array(ResourceReportSchema),\n /** One line per declared task (§31.11), `id` the card's `crd_`. Defaulted so older rows parse. */\n tasks: z.array(ResourceReportSchema).default([]),\n skipped: z.array(z.string()),\n deselected: z.array(z.string()).default([]),\n});\nexport type BlueprintReport = z.infer<typeof BlueprintReportSchema>;\n\n/**\n * Which of the declared crew an apply takes (§31.2), by declared name. Omitting it from the apply\n * body means everything; a selection missing a `required` agent or app is `validation_failed`.\n */\nexport const BlueprintSelectionSchema = z.object({\n agents: z.array(z.string().min(1)),\n apps: z.array(z.string().min(1)),\n});\nexport type BlueprintSelection = z.infer<typeof BlueprintSelectionSchema>;\n\nexport const BlueprintInstallSchema = z.object({\n id: idOf(\"bpi\"),\n object: z.literal(\"blueprint_install\"),\n /** The customer's own `defineProject({ name })` — the same word `app.project` stamps (§29.2). */\n project: z.string().min(1),\n /** The pair the declaration resolved to; `null` for a declaration that names no blueprint. */\n blueprint: z.string().nullable(),\n template: z.string().nullable(),\n /**\n * Applies, not versions of anything: 1 on the first apply, +1 on each one after, whichever writer\n * made it. It is not an agent version and it never rolls back.\n */\n revision: z.number().int().positive(),\n /**\n * The blueprint artifact version this came from, or `null` when it was applied from a working\n * tree — an operator editing a clone has no version to name.\n */\n artifact_version: z.string().nullable(),\n /**\n * The setup answers this project was configured with (§7.1 fields, keyed by their `key`), so a\n * re-apply does not re-ask and both writers configure from the same answers. Configuration only:\n * a secret is a vault credential (§23) or an app secret (§29.2), and neither is ever an answer.\n */\n answers: z.record(z.string(), z.unknown()),\n /**\n * NO `declaration` ON THE WIRE, and that is the reconciliation of §29.6 with §31.1.\n *\n * The applied bytes are stored — a `revision_conflict` names the paths two writers disagree at,\n * and it can only do that by holding what was applied. They are not published. An apply that\n * names a published `blueprint` and `template` sends no declaration: the server reads the\n * catalog's, which §31.1 says never leaves it. Echoing it back on the 201 (and again on every\n * later list) would hand any organization that can sign up the whole private config of a\n * blueprint it has installed nothing of — every agent's system prompt, its `mcp_servers`, its\n * vault credential declarations and its app `env` keys. A caller that sent a declaration already\n * has it, so nothing is lost by not saying it twice.\n */\n source: BlueprintInstallSourceSchema,\n /**\n * WHAT THE APPLY DID, or `null` when it did nothing but record.\n *\n * An apply that sends its own `declaration` has already reconciled it — that is what `naive up`\n * is — so the row it writes is a record and this is `null`. An apply that names a **published**\n * pair has reconciled nothing: it was never given the bytes (§31.1), so the server reads them\n * from the catalog and runs the same engine over them, and this is what that run reported.\n *\n * It is stored rather than only returned because a refusal inside a successful apply — an app\n * whose `env` reads a variable no hosted run has, a session refused for credit — is the one fact\n * a person needs after the screen that showed it is gone.\n */\n report: BlueprintReportSchema.nullable(),\n status: BlueprintInstallStatusSchema,\n /**\n * Why a `failed` run threw, in one sentence — or, on an `applied` row, which `required` agent or\n * app the apply refused and why (§29.6). `null` otherwise. Never a stack or a key.\n */\n failure: z.string().nullable(),\n /**\n * The `selection` the apply carried, or `null` — every row written before §31.2 and every apply\n * that omitted it, both meaning \"everything\". Defaulted so those rows parse unchanged.\n */\n selection: BlueprintSelectionSchema.nullable().default(null),\n /** When the answers were last edited through `PATCH …/installs/{id}` (§31.8); `null` if never. */\n context_updated_at: Timestamp.nullable().default(null),\n /**\n * What this install's agent, app, identity and vault names start with (§29.6, ADR-1104): `\"\"`\n * when its template's names were free in the organization, `\"<project>-\"` when any was already\n * another project's. Decided once, by the apply that created the row, and never again. `null` is\n * an install from before that rule, or one a working tree recorded: its names are the template's.\n * Optional only so a Worker from before the field still parses; this API always sends it.\n */\n name_prefix: z.string().nullable().optional(),\n applied_at: Timestamp,\n created_at: Timestamp,\n});\nexport type BlueprintInstall = z.infer<typeof BlueprintInstallSchema>;\n\n/** One answered setup question, as the crew reads it: the question's `label`, not just its `key`. */\nexport const ProjectContextAnswerSchema = z.object({\n key: z.string().min(1),\n label: z.string(),\n value: z.union([z.string(), z.array(z.string())]),\n});\nexport type ProjectContextAnswer = z.infer<typeof ProjectContextAnswerSchema>;\n\n/**\n * What a template's crew knows about the business it runs (§31.8): the install row's answers joined\n * to the artifact's questions, the report's apps with their URLs, and the crew with its roles.\n * Derived from the latest `applied` install and its report — only an edit to `answers` is stored.\n * `GET /v1/blueprints/installs/{id}/context`, the built-in `project_context` tool, and the\n * orchestrator's `vetta.blueprints_get_context` all return this one object.\n */\nexport const ProjectContextSchema = z.object({\n object: z.literal(\"project_context\"),\n project: z.string().min(1),\n blueprint: z.string().nullable(),\n template: z.string().nullable(),\n artifact_version: z.string().nullable(),\n answers: z.array(ProjectContextAnswerSchema),\n apps: z.array(z.object({ name: z.string().min(1), url: z.string().nullable() })),\n agents: z.array(z.object({ name: z.string().min(1), role: z.string().nullable() })),\n /** `context_updated_at` once the answers have been edited, `applied_at` until then. */\n updated_at: Timestamp,\n});\nexport type ProjectContext = z.infer<typeof ProjectContextSchema>;\n\n/**\n * How many drifted paths a `revision_conflict` message names before it says \"and N more\". A\n * declaration can disagree in hundreds of places and an unbounded refusal is unreadable; a bounded\n * one plus a count still tells the operator whether the other writer touched anything they own.\n */\nexport const DRIFT_PATHS_IN_MESSAGE = 20;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction walk(stored: unknown, incoming: unknown, at: string, into: string[]): void {\n if (isRecord(stored) && isRecord(incoming)) {\n for (const key of new Set([...Object.keys(stored), ...Object.keys(incoming)])) {\n walk(stored[key], incoming[key], at === \"\" ? key : `${at}.${key}`, into);\n }\n return;\n }\n if (Array.isArray(stored) && Array.isArray(incoming)) {\n for (let i = 0; i < Math.max(stored.length, incoming.length); i++) {\n walk(stored[i], incoming[i], `${at}.${i}`, into);\n }\n return;\n }\n if (JSON.stringify(stored ?? null) !== JSON.stringify(incoming ?? null)) into.push(at || \"(root)\");\n}\n\n/**\n * The paths at which a stored declaration and the one being applied disagree — `agents.2.model`,\n * `apps.0.mcp` — sorted, so two runs of the same conflict read the same.\n *\n * This is the canonical, key-sorted comparison `packages/blueprints/src/report.ts` already uses,\n * obtained structurally: the walk visits the union of an object's keys, so key ORDER is never a\n * change, while array order is meaning and is compared position by position. A key present on one\n * side and absent on the other is drift at that path — unlike `report.ts`'s `changed`, which is\n * asked about one declared field at a time and treats absence as \"not declared\". Here both sides\n * are whole declarations, so an added or dropped resource is exactly what an operator needs named.\n *\n * Computable server-side only because the declaration is stored, which is why storing it is not\n * redundancy (§29.6).\n */\nexport function driftedPaths(stored: unknown, incoming: unknown): string[] {\n const found: string[] = [];\n walk(stored, incoming, \"\", found);\n return found.sort();\n}\n","/**\n * The blueprint catalog (`canonical-spec §31`) — the built output of one blueprint × template ×\n * released version, published once and shared by every organization.\n *\n * A hosted run does not fork a blueprint into per-customer storage: the repository is\n * byte-identical for every operator, the template choice is one line out of a closed set, and the\n * answers, posts and accounts are runtime rows. So the build runs once per pair per release and\n * this is the row it produces.\n *\n * Nothing tenant-shaped appears here, and that is not an omission — the row has no `org_id` at all\n * (§31.1). Two of the things behind it never reach the wire either: each tree's `files_ref` is the\n * object-store key of that app's built bytes (the `provider_ref` posture, §29.1) and `declaration`\n * is the config only the reconciler reads. `questions`, `schedules`, `agents`, `apps` and\n * `identities` are the halves lifted out of it that a client genuinely needs — the crew because the\n * screen that asks a person to run a company has to show them the company first (§31.5), the\n * personas because it asks for their accounts before the crew exists (§31.10).\n */\n\nimport { z } from \"zod\";\nimport { SkillRefSchema } from \"./agent\";\nimport { AppTypeSchema } from \"./app\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { MiniAppIconSchema, MiniAppSlugSchema } from \"./mini-app\";\nimport { QuestionFieldSchema } from \"./session\";\nimport { SocialPlatformSchema } from \"./social\";\n\n/**\n * One timer this template's crew runs, flattened out of the declaration's `agents[].schedules[]`\n * so the landing page can print what a crew does before anyone has signed up (§31.3).\n *\n * `agent` is the declared agent's **name**, not an `agt_` id: at the moment this is printed no\n * agent exists to have one.\n */\nexport const BlueprintScheduleSchema = z.object({\n agent: z.string().min(1),\n cron: z.string().min(1),\n timezone: z.string().nullable(),\n /** The message each fire opens its session with — the sentence worth printing. */\n input: z.string().min(1),\n /** What a fire does in a few words, as the template says it (ADR-1172); absent on a row that declares none. */\n summary: z.string().min(1).optional(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type BlueprintSchedule = z.infer<typeof BlueprintScheduleSchema>;\n\n/**\n * One timer's cap as the operator set it on the apply (§29.6 `budgets`), naming the timer by the\n * same `(agent, cron)` the published `schedules` row carries — the only key a schedule has before it\n * is a deployment. The published `budget_micro_usd` is the recommendation this replaces.\n */\nexport const BlueprintBudgetSchema = BlueprintScheduleSchema.pick({ agent: true, cron: true, budget_micro_usd: true });\nexport type BlueprintBudget = z.infer<typeof BlueprintBudgetSchema>;\n\n/**\n * One agent this template provisions, flattened out of the declaration's `agents[]` (§31.5).\n *\n * A third half lifted out of `declaration` for the same reason the first two were: somebody outside\n * the reconciler needs it. Nobody should be asked to provision a company without being shown who is\n * in it, and the crew cannot be read off `schedules` — an agent with no timer would simply not\n * appear, which is exactly the coordinator a template is usually built around.\n *\n * `name` is the declared name, not an `agt_` id, for the reason it is on a schedule: at the moment\n * this is printed no agent exists to have one. `briefed` is whether the declaration gives this\n * agent an `intake` (§31.4) — the difference between a crew that is provisioned and a crew that has\n * started working, and the sentence a person is entitled to read before they pay for it. `intake`\n * is that first message's text, null when the declaration briefs nobody — and ABSENT on a row\n * published before this release, which is why it is optional (see `BlueprintAppSchema` below).\n *\n * `role` (two or three words beside the name), `skills` (§13 refs, verbatim), `tools` (the built-in\n * and `<app>.<tool>` names the declaration allows this agent, sorted) and `required` (whether an\n * install may leave it out, §31.2) are the WS12 v2 half of the same reading, optional for the same\n * reason: rows published before them lack them.\n */\nexport const BlueprintCrewSchema = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n model: z.string().min(1),\n briefed: z.boolean(),\n intake: z.string().nullable().optional(),\n /** What the first session may spend: the intake's own cap, else the agent's (§31.4). Set iff `briefed`. */\n intake_micro_usd: MicroUsdField.nonnegative().optional(),\n role: z.string().min(1).optional(),\n skills: z.array(SkillRefSchema).optional(),\n tools: z.array(z.string().min(1)).optional(),\n required: z.boolean().optional(),\n});\nexport type BlueprintCrew = z.infer<typeof BlueprintCrewSchema>;\n\n/**\n * One app this template deploys, flattened out of the declaration's `apps[]` (§31.5). `mcp` is the\n * path it serves MCP on (§29.5) or null; `tools` is the tool names (no `<app>.` prefix) any agent's\n * `tools.configs` names under it, sorted.\n *\n * *** THESE TWO AND `BlueprintCrewSchema.intake` ARE OPTIONAL, AND THAT IS THE ROLLOUT. ***\n *\n * A deploy does not rebuild the catalog: every published row was written by whichever release was\n * current when its blueprint released, and not one row live today carries any of the three. Making\n * them required makes the artifact a client cannot read the artifact the platform is serving —\n * and `apps/naive-lp-v2` parses that live catalog at build time and fails the build by design on a\n * row it cannot read, so every landing-page build between this deploy and the republish of every\n * artifact would hard-fail. Absent means \"the release that published this row did not carry it\";\n * every screen that reads them already draws that as an app with no MCP path and no tools.\n */\nexport const BlueprintAppSchema = z.object({\n name: z.string().min(1),\n type: AppTypeSchema,\n description: z.string().nullable(),\n mcp: z.string().nullable().optional(),\n tools: z.array(z.string().min(1)).optional(),\n /** Whether an install may deselect it (§31.2). Optional: the rollout argument above. */\n required: z.boolean().optional(),\n});\nexport type BlueprintApp = z.infer<typeof BlueprintAppSchema>;\n\n/**\n * One persona this template's crew acts as, flattened out of the declaration's `identities[]`\n * (§31.10). `name` is the declared name — the same name the apply's `upsertIdentity` finds it by.\n * Its accounts are connected after the apply, and they are where the crew posts (ADR-0922).\n */\nexport const BlueprintIdentitySchema = z.object({\n name: z.string().min(1),\n description: z.string().nullable(),\n});\nexport type BlueprintIdentity = z.infer<typeof BlueprintIdentitySchema>;\n\n/**\n * Lowercase sha-256 hex — exactly what `contentHash()` in `@usenaive-sdk/blueprints`\n * (`src/files.ts`) returns over a deployment's file map.\n *\n * §29.2's `content_hash` is a free string the server stores and never checks, because a *customer*\n * supplies it. This one is ours: an install skips the upload when it equals the newest deployment's\n * hash, so the two must be the same digest of the same bytes. Pinning the shape here is what turns\n * a drift into a failing parse instead of a silent re-upload on every install.\n */\nexport const ContentHashSchema = z.string().regex(/^[0-9a-f]{64}$/, \"a lowercase sha-256 hex digest\");\n\n/** One seeded card as the catalog prints it (§31.5): what it asks for, and whose it is (`null`: the CEO's to hand out). */\nexport const BlueprintTaskSchema = z.object({ title: z.string().min(1), assignee: z.string().min(1).nullable() });\nexport type BlueprintTask = z.infer<typeof BlueprintTaskSchema>;\n\n/** One mini app the template declares (§50), as a catalog lists it: its slug, name and tile. */\nexport const BlueprintMiniAppSchema = z.object({ slug: MiniAppSlugSchema, name: z.string().min(1), icon: MiniAppIconSchema });\nexport type BlueprintMiniApp = z.infer<typeof BlueprintMiniAppSchema>;\n\n/**\n * One app's built tree (§31.1). A blueprint ships as many as it declares with a `deploy_dir` —\n * `media` one, `agency` two (`dashboard` and `site`) — so the artifact addresses a tree PER APP,\n * keyed by the name the declaration gives it.\n *\n * The digest is per app because the skip is per app: §29.2 compares against a *deployment*, and a\n * deployment belongs to one app, so one hash over every tree would move whenever any single app\n * changed and send every other app's unchanged bytes up again on every install.\n *\n * The row's own entry also carries `files_ref`, the object-store key of these bytes. It is a\n * provider handle and stays server-side (§29.1) — and it stays there BY THIS SCHEMA: the store\n * parses stored trees through it on the way out, and zod's default strip is what removes the key.\n * A field added here reaches the wire; that is the thing to know before adding one.\n */\nexport const BlueprintTreeSchema = z.object({\n /** `apps[].name` in the declaration — the same name §31.5 prints and the install ensures by. */\n app: z.string().min(1),\n content_hash: ContentHashSchema,\n});\nexport type BlueprintTree = z.infer<typeof BlueprintTreeSchema>;\n\nexport const BlueprintArtifactSchema = z.object({\n id: idOf(\"bpa\"),\n object: z.literal(\"blueprint_artifact\"),\n /** The machine — its repository, screens and `/api/*`. */\n blueprint: z.string().min(1),\n /** Which of that blueprint's templates provides the crew. */\n template: z.string().min(1),\n /** The blueprint repository's own released version. Stored, never parsed (ADR-0401). */\n version: z.string().min(1),\n /**\n * What a person calls the template, one line on what its crew does, and the networks it publishes\n * to — printed, never provisioned (§31.5, ADR-0921). `platforms` is decoration: where the crew\n * posts is the accounts connected to its persona. Optional for the §31.5 rollout reason.\n */\n title: z.string().min(1).optional(),\n description: z.string().min(1).optional(),\n platforms: z.array(SocialPlatformSchema).optional(),\n /**\n * The built trees, one per deployable app, ordered as the declaration orders its apps. Empty for\n * a data-only blueprint: it declares no app, builds nothing, and still ships a crew (ADR-0900).\n */\n trees: z.array(BlueprintTreeSchema),\n /**\n * The setup questions, asked by the studio **before** provisioning. `QuestionField` (§7.1) is\n * reused rather than restated: a setup question and a question a parked agent asks are the same\n * object at different times, so one component renders both.\n */\n questions: z.array(QuestionFieldSchema),\n schedules: z.array(BlueprintScheduleSchema),\n /** Who the crew is, and what it deploys — §31.5. Derived from `declaration`, never stored twice. */\n agents: z.array(BlueprintCrewSchema),\n apps: z.array(BlueprintAppSchema),\n /**\n * The agents a template creates per client the operator signs — printed, never provisioned by an\n * apply (§31.1). Absent on rows published before WS12 v2, hence optional.\n */\n crew_per_client: z.array(BlueprintCrewSchema).optional(),\n /**\n * The personas the crew posts from, and which accounts to connect to each before the crew\n * exists (§31.10). Derived from `declaration` like `agents`; optional for the §31.5 rollout reason.\n */\n identities: z.array(BlueprintIdentitySchema).optional(),\n /**\n * The crew's first work: the cards an apply seeds on the board (§31.11), as a title and who has\n * it, in the declared order. Derived from `declaration` like `agents`, so a person reads day one\n * before paying for it (the launch roadmap, ADR-1170); optional for the §31.5 rollout reason.\n */\n tasks: z.array(BlueprintTaskSchema).optional(),\n /**\n * The mini apps the template brings (§50.1): no tree, no deploy, so they are not in `apps`, and a\n * person is shown them beside the hosted ones before paying (ADR-1171). Derived from\n * `declaration.mini_apps` like `tasks`; optional for the §31.5 rollout reason.\n */\n mini_apps: z.array(BlueprintMiniAppSchema).optional(),\n /** The first week in the template's own words (ADR-1172): Day 1, what each day after it carries, and what follows the week. */\n roadmap: z.object({ day_one: z.string().min(1).optional(), every_day: z.string().min(1).optional(), after: z.string().min(1).optional() }).optional(),\n /**\n * The creator template a row was published from (§42.8), `null` on every first-party row.\n * `creator_name` is the public display name the landing page credits. The API sends all three\n * on every row; they are optional here only so an artifact typed before §42 still reads.\n */\n creator_template_id: idOf(\"ctp\").nullish(),\n creator_template_version: z.number().int().positive().nullish(),\n creator_name: z.string().min(1).nullish(),\n /**\n * The listing a reviewer curated for a creator row (§42.8): its one-line pitch, and a public\n * sample video with its poster frame. Optional and nullish — a first-party row and a row whose\n * listing names no hero carry none, and the landing page prints only what is present.\n */\n creator_tagline: z.string().min(1).nullish(),\n creator_hero_url: z.string().url().nullish(),\n creator_hero_poster_url: z.string().url().nullish(),\n published_at: Timestamp,\n});\nexport type BlueprintArtifact = z.infer<typeof BlueprintArtifactSchema>;\n","/**\n * MINI APPS — a template's pages of the platform's data-bound blocks (canonical-spec §50, ADR-0982).\n * A template declares its mini apps as data; the platform resolves every binding and the studio\n * draws every mini app with one general UI. A page's spec is `compose`'s (§49): a flat element map\n * under one root, words written by the author, every number a `$source` binding code resolves. The\n * catalog is the same one, plus the blocks a page needs: sections, what waits on a person, what the\n * agents are doing, the accounts, the posts, the setup's answers and the company's media library.\n */\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { PendingActionSchema, TEMPLATE_QUESTIONS_MAX } from \"./session\";\nimport { PostSchema, SocialPlatformSchema } from \"./social\";\nimport { RoadmapViewSchema } from \"./show\";\nimport { Bound, bound, box, catalog, element, Key, label, leaf, Resolved, spec, unknownComponent, words } from \"./catalog\";\n\nexport const PAGE_BLOCKS = [\n \"Page\", \"Section\", \"Stack\", \"Grid\", \"Metric\", \"LineChart\", \"BarList\", \"Progress\", \"Roadmap\", \"Schedule\", \"Media\", \"Text\",\n \"Needs\", \"Activity\", \"Accounts\", \"Posts\", \"Answers\", \"MediaLibrary\",\n] as const;\nexport const MAX_PAGE_ELEMENTS = 48;\n/** The icons a mini app may wear on its tile: a small fixed set, drawn by the studio. Never an agent's face. */\nexport const MINI_APP_ICONS = [\"grid\", \"list\", \"chart\", \"calendar\", \"play\"] as const;\nexport const MiniAppIconSchema = z.enum(MINI_APP_ICONS);\nexport type MiniAppIcon = z.infer<typeof MiniAppIconSchema>;\nconst SLUG = \"[a-z][a-z0-9-]{0,39}\";\nexport const MiniAppSlugSchema = z.string().regex(new RegExp(`^${SLUG}$`), \"a slug is lowercase letters, digits and -\");\n\n/** Where a section's head may lead: a platform place, or a mini app (one of its pages, if named). */\nconst Place = z\n .string()\n .regex(new RegExp(`^/(board|connections|apps/${SLUG}(\\\\?page=${SLUG})?)$`), \"a section links to /board, /connections or /apps/<slug>[?page=<slug>]\");\nconst POSTS = [\"waiting\", \"scheduled\", \"posted\"] as const;\nconst PostStatus = z.enum(POSTS);\n/** How a list of posts is drawn (ADR-1020): rows, one sideways row of cards, or a picture grid. */\nconst PostLayout = z.enum([\"list\", \"row\", \"grid\"]);\n/** One status, or several read into one list in the order given (ADR-1010). */\nconst PostStatuses = z.union([PostStatus, z.array(PostStatus).min(1).max(3).refine((all) => new Set(all).size === all.length, \"each status once\")]);\n\n/** A page's side of the shared slots: a roadmap may be shorter per group, media is up to six tiles. */\nconst PageBound = {\n ...Bound,\n board: bound([\"roadmap\"], { per_group: z.number().int().min(1).max(5).default(5) }),\n media: bound([\"latest_media\", \"newest_media\"], { count: z.number().int().min(1).max(6).default(4) }),\n};\nconst PageResolved = {\n ...Resolved,\n board: z.strictObject({ $source: z.literal(\"roadmap\"), per_group: z.number().int(), groups: RoadmapViewSchema.shape.groups }),\n media: z.array(z.strictObject({ id: z.string(), kind: z.enum([\"image\", \"video\"]) })).max(6),\n};\n\n/** The page's own blocks, bound or resolved. */\nfunction pageBlocks<Needs extends z.ZodType, Agents extends z.ZodType, Accounts extends z.ZodType, Posts extends z.ZodType, Answers extends z.ZodType>(slot: {\n needs: Needs;\n agents: Agents;\n accounts: Accounts;\n posts: Posts;\n answers: Answers;\n}) {\n return {\n Page: element(\"Page\", {}, box, \"The page itself, the root and only the root.\"),\n Section: element(\"Section\", { title: words(40), to: Place.optional(), hide_empty: z.boolean().optional() }, box, \"A titled part of the page; hidden when every block in it is empty, if asked.\"),\n Needs: element(\"Needs\", { label, needs: slot.needs }, leaf, \"What waits on a person: approvals, questions, spent caps.\"),\n Activity: element(\"Activity\", { label, agents: slot.agents }, leaf, \"The agents working or waiting, and on what.\"),\n Accounts: element(\"Accounts\", { accounts: slot.accounts }, leaf, \"The template's networks: connected with a handle, or not.\"),\n Posts: element(\n \"Posts\",\n { label, layout: PostLayout.optional(), posts: slot.posts },\n leaf,\n \"Posts waiting on a person, scheduled, or posted; several statuses make one list. Drawn as rows (list, the default), one sideways row of cards (row), or a picture grid (grid).\",\n ),\n Answers: element(\"Answers\", { answers: slot.answers }, leaf, \"The setup's answers in one line, linking to the setup.\"),\n // No binding: the studio's gallery reads and pages the company's files itself (ADR-0987).\n MediaLibrary: element(\"MediaLibrary\", {}, leaf, \"Every picture and clip the company's agents made, with filters, sort and a viewer.\"),\n };\n}\n\nconst OwnBound = pageBlocks({\n needs: bound([\"needs\"], {}),\n agents: bound([\"agents_activity\"], {}),\n accounts: bound([\"accounts\"], {}),\n posts: bound([\"posts\"], { status: PostStatuses, limit: z.number().int().min(1).max(50).default(10) }),\n answers: bound([\"answers\"], { keys: z.array(Key).min(1).max(TEMPLATE_QUESTIONS_MAX) }),\n});\n\nconst Need = z.object({\n session_id: z.string(),\n agent_id: z.string(),\n agent: z.string(),\n since: Timestamp,\n /** The chat's stored title, or `null`: the studio names it by when it began. */\n title: z.string().nullable(),\n kind: z.enum([\"tool\", \"question\", \"budget\"]),\n /** The call or question it is held on; `null` for a spent cap. */\n action: PendingActionSchema.nullable(),\n});\nconst Working = z.object({\n agent_id: z.string(),\n agent: z.string(),\n state: z.enum([\"working\", \"waiting\"]),\n session_id: z.string().nullable(),\n title: z.string().nullable(),\n at: Timestamp,\n});\n\nconst OwnResolved = pageBlocks({\n needs: z.strictObject({ $source: z.literal(\"needs\"), items: z.array(Need) }),\n agents: z.strictObject({ $source: z.literal(\"agents_activity\"), agents: z.array(Working) }),\n accounts: z.strictObject({\n $source: z.literal(\"accounts\"),\n accounts: z.array(z.object({ platform: SocialPlatformSchema, connected: z.boolean(), handle: z.string().nullable() })),\n }),\n posts: z.strictObject({ $source: z.literal(\"posts\"), status: z.union([PostStatus, z.array(PostStatus)]), limit: z.number().int(), posts: z.array(PostSchema), more: z.boolean() }),\n answers: z.strictObject({\n $source: z.literal(\"answers\"),\n keys: z.array(z.string()),\n values: z.array(z.string()),\n template: z.object({ blueprint: z.string(), template: z.string() }).nullable(),\n }),\n});\n\nconst BoundBlocks = { ...catalog(PageBound), ...OwnBound };\nconst ResolvedBlocks = { ...catalog(PageResolved), ...OwnResolved };\n\n/** A block whose source could not be read: one quiet line in its place, never the page down. */\nconst Unread = element(\"Unread\", { of: z.string(), label: z.string().nullable(), reason: z.string() }, leaf, \"A block that could not be read.\");\n\n/* Spelled out for each side, as `compose.ts` does: a helper generic over the blocks loses their types. */\nconst B = BoundBlocks;\nexport const PageSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [B.Page, B.Section, B.Stack, B.Grid, B.Metric, B.LineChart, B.BarList, B.Progress, B.Roadmap, B.Schedule, B.Media, B.Text, B.Needs, B.Activity, B.Accounts, B.Posts, B.Answers, B.MediaLibrary],\n unknownComponent(PAGE_BLOCKS),\n ),\n \"Page\",\n MAX_PAGE_ELEMENTS,\n);\nexport type PageSpec = z.infer<typeof PageSpecSchema>;\nexport type PageElement = PageSpec[\"elements\"][string];\n\nconst R = ResolvedBlocks;\n/** One resolved block: checked as it is read, so a bad one is one `Unread` line, not the page down. */\nexport const ResolvedPageElementSchema = z.discriminatedUnion(\n \"type\",\n [R.Page, R.Section, R.Stack, R.Grid, R.Metric, R.LineChart, R.BarList, R.Progress, R.Roadmap, R.Schedule, R.Media, R.Text, R.Needs, R.Activity, R.Accounts, R.Posts, R.Answers, R.MediaLibrary, Unread],\n unknownComponent(PAGE_BLOCKS),\n);\nexport const ResolvedPageSpecSchema = spec(ResolvedPageElementSchema, \"Page\", MAX_PAGE_ELEMENTS);\nexport type ResolvedPageSpec = z.infer<typeof ResolvedPageSpecSchema>;\nexport type ResolvedPageElement = ResolvedPageSpec[\"elements\"][string];\n/** One block's resolved props: what the studio's renderer draws. */\nexport type BlockProps<T extends ResolvedPageElement[\"type\"]> = Extract<ResolvedPageElement, { type: T }>[\"props\"];\n\nconst unique = (items: { slug: string }[]) => new Set(items.map((item) => item.slug)).size === items.length;\n\n/** One page of a mini app: a tab of its own, under its own title. */\nexport const MiniAppPageSchema = z.strictObject({ slug: MiniAppSlugSchema, title: words(24), spec: PageSpecSchema });\n\n/** One mini app as a template declares it: data only, checked with the catalog when it is read (§50.2). */\nexport const MiniAppDeclSchema = z.strictObject({\n slug: MiniAppSlugSchema,\n name: words(40),\n icon: MiniAppIconSchema,\n pages: z.array(MiniAppPageSchema).min(1).max(6).refine(unique, \"each page's slug is its own\"),\n});\nexport type MiniAppDecl = z.infer<typeof MiniAppDeclSchema>;\nexport const MiniAppDeclsSchema = z.array(MiniAppDeclSchema).max(8).refine(unique, \"each mini app's slug is its own\");\n\n/**\n * WHAT A MINI APP READS (§50.3, ADR-1048), derived by code from its declaration, never written by\n * its author: every `$source` bound on any of its pages, `media_library` for the library block, and\n * `posts_waiting` where a posts list shows posts waiting on a person — which that person can allow\n * or refuse from it. Sorted, each once.\n */\nexport function miniAppReads(app: MiniAppDecl): string[] {\n const reads = new Set<string>();\n for (const page of app.pages) {\n for (const element of Object.values(page.spec.elements)) {\n if (element.type === \"MediaLibrary\") reads.add(\"media_library\");\n for (const value of Object.values(element.props as Record<string, unknown>)) {\n const source = typeof value === \"object\" && value !== null && \"$source\" in value ? (value as { $source: unknown; status?: unknown }) : null;\n if (typeof source?.$source !== \"string\") continue;\n reads.add(source.$source);\n if (source.$source === \"posts\" && [source.status].flat().includes(\"waiting\")) reads.add(\"posts_waiting\");\n }\n }\n }\n return [...reads].sort();\n}\n\n/** `GET /v1/mini-apps` — the mini apps a company has, in its template's order (§50.3). */\nexport const MiniAppSummarySchema = z.object({\n object: z.literal(\"mini_app\"),\n slug: MiniAppSlugSchema,\n name: z.string(),\n icon: MiniAppIconSchema,\n pages: z.array(z.object({ slug: MiniAppSlugSchema, title: z.string() })).min(1),\n /** What it reads (`miniAppReads`). Absent from an older API: the Studio then claims nothing it cannot see. */\n reads: z.array(z.string()).optional(),\n});\nexport type MiniAppSummary = z.infer<typeof MiniAppSummarySchema>;\n\n/**\n * `GET /v1/mini-apps/{slug}` — one mini app with one page read, every binding at `as_of` on the\n * company's clock. `networks` is the applied template's networks for the header's marks, each with\n * whether a persona is connected to it (`null`: that could not be read; ADR-0992).\n */\nexport const MiniAppSchema = MiniAppSummarySchema.extend({\n networks: z.array(z.object({ platform: SocialPlatformSchema, connected: z.boolean().nullable() })),\n page: MiniAppSlugSchema,\n as_of: Timestamp,\n timezone: z.string().min(1),\n spec: ResolvedPageSpecSchema,\n});\nexport type MiniApp = z.infer<typeof MiniAppSchema>;\n","/**\n * `show` — a view of the company the chat draws (canonical-spec §48). The model names a source;\n * code reads the data and writes the view, title included, so no number on the figure was typed\n * by the model. The same schema is the tool's argument parser, its result, and the web's reader.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { BoardStatusSchema } from \"./board\";\n\nexport const SHOW_SOURCES = [\"spend_by_day\", \"post_views\", \"roadmap\", \"schedule\"] as const;\nexport const ShowSourceSchema = z.enum(SHOW_SOURCES);\n\n/**\n * FLAT, ON PURPOSE. A discriminated union of per-source arguments becomes a root `oneOf`, which\n * providers refuse and which `defineTool`'s key repair cannot read (it only knows an object's\n * keys). `days` is read by `spend_by_day` alone.\n */\nexport const ShowArgsSchema = z.object({\n source: ShowSourceSchema.describe(\n \"What to show: spend_by_day (company spend per day, a line), post_views (views per recent post, bars), \" +\n \"roadmap (the board's work by status), schedule (routines and scheduled posts over the next 7 days).\",\n ),\n days: z.number().int().min(2).max(30).optional().describe(\"spend_by_day only: days back, today included. Default 14.\"),\n});\nexport type ShowArgs = z.infer<typeof ShowArgsSchema>;\n\n/** A calendar day on the company's clock (§20.6). */\nconst Day = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\nconst Count = z.number().int().nonnegative();\n\n/** What every view carries: its title (written by code), when it was read, and the company's clock. */\nconst head = { title: z.string().min(1), as_of: Timestamp, timezone: z.string().min(1) };\n\nexport const SpendByDayViewSchema = z.object({\n source: z.literal(\"spend_by_day\"),\n ...head,\n days: z.array(z.object({ day: Day, micro_usd: Count })).min(2).max(30),\n});\n\nexport const PostViewsViewSchema = z.object({\n source: z.literal(\"post_views\"),\n ...head,\n posts: z\n .array(z.object({ post_id: z.string().min(1), label: z.string(), networks: z.array(z.string()), posted_at: Timestamp, views: Count }))\n .max(12),\n});\n\nexport const RoadmapViewSchema = z.object({\n source: z.literal(\"roadmap\"),\n ...head,\n groups: z.array(\n z.object({\n status: BoardStatusSchema,\n count: Count,\n cards: z.array(z.object({ title: z.string(), assignee: z.string().nullable(), waits_on: z.array(z.string()) })).max(5),\n }),\n ),\n});\n\nexport const ScheduleViewSchema = z.object({\n source: z.literal(\"schedule\"),\n ...head,\n days: z\n .array(\n z.object({\n day: Day,\n count: Count,\n items: z\n .array(\n z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"routine\"), at: Timestamp, agent: z.string(), text: z.string(), runs: z.number().int().min(1).max(100) }),\n z.object({ kind: z.literal(\"post\"), at: Timestamp, networks: z.array(z.string()), text: z.string() }),\n ]),\n )\n .max(8),\n }),\n )\n .max(7),\n});\n\nexport const ShowViewSchema = z.discriminatedUnion(\"source\", [\n SpendByDayViewSchema,\n PostViewsViewSchema,\n RoadmapViewSchema,\n ScheduleViewSchema,\n]);\nexport type ShowView = z.infer<typeof ShowViewSchema>;\nexport type ScheduleItem = z.infer<typeof ScheduleViewSchema>[\"days\"][number][\"items\"][number];\n","/**\n * The block catalog shared by `compose` (§49) and mini apps (§50): the components, the rule that a\n * number is a binding code resolves, and the tree check. One catalog, built with different slots:\n * with bindings for what an author writes, with resolved values for what a renderer draws.\n * Internal to `schema/`: `compose.ts` and `mini-app.ts` export what the wire needs.\n */\n\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\nimport { PostViewsViewSchema, RoadmapViewSchema, ScheduleViewSchema } from \"./show\";\n\nexport const Key = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,39}$/, \"an element key is a short name: a letter, then letters, digits, - or _\");\nexport const Count = z.number().int().nonnegative();\n\n/**\n * WORDS ARE THE MODEL'S; DIGITS ARE NOT. A title or a note that says \"up 18%\" would put a number on\n * the card that no code read. The window a value covers is written by the chat from its binding\n * (\"Last 7 days\"), so the model never needs a digit. The ASCII regex is what the JSON Schema the\n * model is shown carries (a `\\p{…}` pattern is one some providers' validators cannot compile); the\n * refine closes every other script's digits, fractions and numeral signs (`١٢`, `18`, `½`, `Ⅻ`).\n * Number WORDS (\"twelve thousand\") no pattern can close: that is the model's words, unchecked for\n * meaning like any label (ADR-0955).\n */\nconst DIGIT = \"words only: a digit is refused, because every number on the card is read by code from a $source binding\";\nexport const words = (max: number) =>\n z\n .string()\n .trim()\n .min(1)\n .max(max)\n .regex(/^[^0-9]*$/, DIGIT)\n .refine((text) => !/\\p{N}/u.test(text), DIGIT);\n\nexport const Days = z.number().int().min(1).max(30).default(7).describe(\"The window: today and the days before it, on the company's clock. Default 7.\");\n\n/** A binding to one of `sources`. A literal where one belongs is refused with the fix. */\nexport function bound<const S extends readonly [string, ...string[]], T extends z.ZodRawShape>(sources: S, shape: T) {\n const example = JSON.stringify({ $source: sources[0] });\n return z.strictObject(\n { $source: z.enum(sources), ...shape },\n { error: (issue) => (issue.code === \"invalid_type\" ? `must be a binding such as ${example}: a literal value is refused, code reads every number` : undefined) },\n );\n}\n\n/** The model's side: every data slot is a binding (or, for media, the ids of the company's files). */\nexport const Bound = {\n value: bound([\"views_total\", \"spend_total\"], { days: Days }).describe(\n \"views_total: the latest views of the posts published in the window. spend_total: the company's spend in the window (the CEO only).\",\n ),\n delta: bound([\"views_change\"], {}).describe(\n \"views_change: the value's views_total against the same number of days before it, as a percentage. Its window is the value's.\",\n ),\n series: bound([\"spend_by_day\"], { days: z.number().int().min(2).max(30).default(14) }).describe(\"spend_by_day: the company's spend per day (the CEO only).\"),\n bars: bound([\"post_views\"], { limit: z.number().int().min(1).max(12).default(5).describe(\"How many posts, newest first. Default 5.\") }).describe(\n \"post_views: each recent post's latest views, newest first.\",\n ),\n progress: bound([\"posts_this_week\"], {}).describe(\"posts_this_week: posts published since Monday against the weekly cadence from the company's setup or its channel plan, else 3× a week.\"),\n board: bound([\"roadmap\"], {}).describe(\"roadmap: the board's work by status.\"),\n week: bound([\"schedule\"], {}).describe(\"schedule: routines and scheduled posts over the next 7 days.\"),\n media: z\n .union([bound([\"latest_media\"], { count: z.number().int().min(1).max(4).default(1) }), z.array(idOf(\"fil\")).min(1).max(4)])\n .describe('{\"$source\":\"latest_media\",\"count\":1} for the newest posted pictures or clips, or up to 4 fil_ ids.'),\n};\n\nexport const SpendDay = z.strictObject({ day: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/), micro_usd: Count });\n\n/** The result's side: each binding as it was asked, with what code read for it. */\nexport const Resolved = {\n value: z.discriminatedUnion(\"$source\", [\n z.strictObject({ $source: z.literal(\"views_total\"), days: z.number().int(), value: Count, posts: Count }),\n z.strictObject({ $source: z.literal(\"spend_total\"), days: z.number().int(), value: Count }),\n ]),\n delta: z.strictObject({ $source: z.literal(\"views_change\"), days: z.number().int(), current: Count, previous: Count }),\n series: z.strictObject({ $source: z.literal(\"spend_by_day\"), days: z.number().int(), points: z.array(SpendDay).min(2).max(30) }),\n bars: z.strictObject({ $source: z.literal(\"post_views\"), limit: z.number().int(), posts: PostViewsViewSchema.shape.posts }),\n progress: z.strictObject({ $source: z.literal(\"posts_this_week\"), value: Count, max: z.number().int().positive(), cadence: z.string() }),\n board: z.strictObject({ $source: z.literal(\"roadmap\"), groups: RoadmapViewSchema.shape.groups }),\n week: z.strictObject({ $source: z.literal(\"schedule\"), days: ScheduleViewSchema.shape.days }),\n media: z.array(z.strictObject({ id: idOf(\"fil\"), kind: z.enum([\"image\", \"video\"]) })).min(1).max(4),\n};\n\n/** An element that holds children, and one that holds none. */\nexport const box = { children: z.array(Key).min(1).max(12) };\nexport const leaf = { children: z.array(Key).max(0).optional() };\nexport const label = words(40).optional();\nexport const element = <T extends string, P extends z.ZodRawShape, C extends z.ZodRawShape>(type: T, props: P, children: C, about: string) =>\n z.strictObject({ type: z.literal(type), props: z.strictObject(props), ...children }).describe(about);\n\n/**\n * The components, once. `box` elements hold children; every other element is a leaf. One type\n * parameter per slot: a single `S extends Record<…, ZodType>` loses each slot's type to `unknown`.\n */\nexport function catalog<\n Value extends z.ZodType,\n Delta extends z.ZodType,\n Series extends z.ZodType,\n Bars extends z.ZodType,\n Goal extends z.ZodType,\n Board extends z.ZodType,\n Week extends z.ZodType,\n Files extends z.ZodType,\n>(slot: { value: Value; delta: Delta; series: Series; bars: Bars; progress: Goal; board: Board; week: Week; media: Files }) {\n return {\n Card: element(\"Card\", { title: words(60) }, box, \"The card, with a short title. It is the root, and only the root.\"),\n Stack: element(\"Stack\", {}, box, \"Children one under another.\"),\n Grid: element(\"Grid\", { columns: z.literal([1, 2, 3]) }, box, \"Children side by side, 1 to 3 columns.\"),\n Metric: element(\"Metric\", { label: words(40), value: slot.value, delta: slot.delta.optional() }, leaf, \"One big number with a label, and optionally its change.\"),\n LineChart: element(\"LineChart\", { label, series: slot.series }, leaf, \"A line over days.\"),\n BarList: element(\"BarList\", { label, bars: slot.bars }, leaf, \"One bar per post.\"),\n Progress: element(\"Progress\", { label: words(40), progress: slot.progress }, leaf, \"A value against its goal, as a bar.\"),\n Roadmap: element(\"Roadmap\", { label, board: slot.board }, leaf, \"The board grouped by status.\"),\n Schedule: element(\"Schedule\", { label, week: slot.week }, leaf, \"The week ahead, day by day.\"),\n Media: element(\"Media\", { label, files: slot.media }, leaf, \"Pictures or clips the company holds.\"),\n Text: element(\"Text\", { text: words(240) }, leaf, \"A short note in words.\"),\n };\n}\n\n/** An element outside the catalog is refused with the list. */\nexport const unknownComponent = (names: readonly string[]) => ({\n error: (issue: { code?: string }) => (issue.code === \"invalid_union\" ? `unknown component: use one of ${names.join(\", \")}` : undefined),\n});\n\n/**\n * THE TREE, CHECKED IN CODE. json-render draws whatever the map names and silently skips a child it\n * cannot find; here a missing child, a second parent, an orphan, a nested root or a root of the wrong\n * type is refused, so what the chat draws is exactly what the model sent.\n */\nfunction tree(rootType: string, max: number, spec: { root: string; elements: Record<string, { type: string; children?: string[] | undefined }> }, ctx: z.RefinementCtx): void {\n const refuse = (message: string, path: (string | number)[] = []) => ctx.addIssue({ code: \"custom\", message, path });\n const keys = Object.keys(spec.elements);\n // Own keys only: `toString` and `constructor` answer on every object, and are not elements.\n const has = (key: string): boolean => Object.hasOwn(spec.elements, key);\n if (keys.length > max) return refuse(`at most ${max} elements`, [\"elements\"]);\n const root = has(spec.root) ? spec.elements[spec.root] : undefined;\n if (!root) return refuse(`root names \"${spec.root}\", which is not in elements`, [\"root\"]);\n if (root.type !== rootType) return refuse(`the root must be a ${rootType}`, [\"root\"]);\n const parent = new Map<string, string>();\n for (const key of keys) {\n for (const child of spec.elements[key]!.children ?? []) {\n if (!has(child)) return refuse(`\"${child}\" is not in elements`, [\"elements\", key, \"children\"]);\n if (child === spec.root || parent.has(child)) return refuse(`\"${child}\" has more than one parent`, [\"elements\", key, \"children\"]);\n if (spec.elements[child]!.type === rootType) return refuse(`a ${rootType} is the root only; group with Stack or Grid`, [\"elements\", child, \"type\"]);\n parent.set(child, key);\n }\n }\n // One parent each and none for the root, so a walk down from the root ends; what it misses is\n // an orphan or a loop of its own.\n const reached = new Set([spec.root]);\n for (const key of reached) for (const child of spec.elements[key]!.children ?? []) reached.add(child);\n const lost = keys.find((key) => !reached.has(key));\n if (lost) refuse(`\"${lost}\" is not under the root`, [\"elements\", lost]);\n}\n\n/** A flat element map under one `root` of `rootType`, at most `max` elements, checked as a tree. */\nexport const spec = <E extends z.ZodType<{ type: string; children?: string[] | undefined }>>(element: E, rootType: string, max: number) =>\n z.strictObject({ root: Key, elements: z.record(Key, element) }).superRefine((value, ctx) => tree(rootType, max, value, ctx));\n","/**\n * The credential vault (`canonical-spec.md §23`, `docs/identity/vault.mdx`, `docs/api/vaults.mdx`).\n *\n * One property defines this object and every field below serves it: **the value is write-only.**\n * It is accepted on create, sealed, and never returned by any endpoint — there is no reveal route,\n * no `value` on any read schema, and no update route (rotation is create-new + delete-old, so\n * `last_injected_at` stays attributable to exactly one secret).\n *\n * Note what is *absent* on purpose: `VaultCredentialSchema` has no `value`, so a handler that\n * parsed a row through it could not emit one even by accident. That is the guarantee expressed as\n * a type rather than as a convention.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\n/**\n * The three kinds `docs/identity/vault.mdx` publishes.\n *\n * · `static_bearer` / `mcp_oauth` are injected **server-side, in our own isolate**, when the MCP\n * client connects to `mcp_server_url`. The token never enters the sandbox, so the guarantee holds\n * with no vendor capability we do not have.\n * · `env_var` promises substitution at an egress proxy on the sandbox's network path. No such\n * boundary exists (`memory/vendor-tenki.md §5`: no egress allowlist, no per-domain policy, no\n * proxy hook), so the route refuses it with `feature_not_configured` rather than storing a secret\n * whose central safety property we cannot deliver (ADR-0117).\n */\nexport const VaultCredentialKindSchema = z.enum([\"env_var\", \"static_bearer\", \"mcp_oauth\"]);\nexport type VaultCredentialKind = z.infer<typeof VaultCredentialKindSchema>;\n\n/** A vault belongs to exactly one identity; `null` until the identity stream lands the object. */\nexport const VaultSchema = z.object({\n id: idOf(\"vlt\"),\n object: z.literal(\"vault\"),\n identity_id: idOf(\"idn\").nullable(),\n display_name: z.string().min(1).max(128),\n credential_count: z.number().int().nonnegative(),\n created_at: Timestamp,\n});\nexport type Vault = z.infer<typeof VaultSchema>;\n\n/**\n * Credential **metadata**. Every read surface returns this and only this.\n *\n * `placeholder_ref` is not a secret and is returned deliberately: a caller needs it to write the\n * reference into a script. It names a credential; it authenticates nothing.\n */\nexport const VaultCredentialSchema = z.object({\n id: idOf(\"vcr\"),\n object: z.literal(\"vault_credential\"),\n vault_id: idOf(\"vlt\"),\n kind: VaultCredentialKindSchema,\n /** For `env_var`, the environment variable name. For the MCP kinds, a display label. */\n key: z.string().min(1).max(128),\n /** The exact destination host an `env_var` credential is bound to. Never a wildcard. */\n host: z.string().nullable(),\n /** The exact MCP server URL an `mcp_*` token is matched to. */\n mcp_server_url: z.url().nullable(),\n /**\n * The one agent this credential may be injected into (ADR-1097). `null` is any agent that\n * declares `mcp_server_url` — except the platform's own `/v1/mcp`, whose key is never injected\n * unbound. Set at create, by `admin`, and immutable like the rest. Defaults to `null` so a\n * client reading a control plane older than the field still parses the row.\n */\n agent_id: idOf(\"agt\").nullable().default(null),\n placeholder_ref: z.string(),\n expires_at: Timestamp.nullable(),\n last_injected_at: Timestamp.nullable(),\n created_at: Timestamp,\n});\nexport type VaultCredential = z.infer<typeof VaultCredentialSchema>;\n","/**\n * Handoffs — `send_to_agent` with `wait: false` (canonical-spec §28.12, §28.15): an agent starts a\n * top-level session on another agent of its organization and carries on. Who it may reach is the\n * agent's `handoffs` field (`schema/agent.ts`), the same field that governs a `wait: true` thread.\n *\n * The body the door takes, the answer it returns and the mark the receiver's row carries are one\n * shape each, here, so the runtime, the API and a blueprint cannot drift apart on any of them.\n */\n\nimport { z } from \"zod\";\nimport { isId } from \"../id\";\nimport { idOf, type Metadata } from \"./common\";\n\n/** The most targets one human send may fan out to (§28.16): a room seats a coordinator and up to six. */\nexport const MAX_HANDOFF_TARGETS = 6;\n\n/** A sender at this depth is refused: a chain — or a cycle — ends in five sessions at most (§28.15). */\nexport const MAX_HANDOFF_DEPTH = 4;\nexport const MAX_HANDOFFS_PER_SESSION = 8;\n\nexport const HandoffRequestSchema = z.object({\n agent: z.string().min(1),\n message: z.string().min(1),\n handoff_key: z.string().min(1).max(128).optional(),\n budget_micro_usd: z.number().int().positive().optional(),\n});\nexport type HandoffRequest = z.infer<typeof HandoffRequestSchema>;\n\nexport const HandoffSchema = z.object({\n object: z.literal(\"handoff\"),\n session_id: idOf(\"ses\"),\n status: z.enum([\"queued\", \"already_running\"]),\n handoff_key: z.string().nullable(),\n});\nexport type Handoff = z.infer<typeof HandoffSchema>;\n\n/**\n * `POST /v1/sessions/{id}/handoffs` (§28.16): a person hands `{id}`'s work to several agents in one\n * call. Each target is an `agt_` id or a name; the sender is the session in the path.\n */\nexport const SessionHandoffRequestSchema = z.object({\n agents: z.array(z.string().min(1)).min(1).max(MAX_HANDOFF_TARGETS),\n message: z.string().min(1),\n handoff_key: z.string().min(1).max(128).optional(),\n budget_micro_usd: z.number().int().positive().optional(),\n});\nexport type SessionHandoffRequest = z.infer<typeof SessionHandoffRequestSchema>;\n\n/** One target the door would not start: a row of the batch, never the whole answer (§28.16). */\nexport const HandoffRefusalSchema = z.object({\n object: z.literal(\"handoff_refusal\"),\n agent: z.string(),\n code: z.string(),\n message: z.string(),\n});\nexport type HandoffRefusal = z.infer<typeof HandoffRefusalSchema>;\n\n/** The human door's answer: §28.15's `Handoff` per admitted target, plus the seat it landed on. */\nexport const HandoffBatchSchema = z.object({\n object: z.literal(\"handoff_batch\"),\n handoffs: z.array(HandoffSchema.extend({ agent_id: idOf(\"agt\") })),\n refusals: z.array(HandoffRefusalSchema),\n});\nexport type HandoffBatch = z.infer<typeof HandoffBatchSchema>;\n\n/** `metadata.handoff` on the receiver's session row (§28.15). */\nexport const SessionHandoffSchema = z.object({\n from_session: idOf(\"ses\"),\n from_agent: idOf(\"agt\"),\n key: z.string().nullable(),\n depth: z.number().int().positive(),\n});\nexport type SessionHandoff = z.infer<typeof SessionHandoffSchema>;\n\n/** The mark a row carries, or `null` for a session nobody handed off. Lenient: metadata is the customer's. */\nexport function handoffOf(metadata: z.infer<typeof Metadata>): SessionHandoff | null {\n const parsed = SessionHandoffSchema.safeParse(metadata[\"handoff\"]);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * `metadata.role` of the one standing agent the dashboard calls the CEO. It is also the mark the\n * **company board** is found by (§28.18): the CEO owns that board and every live agent sits on it,\n * which is a fact the database reads (`@vetta/db` `seatFor`) and the runtime reads, so the string\n * lives here rather than once per reader.\n */\nexport const ORCHESTRATOR_ROLE = \"orchestrator\" as const;\n\n/** A room (§28.16) is a coordinator whose `metadata.role` is `\"group\"` or `\"orchestrator\"`; read off a pinned version. */\nexport const isRoom = (version: { metadata: z.infer<typeof Metadata> }): boolean =>\n version.metadata[\"role\"] === \"group\" || version.metadata[\"role\"] === ORCHESTRATOR_ROLE;\n\n/**\n * WHEN THE CHANNEL MARK BEGAN — the boundary one-time adoption may reach back over, and no further.\n *\n * From this instant a channel's session is MARKED at creation (`metadata.room`), so nothing created\n * from here on ever needs adopting. Adoption exists only for the channels that predate the mark, and\n * bounding it here is what keeps it from being a live rule: without the bound it considers every\n * unmarked top-level session of the coordinator forever, which includes the private 1:1 chat a\n * person starts from the agent page tomorrow — one dashboard read and the channel owns that chat's\n * transcript, permanently, with nothing in the product to undo it.\n *\n * It is NOT the cutoff that was tried and rejected on this branch. That one adopted only sessions\n * created AFTER a date, which strands exactly the legacy channels adoption is for. This is the\n * opposite bound: legacy sessions are eligible, new ones never are. It needs no migration and no\n * backfill, and it stops mattering once every channel that predates it has been read once.\n */\nexport const ROOM_ADOPTION_BEFORE = \"2026-09-19T00:00:00.000Z\";\n\n/** A room's `handoff_key` (§28.16), minted from the root session it names; `roomOfKey` reads it back. */\nexport const roomKey = (rootId: string): string => `room:${rootId}`;\n\n/** A room's `handoff_key` is `room:<root session id>` (§28.16); this reads the root off one, or `null` for any other key. */\nexport function roomOfKey(key: string | null | undefined): string | null {\n const root = key?.startsWith(\"room:\") ? key.slice(\"room:\".length) : \"\";\n return isId(\"ses\", root) ? root : null;\n}\n\n/**\n * A SEAT is a member's session in a room (§28.16): top-level and handed off under `room:<root>`.\n * It answers into the room, so it is the room's plumbing, never one of its agent's own chats; a\n * person reads it from the room and does not type into it. This reads the root it sits in, or `null`.\n */\nexport const seatOf = (session: { parent_session_id: string | null; metadata: z.infer<typeof Metadata> }): string | null =>\n session.parent_session_id === null ? roomOfKey(handoffOf(session.metadata)?.key) : null;\n\n/**\n * What a receiver handed off under a room's key is told about the room (§28.15 `channel`): the\n * root it may post into, the room agent's name, and the roster less itself. `null` outside a room.\n */\nexport const ChannelBriefSchema = z.object({\n root_session_id: idOf(\"ses\"),\n name: z.string().min(1),\n members: z.array(z.string().min(1)),\n /**\n * The receiver's own name, so it can tell the part of a post addressed to it from a teammate's\n * (ADR-1099). Optional: a brief pinned before it existed still parses.\n */\n you: z.string().min(1).optional(),\n});\nexport type ChannelBrief = z.infer<typeof ChannelBriefSchema>;\n\n/** `POST /v1/sandbox/channel/messages` (§28.16): a member's words for its room, and the door's answer. */\nexport const ChannelPostRequestSchema = z.object({\n message: z.string().min(1).max(20_000),\n});\nexport type ChannelPostRequest = z.infer<typeof ChannelPostRequestSchema>;\n\nexport const ChannelPostSchema = z.object({\n object: z.literal(\"channel_post\"),\n root_session_id: idOf(\"ses\"),\n queued: z.boolean(),\n});\nexport type ChannelPost = z.infer<typeof ChannelPostSchema>;\n\n/** How many voices a live call can speak a channel in (`canonical-spec §35.5`, ADR-1166). */\nexport const VOICE_SLOTS = 9;\n\n/**\n * THE VOICE A CHANNEL MEMBER SPEAKS IN ON A CALL (`canonical-spec §35.5`, ADR-1166): a stable\n * FNV-1a hash of its agent id onto 1..`VOICE_SLOTS`, so the bridge that speaks and the dashboard\n * that captions agree with no shared state. Two members may share a slot; nine voices is the cap.\n */\nexport function voiceSlotFor(agentId: string): number {\n let hash = 0x811c9dc5;\n for (let i = 0; i < agentId.length; i++) hash = Math.imul(hash ^ agentId.charCodeAt(i), 0x01000193);\n return ((hash >>> 0) % VOICE_SLOTS) + 1;\n}\n","/**\n * `compose` — a card the model lays out and code fills (canonical-spec §49, ADR-0955–0957). The\n * model writes a json-render spec: a flat map of elements under one `root`. It chooses the\n * components, their order and their words. It never writes a number: every value, series or\n * percentage on the card is a BINDING, `{ \"$source\": \"views_total\", \"days\": 7 }`, that code resolves\n * from Postgres when the tool runs. The tool's result is the same spec with each binding filled in.\n *\n * One catalog, written once (`catalog`), is built twice: with bindings for the model's argument\n * (`ComposeSpecSchema`), and with resolved values for the frozen result the chat draws\n * (`ComposedSpecSchema`). The two cannot drift apart, because they are the same components.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp } from \"./common\";\nimport { Bound, catalog, Resolved, spec, unknownComponent } from \"./catalog\";\n\nexport const COMPOSE_COMPONENTS = [\"Card\", \"Stack\", \"Grid\", \"Metric\", \"LineChart\", \"BarList\", \"Progress\", \"Roadmap\", \"Schedule\", \"Media\", \"Text\"] as const;\nexport const MAX_COMPOSE_ELEMENTS = 24;\n\n/** The model's spec: bindings where the numbers go. */\nconst BoundComponents = catalog(Bound);\n/*\n * The union is spelled out for each side. A helper generic over the catalog loses every slot's type\n * to `unknown`, as `catalog`'s own parameters did before they were split.\n */\nexport const ComposeSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [\n BoundComponents.Card, BoundComponents.Stack, BoundComponents.Grid, BoundComponents.Metric, BoundComponents.LineChart, BoundComponents.BarList,\n BoundComponents.Progress, BoundComponents.Roadmap, BoundComponents.Schedule, BoundComponents.Media, BoundComponents.Text,\n ],\n unknownComponent(COMPOSE_COMPONENTS),\n ),\n \"Card\",\n MAX_COMPOSE_ELEMENTS,\n);\nexport type ComposeSpec = z.infer<typeof ComposeSpecSchema>;\nexport type ComposeElement = ComposeSpec[\"elements\"][string];\n\n/** FLAT, like `show`'s (ADR-0945): the spec sits inside one property of a plain object. */\nexport const ComposeArgsSchema = z.object({\n spec: ComposeSpecSchema.describe(\n 'A json-render spec: { \"root\": key, \"elements\": { key: { \"type\", \"props\", \"children\"? } } }. The root is one Card.',\n ),\n});\n\n/** Each component with its values resolved: the props the chat's renderer is typed by. */\nexport const ComposedComponents = catalog(Resolved);\n\n/** The frozen result: the spec with every binding resolved, as read at `as_of` on the company's clock. */\nexport const ComposedSpecSchema = spec(\n z.discriminatedUnion(\n \"type\",\n [\n ComposedComponents.Card, ComposedComponents.Stack, ComposedComponents.Grid, ComposedComponents.Metric, ComposedComponents.LineChart,\n ComposedComponents.BarList, ComposedComponents.Progress, ComposedComponents.Roadmap, ComposedComponents.Schedule, ComposedComponents.Media,\n ComposedComponents.Text,\n ],\n unknownComponent(COMPOSE_COMPONENTS),\n ),\n \"Card\",\n MAX_COMPOSE_ELEMENTS,\n);\nexport const ComposedSchema = z.object({ as_of: Timestamp, timezone: z.string().min(1), spec: ComposedSpecSchema });\nexport type Composed = z.infer<typeof ComposedSchema>;\nexport type ComposedElement = Composed[\"spec\"][\"elements\"][string];\n/** One component's resolved props: what a block in the studio is typed by. */\nexport type ComposedProps<T extends ComposedElement[\"type\"]> = Extract<ComposedElement, { type: T }>[\"props\"];\n","/**\n * core-gaps: contracts — media as REST (`canonical-spec §33–§35`): the `med_` job that every\n * async kind shares (D5), and the request/result shapes of images, videos, clips and audio.\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { FileSchema } from \"./resource\";\n\n/**\n * The catalogue's `kind` (`§33.3`, `§35.1`): what `GET /v1/media/models?kind=` and the CLI's\n * `--kind` select. Distinct from the job kinds below — a catalogue row is a capability, a job is\n * work in flight.\n */\nexport const MEDIA_MODEL_KINDS = [\"image\", \"video\", \"stt\", \"tts\", \"s2s\"] as const;\nexport type MediaModelKind = (typeof MEDIA_MODEL_KINDS)[number];\nexport const isMediaModelKind = (value: string): value is MediaModelKind =>\n MEDIA_MODEL_KINDS.some((kind) => kind === value);\n\n/** `image` is synchronous (a `fil_` straight back), so it is not a job kind. */\nexport const MEDIA_JOB_KINDS = [\"video\", \"clip\", \"transcription\"] as const;\nexport const MediaJobKindSchema = z.enum(MEDIA_JOB_KINDS);\nexport const MediaJobStatusSchema = z.enum([\"queued\", \"processing\", \"completed\", \"failed\"]);\n\nconst PublicUrl = z.string().url().startsWith(\"http\");\nconst Score = z.number().int().min(0).max(100);\nconst Seconds = z.number().nonnegative();\n\nexport const VideoResultSchema = z.object({\n files: z.array(\n z.object({\n file_id: idOf(\"fil\"),\n content_type: z.string(),\n width: z.number().int().positive().nullable(),\n height: z.number().int().positive().nullable(),\n duration_seconds: Seconds.nullable(),\n }),\n ),\n});\n\nexport const ViralityScoreSchema = z.object({\n total: Score,\n shareability: Score,\n hook_strength: Score,\n story_quality: Score,\n emotional_impact: Score,\n});\n\nexport const ClipResultSchema = z.object({\n clips: z.array(\n z.object({\n file_id: idOf(\"fil\"),\n title: z.string(),\n start_seconds: Seconds,\n end_seconds: Seconds,\n duration_seconds: Seconds,\n virality: ViralityScoreSchema,\n }),\n ),\n});\n\nexport const TranscriptSchema = z.object({\n text: z.string(),\n language: z.string().nullable(),\n duration_seconds: Seconds.nullable(),\n segments: z.array(z.object({ start_seconds: Seconds, end_seconds: Seconds, text: z.string() })),\n});\n\nexport const MediaJobResultSchema = z.union([VideoResultSchema, ClipResultSchema, TranscriptSchema]);\n\nexport const MediaJobSchema = z.object({\n id: idOf(\"med\"),\n object: z.literal(\"media_job\"),\n kind: MediaJobKindSchema,\n status: MediaJobStatusSchema,\n model: z.string().nullable(),\n input: z.record(z.string(), z.unknown()),\n result: MediaJobResultSchema.nullable(),\n error: z.object({ code: z.string(), message: z.string() }).nullable(),\n cost_micro_usd: MicroUsdField.nullable(),\n session_id: idOf(\"ses\").nullable(),\n created_at: Timestamp,\n completed_at: Timestamp.nullable(),\n});\nexport type MediaJob = z.infer<typeof MediaJobSchema>;\n\nexport const ImageRequestSchema = z.object({\n model: z.string().min(1).optional(),\n prompt: z.string().min(1),\n image_urls: z.array(PublicUrl).max(4).optional(),\n aspect_ratio: z.string().optional(),\n seed: z.number().int().optional(),\n n: z.number().int().min(1).max(4).default(1),\n});\n\nexport const VideoRequestSchema = z.object({\n /** Omitted: the platform's video default while the catalogue publishes it (`resolveModel`, §33.2). */\n model: z.string().min(1).optional(),\n prompt: z.string().min(1),\n image_urls: z.array(PublicUrl).max(1).optional(),\n /** The source clip of a video-to-video edit (ADR-0814). */\n video_url: PublicUrl.optional(),\n aspect_ratio: z.string().optional(),\n seed: z.number().int().optional(),\n seconds: z.number().int().min(1).max(60).optional(),\n});\n\nexport const ImageGenerationSchema = z.object({\n object: z.literal(\"image_generation\"),\n model: z.string(),\n files: z.array(FileSchema),\n cost_micro_usd: MicroUsdField,\n});\n\nconst ClipLength = z.number().int().min(5).max(180);\nexport const ClipRequestSchema = z.object({\n video_url: PublicUrl,\n aspect_ratio: z.enum([\"9:16\", \"16:9\"]).default(\"9:16\"),\n remove_silence: z.boolean().default(false),\n caption_preset: z.enum([\"none\", \"clean\", \"bold\", \"karaoke\"]).default(\"none\"),\n language: z.string().min(2).optional(),\n min_seconds: ClipLength.default(15),\n max_seconds: ClipLength.default(60),\n title: z.string().min(1).optional(),\n});\nexport type ClipRequest = z.infer<typeof ClipRequestSchema>;\n\nexport const AudioFormatSchema = z.enum([\"mp3\", \"wav\", \"ogg\"]);\n\n/** Exactly one source — a library file or a public URL. */\nexport const TranscriptionRequestSchema = z\n .object({\n model: z.string().min(1).optional(),\n file_id: idOf(\"fil\").optional(),\n url: PublicUrl.optional(),\n language: z.string().min(2).optional(),\n timestamps: z.boolean().default(true),\n })\n .refine((request) => (request.file_id === undefined) !== (request.url === undefined), {\n error: \"exactly one of file_id or url\",\n path: [\"file_id\"],\n });\n\nexport const SpeechRequestSchema = z.object({\n model: z.string().min(1).optional(),\n text: z.string().min(1).max(4_096),\n voice: z.string().min(1).optional(),\n format: AudioFormatSchema.default(\"mp3\"),\n speed: z.number().min(0.5).max(2).optional(),\n});\n\nexport const SpeechToSpeechRequestSchema = z.object({\n model: z.string().min(1).optional(),\n file_id: idOf(\"fil\"),\n voice: z.string().min(1).optional(),\n format: AudioFormatSchema.default(\"mp3\"),\n});\n\nexport const SpeechGenerationSchema = z.object({\n object: z.literal(\"speech_generation\"),\n model: z.string(),\n file: FileSchema,\n duration_seconds: Seconds.nullable(),\n cost_micro_usd: MicroUsdField,\n});\n","/**\n * core-gaps: contracts — an app backend's database and object storage on the wire\n * (`canonical-spec §37`, §38). Buckets and objects are customer-named and carry no id prefix.\n */\n\nimport { z } from \"zod\";\nimport { Timestamp, idOf } from \"./common\";\n\nexport const DbTableSchema = z.object({\n object: z.literal(\"db_table\"),\n name: z.string(),\n schema: z.string().default(\"public\"),\n rows: z.number().int().nonnegative().nullable(),\n size_bytes: z.number().int().nonnegative().nullable(),\n});\nexport type DbTable = z.infer<typeof DbTableSchema>;\n\nexport const DbMigrationSchema = z.object({\n id: idOf(\"dbm\"),\n object: z.literal(\"db_migration\"),\n name: z.string(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n applied_at: Timestamp,\n statements: z.number().int().nonnegative(),\n});\nexport type DbMigration = z.infer<typeof DbMigrationSchema>;\n\nexport const ApplyDbMigrationSchema = z.object({\n name: z.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9_-]*$/),\n sql: z.string().min(1),\n});\n\nexport const DB_REST_METHODS = [\"GET\", \"POST\", \"PATCH\", \"PUT\", \"DELETE\", \"HEAD\"] as const;\nexport const DbRestMethodSchema = z.enum(DB_REST_METHODS);\n\nexport const BUCKET_NAME = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;\n\nexport const BucketSchema = z.object({\n object: z.literal(\"bucket\"),\n name: z.string().regex(BUCKET_NAME),\n public: z.boolean(),\n created_at: Timestamp,\n});\nexport type Bucket = z.infer<typeof BucketSchema>;\n\nexport const CreateBucketSchema = z.object({\n name: z.string().regex(BUCKET_NAME, { error: \"3–63 lowercase letters, digits and hyphens\" }),\n public: z.boolean().default(false),\n});\n\nexport const StorageObjectSchema = z.object({\n object: z.literal(\"storage_object\"),\n bucket: z.string(),\n key: z.string().min(1),\n size_bytes: z.number().int().nonnegative(),\n content_type: z.string(),\n etag: z.string().nullable(),\n updated_at: Timestamp,\n});\nexport type StorageObject = z.infer<typeof StorageObjectSchema>;\n\nexport const SignedUrlMethodSchema = z.enum([\"PUT\", \"GET\"]);\nexport const SignedUrlSchema = z.object({\n object: z.literal(\"signed_url\"),\n url: z.string().url(),\n method: SignedUrlMethodSchema,\n expires_at: Timestamp,\n});\nexport type SignedUrl = z.infer<typeof SignedUrlSchema>;\n\n/** `POST …/objects/{key}/upload-url` — a PUT the caller streams the bytes to. */\nexport const CreateUploadUrlSchema = z.object({\n content_type: z.string().min(1),\n expires_seconds: z.number().int().min(60).max(3_600).default(900),\n});\n","/**\n * core-gaps: contracts — stock photo search (`canonical-spec §39`, D6). The `id` is the\n * provider's, opaque and unprefixed; `attribution_url` is the one field allowed to point at the\n * provider's domain, because the licence requires it.\n */\n\nimport { z } from \"zod\";\n\nexport const STOCK_PHOTO_ORIENTATIONS = [\"landscape\", \"portrait\", \"square\"] as const;\nexport const STOCK_PHOTO_SIZES = [\"small\", \"medium\", \"large\"] as const;\n\nexport const StockPhotoQuerySchema = z.object({\n query: z.string().min(1).max(200),\n count: z.coerce.number().int().min(1).max(30).default(10),\n orientation: z.enum(STOCK_PHOTO_ORIENTATIONS).optional(),\n color: z.string().min(1).max(32).optional(),\n size: z.enum(STOCK_PHOTO_SIZES).optional(),\n});\nexport type StockPhotoQuery = z.infer<typeof StockPhotoQuerySchema>;\n\nexport const StockPhotoSchema = z.object({\n object: z.literal(\"stock_photo\"),\n id: z.string().min(1),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n url: z.string().url(),\n preview_url: z.string().url(),\n alt: z.string().nullable(),\n photographer: z.string().nullable(),\n attribution_url: z.string().url().nullable(),\n dominant_color: z.string().nullable(),\n});\nexport type StockPhoto = z.infer<typeof StockPhotoSchema>;\n","/**\n * The creator program (`canonical-spec §42`) — creators, their applications, referrals,\n * commissions, payouts and creator templates.\n *\n * None of these objects belongs to an organization (§42.12): a creator is a person keyed by email,\n * and a referral or a commission *points at* an organization's rows without living in the tenant.\n * Money is integer micro-USD, `floor`ed, USD only (§1).\n */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\n/** The referral code, and the namespace of every template the creator publishes: `c-<code>-<slug>`. */\nexport const CreatorCodeSchema = z\n .string()\n .regex(/^[a-z0-9]{3,24}$/, \"3 to 24 lowercase letters or digits\");\n\n/** `POST …/payouts` copies these onto the payout, so a later change never rewrites where money went. */\nexport const PayoutMethodSchema = z.enum([\"wise\", \"paypal\"]);\nexport type PayoutMethod = z.infer<typeof PayoutMethodSchema>;\n\nexport const PayoutDetailsSchema = z.object({\n method: PayoutMethodSchema,\n account: z.string().min(1).max(320),\n});\n\nexport const CreatorStatusSchema = z.enum([\"active\", \"suspended\"]);\nexport type CreatorStatus = z.infer<typeof CreatorStatusSchema>;\n\nexport const CreatorSchema = z.object({\n id: idOf(\"crt\"),\n object: z.literal(\"creator\"),\n email: z.email(),\n display_name: z.string().min(1).max(80),\n code: CreatorCodeSchema,\n status: CreatorStatusSchema,\n payout: PayoutDetailsSchema.nullable(),\n clicks: z.number().int().nonnegative(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Creator = z.infer<typeof CreatorSchema>;\n\n/** What `GET /v1/me` carries for a signed-in person (§20.1, §42.3). */\nexport const IdentityCreatorSchema = CreatorSchema.pick({\n id: true,\n status: true,\n});\nexport type IdentityCreator = z.infer<typeof IdentityCreatorSchema>;\n\nexport const CreatorApplicationStatusSchema = z.enum([\n \"pending\",\n \"approved\",\n \"rejected\",\n]);\nexport type CreatorApplicationStatus = z.infer<\n typeof CreatorApplicationStatusSchema\n>;\n\nexport const CreatorApplicationSchema = z.object({\n id: idOf(\"cra\"),\n object: z.literal(\"creator_application\"),\n email: z.email(),\n display_name: z.string().min(1).max(80),\n pitch: z.string().min(1).max(2000),\n links: z.array(z.url({ protocol: /^https$/ })).max(5),\n status: CreatorApplicationStatusSchema,\n note: z.string().nullable(),\n creator_id: idOf(\"crt\").nullable(),\n created_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type CreatorApplication = z.infer<typeof CreatorApplicationSchema>;\n\n/** Derived: `pending` until the first paid invoice, `active` for 12 months from it, `expired` after (§42.1). */\nexport const ReferralStatusSchema = z.enum([\"pending\", \"active\", \"expired\"]);\nexport type ReferralStatus = z.infer<typeof ReferralStatusSchema>;\n\nexport const ReferralSchema = z.object({\n id: idOf(\"crf\"),\n object: z.literal(\"referral\"),\n creator_id: idOf(\"crt\"),\n organization_id: idOf(\"org\"),\n status: ReferralStatusSchema,\n attributed_at: Timestamp,\n first_paid_at: Timestamp.nullable(),\n commission_until: Timestamp.nullable(),\n /** Opaque per-creator hash of the referred person, so organizations group by person; never the email. */\n person_key: z.string().nullable().optional(),\n});\nexport type Referral = z.infer<typeof ReferralSchema>;\n\nexport const CommissionKindSchema = z.enum([\"referral\", \"template\"]);\nexport type CommissionKind = z.infer<typeof CommissionKindSchema>;\n\n/** Derived from `available_at` and the payout the row is claimed by, never stored (§42.1). */\nexport const CommissionStatusSchema = z.enum([\n \"pending\",\n \"available\",\n \"claimed\",\n \"paid\",\n]);\nexport type CommissionStatus = z.infer<typeof CommissionStatusSchema>;\n\nexport const CommissionSchema = z.object({\n id: idOf(\"crc\"),\n object: z.literal(\"commission\"),\n creator_id: idOf(\"crt\"),\n kind: CommissionKindSchema,\n referral_id: idOf(\"crf\").nullable(),\n install_id: idOf(\"bpi\").nullable(),\n creator_template_id: idOf(\"ctp\").nullable(),\n base_micro_usd: MicroUsdField.nonnegative(),\n amount_micro_usd: MicroUsdField.nonnegative(),\n status: CommissionStatusSchema,\n accrued_at: Timestamp,\n available_at: Timestamp,\n payout_id: idOf(\"crp\").nullable(),\n});\nexport type Commission = z.infer<typeof CommissionSchema>;\n\nexport const PayoutStatusSchema = z.enum([\"requested\", \"paid\", \"rejected\"]);\nexport type PayoutStatus = z.infer<typeof PayoutStatusSchema>;\n\nexport const PayoutSchema = z.object({\n id: idOf(\"crp\"),\n object: z.literal(\"payout\"),\n creator_id: idOf(\"crt\"),\n amount_micro_usd: MicroUsdField.positive(),\n currency: z.literal(\"USD\"),\n method: PayoutMethodSchema,\n account: z.string().min(1),\n status: PayoutStatusSchema,\n reference: z.string().nullable(),\n note: z.string().nullable(),\n requested_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type Payout = z.infer<typeof PayoutSchema>;\n\n/** The percentages and thresholds of §42.7, §42.9 and §42.10, in one place so no route restates them. */\nexport const CREATOR_PROGRAM = {\n referral_percent: 15,\n /** Of each qualifying subscription invoice of an org whose FIRST install was the template. */\n template_percent: 15,\n commission_months: 12,\n hold_days: 30,\n attribution_days: 30,\n /** A template install earns only for an org it was installed in within this many days of creation. */\n template_new_org_days: 35,\n minimum_payout_micro_usd: 20_000_000,\n /** The creator studio's per-draft spend caps; one session never plans past what the draft has left. */\n studio: {\n draft_budget_micro_usd: 40_000_000,\n author_budget_micro_usd: 8_000_000,\n demo_budget_micro_usd: 10_000_000,\n uploads: 3,\n upload_max_bytes: 60 * 1024 * 1024,\n upload_token_minutes: 15,\n skill_max_bytes: 32 * 1024,\n },\n} as const;\n\n/** The creator's own part of the catalog key; `template` is `c-<code>-<slug>` (§42.8). */\nexport const CreatorTemplateSlugSchema = z\n .string()\n .max(32)\n .regex(\n /^[a-z0-9]+(-[a-z0-9]+)*$/,\n \"lowercase letters, digits and single dashes\",\n );\n\n/** The namespaced catalog key: what `POST /v1/blueprints/installs` receives as `template`. */\nexport const creatorTemplateName = (code: string, slug: string): string =>\n `c-${code}-${slug}`;\n\n/** One `SKILL.md` travelling with the declaration — a creator has no checkout for the engine's `file`. */\nexport const CreatorSkillSchema = z.object({\n slug: z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, \"lowercase letters, digits and dashes\"),\n body: z\n .string()\n .min(1)\n .max(64 * 1024),\n});\nexport type CreatorSkill = z.infer<typeof CreatorSkillSchema>;\n\n/**\n * The version `declaration` (§42.2). `agents[]` is exactly `AgentDeclSchema` and `questions[]`\n * exactly `QuestionFieldSchema`, but `AgentDeclSchema` lives in `@usenaive-sdk/blueprints`, which\n * depends on core — so core types those two arrays as `unknown` and the API validates a submission\n * by composing the artifact declaration and running the engine's `parseProject` over it. The draft\n * is checked for this shape only; a half-written crew may be saved.\n */\nexport const CreatorDeclarationSchema = z.object({\n agents: z.array(z.unknown()),\n questions: z.array(z.unknown()),\n skills: z.array(CreatorSkillSchema).max(16),\n /** A `niche` version only: the studio round it froze (see `NicheVersionStudioSchema`, below). */\n studio: z.lazy(() => NicheVersionStudioSchema).optional(),\n});\nexport type CreatorDeclaration = z.infer<typeof CreatorDeclarationSchema>;\n\nexport const CreatorTemplateVersionStatusSchema = z.enum([\n \"in_review\",\n \"approved\",\n \"changes_requested\",\n]);\nexport type CreatorTemplateVersionStatus = z.infer<\n typeof CreatorTemplateVersionStatusSchema\n>;\n\nconst VersionNumber = z.number().int().positive();\n\n/** `crew`: the hand-built crew declaration; `niche`: authored by agents in the creator studio. */\nexport const CreatorTemplateKindSchema = z.enum([\"crew\", \"niche\"]);\nexport type CreatorTemplateKind = z.infer<typeof CreatorTemplateKindSchema>;\n\n/** The studio lifecycle of a `niche` template; a `crew` template stays `setup` and never reads it. */\nexport const StudioStateSchema = z.enum([\n \"setup\",\n \"building\",\n \"ready\",\n \"in_review\",\n \"live\",\n \"changes_requested\",\n]);\nexport type StudioState = z.infer<typeof StudioStateSchema>;\n\nexport const StudioUploadContentTypeSchema = z.enum([\n \"video/mp4\",\n \"video/quicktime\",\n \"video/webm\",\n]);\nexport type StudioUploadContentType = z.infer<\n typeof StudioUploadContentTypeSchema\n>;\n\nconst UploadPosition = z.number().int().min(1).max(CREATOR_PROGRAM.studio.uploads);\nconst StudioPrompt = z.string().max(2000);\n\n/** One of the three reference videos; `file_id` is null until its PUT lands (a studio-org file). */\nexport const StudioUploadSchema = z.object({\n position: UploadPosition,\n file_id: z.string().nullable(),\n prompt: StudioPrompt,\n bytes: z.number().int().positive().max(CREATOR_PROGRAM.studio.upload_max_bytes),\n content_type: StudioUploadContentTypeSchema,\n filename: z.string().min(1).max(200),\n});\nexport type StudioUpload = z.infer<typeof StudioUploadSchema>;\n\n/** `creator_template.studio` (migration 0098). Empty `{}` in the database reads as this default. */\nexport const CreatorStudioSchema = z.object({\n uploads: z.array(StudioUploadSchema).max(CREATOR_PROGRAM.studio.uploads).default([]),\n state: StudioStateSchema.default(\"setup\"),\n spend_micro_usd: MicroUsdField.nonnegative().default(0),\n rights_attested_at: Timestamp.nullable().default(null),\n});\nexport type CreatorStudio = z.infer<typeof CreatorStudioSchema>;\n\n/** The reviewer-curated catalog columns of a creator template (migration 0098). */\nexport const CreatorTemplateListingSchema = z.object({\n listed: z.boolean(),\n featured: z.boolean(),\n sort_order: z.number().int(),\n tagline: z.string().max(140).nullable(),\n hero_file_id: z.string().nullable(),\n});\nexport type CreatorTemplateListing = z.infer<typeof CreatorTemplateListingSchema>;\n\nexport const StudioRoundStateSchema = z.enum([\n \"queued\",\n \"authoring\",\n \"rendering\",\n \"ready\",\n \"failed\",\n]);\nexport type StudioRoundState = z.infer<typeof StudioRoundStateSchema>;\n\n/** A generated, brand-free reference frame: `file` is its path in the skill folder (`reference/…`). */\nexport const StudioFrameSchema = z.object({\n file: z.string().min(1),\n file_id: z.string().min(1),\n role: z.string(),\n});\nexport type StudioFrame = z.infer<typeof StudioFrameSchema>;\n\nexport const StudioSampleSchema = z.object({\n file_id: z.string().min(1),\n poster_file_id: z.string().nullable(),\n seconds: z.number().nonnegative(),\n title: z.string(),\n});\nexport type StudioSample = z.infer<typeof StudioSampleSchema>;\n\n/** One build or revision (`vetta.creator_template_round`), keyed `(template_id, n)`. */\nexport const CreatorTemplateRoundSchema = z.object({\n object: z.literal(\"creator_template_round\"),\n template_id: idOf(\"ctp\"),\n n: z.number().int().positive(),\n feedback: z.string().nullable(),\n state: StudioRoundStateSchema,\n author_session_id: z.string().nullable(),\n demo_session_id: z.string().nullable(),\n skill_md: z.string().nullable(),\n reference_json: z.unknown().nullable(),\n frames: z.array(StudioFrameSchema),\n samples: z.array(StudioSampleSchema),\n spend_micro_usd: MicroUsdField.nonnegative(),\n error: z.string().nullable(),\n created_at: Timestamp,\n finished_at: Timestamp.nullable(),\n});\nexport type CreatorTemplateRound = z.infer<typeof CreatorTemplateRoundSchema>;\n\n/** What a `niche` version freezes beside its one skill: what the reviewer and the publish read. */\nexport const NicheVersionStudioSchema = z.object({\n round: z.number().int().positive(),\n uploads: z.array(StudioUploadSchema),\n reference_json: z.unknown().nullable(),\n frames: z.array(StudioFrameSchema),\n samples: z.array(StudioSampleSchema),\n tagline: z.string().max(140),\n hero_sample_index: z.number().int().nonnegative(),\n});\nexport type NicheVersionStudio = z.infer<typeof NicheVersionStudioSchema>;\n\nexport const CreatorTemplateSchema = z.object({\n id: idOf(\"ctp\"),\n object: z.literal(\"creator_template\"),\n creator_id: idOf(\"crt\"),\n blueprint: z.string().min(1),\n base_template: z.string().min(1),\n slug: CreatorTemplateSlugSchema,\n template: z.string().min(1).max(64),\n name: z.string().min(1).max(80),\n description: z.string().max(2000),\n declaration: CreatorDeclarationSchema,\n published_version: VersionNumber.nullable(),\n latest_version: z\n .object({\n version: VersionNumber,\n status: CreatorTemplateVersionStatusSchema,\n })\n .nullable(),\n kind: CreatorTemplateKindSchema,\n studio: CreatorStudioSchema,\n listing: CreatorTemplateListingSchema,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type CreatorTemplate = z.infer<typeof CreatorTemplateSchema>;\n\n/** Keyed `(template_id, version)`; immutable but for `status`, `note`, `decided_at`, `artifact_id`. */\nexport const CreatorTemplateVersionSchema = z.object({\n object: z.literal(\"creator_template_version\"),\n template_id: idOf(\"ctp\"),\n version: VersionNumber,\n declaration: CreatorDeclarationSchema,\n status: CreatorTemplateVersionStatusSchema,\n note: z.string().nullable(),\n artifact_id: idOf(\"bpa\").nullable(),\n submitted_at: Timestamp,\n decided_at: Timestamp.nullable(),\n});\nexport type CreatorTemplateVersion = z.infer<\n typeof CreatorTemplateVersionSchema\n>;\n\n/** `GET /v1/creator/balance` — the caller's commissions summed by derived status (§42.4). */\nexport const CreatorBalanceSchema = z.object({\n object: z.literal(\"creator_balance\"),\n pending_micro_usd: MicroUsdField.nonnegative(),\n available_micro_usd: MicroUsdField.nonnegative(),\n claimed_micro_usd: MicroUsdField.nonnegative(),\n paid_micro_usd: MicroUsdField.nonnegative(),\n minimum_payout_micro_usd: z.literal(CREATOR_PROGRAM.minimum_payout_micro_usd),\n});\nexport type CreatorBalance = z.infer<typeof CreatorBalanceSchema>;\n\n/** `POST /v1/referral_clicks` (§42.6) — what the landing page times its 30-day cookie by. */\nexport const ReferralClickSchema = z.object({\n object: z.literal(\"referral_click\"),\n code: CreatorCodeSchema,\n creator: z.object({ display_name: z.string().min(1) }),\n expires_at: Timestamp,\n});\nexport type ReferralClick = z.infer<typeof ReferralClickSchema>;\n\nconst Day = z.iso.date();\n\n/** One shape for both analytics routes (§42.11); the template route narrows to one template's installs. */\nexport const CreatorAnalyticsSchema = z.object({\n object: z.literal(\"creator_analytics\"),\n days: z.number().int().min(1).max(90),\n from: Day,\n to: Day,\n clicks: z.number().int().nonnegative(),\n referrals: z.number().int().nonnegative(),\n installs: z.number().int().nonnegative(),\n active_installs: z.number().int().nonnegative(),\n /** Distinct orgs with at least one commission-bearing invoice in the window (invoice-based template commission). */\n paying_orgs: z.number().int().nonnegative().optional(),\n /** DEPRECATED with the 5% usage accrual; optional until `analytics()` stops returning it. */\n usage_by_day: z\n .array(z.object({ day: Day, debit_micro_usd: MicroUsdField.nonnegative() }))\n .optional(),\n commission_micro_usd: z.object({\n pending: MicroUsdField.nonnegative(),\n available: MicroUsdField.nonnegative(),\n claimed: MicroUsdField.nonnegative(),\n paid: MicroUsdField.nonnegative(),\n }),\n commissions_by_template: z.array(\n z.object({\n creator_template_id: idOf(\"ctp\"),\n amount_micro_usd: MicroUsdField.nonnegative(),\n }),\n ),\n /** Every install covered, newest first: the day it was created and the day its twelve months end. */\n install_windows: z\n .array(z.object({ install_id: idOf(\"bpi\"), from: Day, until: Day }))\n .optional(),\n});\nexport type CreatorAnalytics = z.infer<typeof CreatorAnalyticsSchema>;\n\n// ── The creator studio's wire (`/v1/creator/templates/:id/{uploads,rounds,studio}`, `/v1/creator-admin/listings`)\n\n/** `POST /v1/creator/templates` — `kind: niche` makes a studio template; `crew` is the old builder. */\nexport const CreatorTemplateCreateKindSchema = z.object({\n kind: CreatorTemplateKindSchema.default(\"crew\"),\n});\n\n/** `POST /v1/creator/templates/:id/uploads`. */\nexport const StudioUploadCreateSchema = z.object({\n position: UploadPosition,\n filename: z.string().min(1).max(200),\n content_type: StudioUploadContentTypeSchema,\n bytes: z.number().int().positive().max(CREATOR_PROGRAM.studio.upload_max_bytes),\n});\nexport type StudioUploadCreate = z.infer<typeof StudioUploadCreateSchema>;\n\n/** Its answer: the browser PUTs the bytes to `upload_url` (one-shot, `upload_token_minutes`). */\nexport const StudioUploadTicketSchema = z.object({\n object: z.literal(\"studio_upload_ticket\"),\n position: UploadPosition,\n upload_url: z.url(),\n expires_at: Timestamp,\n});\nexport type StudioUploadTicket = z.infer<typeof StudioUploadTicketSchema>;\n\n/** `PATCH /v1/creator/templates/:id/uploads/:position`. */\nexport const StudioUploadPatchSchema = z.object({ prompt: StudioPrompt });\nexport type StudioUploadPatch = z.infer<typeof StudioUploadPatchSchema>;\n\n/** `PUT /v1/creator/uploads/:token` answers the upload as now stored. */\nexport const StudioUploadResultSchema = z.object({\n object: z.literal(\"studio_upload\"),\n template_id: idOf(\"ctp\"),\n upload: StudioUploadSchema,\n});\nexport type StudioUploadResult = z.infer<typeof StudioUploadResultSchema>;\n\n/**\n * `POST /v1/creator/templates/:id/rounds`. The first round needs three uploads with prompts and the\n * rights attestation (`rights_attested: true` here, or already on the studio); a revision needs\n * `feedback`.\n */\nexport const StudioRoundCreateSchema = z.object({\n feedback: z.string().min(1).max(4000).optional(),\n rights_attested: z.boolean().optional(),\n});\nexport type StudioRoundCreate = z.infer<typeof StudioRoundCreateSchema>;\n\nexport const StudioBudgetSchema = z.object({\n draft_micro_usd: MicroUsdField.nonnegative(),\n spent_micro_usd: MicroUsdField.nonnegative(),\n remaining_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type StudioBudget = z.infer<typeof StudioBudgetSchema>;\n\n/** `GET /v1/creator/templates/:id/studio` — advances the newest round on read, then answers this. */\nexport const CreatorStudioViewSchema = z.object({\n object: z.literal(\"creator_studio\"),\n template_id: idOf(\"ctp\"),\n studio: CreatorStudioSchema,\n /** Newest first. */\n rounds: z.array(CreatorTemplateRoundSchema),\n budget: StudioBudgetSchema,\n});\nexport type CreatorStudioView = z.infer<typeof CreatorStudioViewSchema>;\n\n/** `POST /v1/creator/templates/:id/versions` for a `niche` template (a `crew` template sends `{}`). */\nexport const NicheSubmitSchema = z.object({\n round: z.number().int().positive(),\n listing: z.object({\n tagline: z.string().min(1).max(140),\n hero_sample_index: z.number().int().nonnegative(),\n }),\n});\nexport type NicheSubmit = z.infer<typeof NicheSubmitSchema>;\n\n/** `PATCH /v1/creator-admin/listings/:template_id`. */\nexport const CreatorListingPatchSchema = CreatorTemplateListingSchema.partial();\nexport type CreatorListingPatch = z.infer<typeof CreatorListingPatchSchema>;\n\n/** One row of `GET /v1/creator-admin/listings`: a published creator template and its curation. */\nexport const CreatorListingSchema = z.object({\n object: z.literal(\"creator_listing\"),\n template_id: idOf(\"ctp\"),\n template: z.string().min(1),\n name: z.string(),\n kind: CreatorTemplateKindSchema,\n blueprint: z.string(),\n base_template: z.string(),\n published_version: VersionNumber.nullable(),\n creator: z.object({\n id: idOf(\"crt\"),\n display_name: z.string(),\n code: CreatorCodeSchema,\n status: CreatorStatusSchema,\n }),\n listing: CreatorTemplateListingSchema,\n /** Installs of the template, and distinct orgs among them that earned a template commission. */\n deploys: z.number().int().nonnegative().optional(),\n paying_orgs: z.number().int().nonnegative().optional(),\n updated_at: Timestamp,\n});\nexport type CreatorListing = z.infer<typeof CreatorListingSchema>;\n","/** Identity-owned legal: verifications and companies (`canonical-spec.md §43`). */\n\nimport { z } from \"zod\";\nimport { VettaError } from \"../errors\";\nimport { Metadata, MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const LEGAL_MEMBER_STATUSES = [\n \"pending\",\n \"link_ready\",\n \"link_sent\",\n \"in_progress\",\n \"pending_review\",\n \"verified\",\n \"failed\",\n] as const;\nexport const LegalMemberStatusSchema = z.enum(LEGAL_MEMBER_STATUSES);\nexport type LegalMemberStatus = z.infer<typeof LegalMemberStatusSchema>;\n\nexport const LEGAL_VERIFICATION_STATUSES = [\"in_progress\", \"pending_review\", \"verified\", \"failed\"] as const;\nexport const LegalVerificationStatusSchema = z.enum(LEGAL_VERIFICATION_STATUSES);\nexport type LegalVerificationStatus = z.infer<typeof LegalVerificationStatusSchema>;\n\nexport const LEGAL_COMPANY_STATUSES = [\"awaiting_payment\", \"paid\", \"submitted\", \"formed\", \"failed\"] as const;\nexport const LegalCompanyStatusSchema = z.enum(LEGAL_COMPANY_STATUSES);\nexport type LegalCompanyStatus = z.infer<typeof LegalCompanyStatusSchema>;\n\nexport const LEGAL_DOCUMENT_KINDS = [\"articles\", \"ein_letter\", \"operating_agreement\", \"other\"] as const;\nexport const LegalDocumentKindSchema = z.enum(LEGAL_DOCUMENT_KINDS);\nexport type LegalDocumentKind = z.infer<typeof LegalDocumentKindSchema>;\n\nexport const LegalMemberRoleSchema = z.enum([\"primary\", \"secondary\"]);\nexport const LegalEinStatusSchema = z.enum([\"none\", \"pending\", \"issued\"]);\nexport const LegalRequiredActionKindSchema = z.enum([\"signature\", \"information\", \"payment\", \"other\"]);\nexport type LegalRequiredActionKind = z.infer<typeof LegalRequiredActionKindSchema>;\n\n/** The 50 states plus DC, two-letter and uppercase. */\nexport const US_STATES = [\n \"AL\", \"AK\", \"AZ\", \"AR\", \"CA\", \"CO\", \"CT\", \"DE\", \"DC\", \"FL\", \"GA\", \"HI\", \"ID\", \"IL\", \"IN\", \"IA\", \"KS\",\n \"KY\", \"LA\", \"ME\", \"MD\", \"MA\", \"MI\", \"MN\", \"MS\", \"MO\", \"MT\", \"NE\", \"NV\", \"NH\", \"NJ\", \"NM\", \"NY\", \"NC\",\n \"ND\", \"OH\", \"OK\", \"OR\", \"PA\", \"RI\", \"SC\", \"SD\", \"TN\", \"TX\", \"UT\", \"VT\", \"VA\", \"WA\", \"WV\", \"WI\", \"WY\",\n] as const;\nexport const UsStateSchema = z.enum(US_STATES);\nexport type UsState = z.infer<typeof UsStateSchema>;\n\nexport const LegalMemberInputSchema = z.object({\n first_name: z.string().min(1).max(128),\n last_name: z.string().min(1).max(128),\n email: z.string().min(1).max(320),\n role: LegalMemberRoleSchema,\n is_responsible_party: z.boolean(),\n ownership_percent: z.number().int(),\n});\nexport type LegalMemberInput = z.infer<typeof LegalMemberInputSchema>;\n\nexport const LegalMemberSchema = LegalMemberInputSchema.extend({\n id: idOf(\"lgm\"),\n object: z.literal(\"legal_member\"),\n verification_id: idOf(\"lgv\"),\n status: LegalMemberStatusSchema,\n link_url: z.url().nullable(),\n link_expires_at: Timestamp.nullable(),\n completed_at: Timestamp.nullable(),\n});\nexport type LegalMember = z.infer<typeof LegalMemberSchema>;\n\nexport const LegalVerificationSchema = z.object({\n id: idOf(\"lgv\"),\n object: z.literal(\"legal_verification\"),\n identity_id: idOf(\"idn\"),\n status: LegalVerificationStatusSchema,\n members: z.array(LegalMemberSchema),\n ready_for_formation: z.boolean(),\n started_at: Timestamp,\n completed_at: Timestamp.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type LegalVerification = z.infer<typeof LegalVerificationSchema>;\n\nexport const StartLegalVerificationSchema = z.object({ members: z.array(LegalMemberInputSchema) });\nexport type StartLegalVerification = z.infer<typeof StartLegalVerificationSchema>;\n\nexport const CompleteLegalMemberSchema = z.object({ token: z.string().min(1) });\n\nexport const LegalNameOptionSchema = z.object({ name: z.string().min(1).max(200), ending: z.literal(\"LLC\") });\nexport type LegalNameOption = z.infer<typeof LegalNameOptionSchema>;\n\nexport const LegalMailingAddressSchema = z.object({\n line1: z.string().min(1).max(200),\n line2: z.string().max(200).nullable(),\n city: z.string().min(1).max(100),\n state: UsStateSchema,\n postal_code: z.string().min(1).max(16),\n country: z.literal(\"US\"),\n});\nexport type LegalMailingAddress = z.infer<typeof LegalMailingAddressSchema>;\n\nexport const LegalRequiredActionSchema = z.object({\n kind: LegalRequiredActionKindSchema,\n description: z.string(),\n url: z.url().nullable(),\n});\nexport type LegalRequiredAction = z.infer<typeof LegalRequiredActionSchema>;\n\n/** The one length rule the provider imposes on a company description. */\nexport const LEGAL_DESCRIPTION_MAX = 50;\n\nexport const CreateLegalCompanySchema = z.object({\n verification_id: idOf(\"lgv\"),\n state: UsStateSchema,\n name_options: z.array(z.string().min(1).max(200)).min(1).max(3),\n naics_code: z.string().regex(/^\\d{2,6}$/),\n description: z.string().min(1).max(LEGAL_DESCRIPTION_MAX),\n mailing_address: LegalMailingAddressSchema,\n});\nexport type CreateLegalCompany = z.infer<typeof CreateLegalCompanySchema>;\n\nexport const LegalCompanySchema = CreateLegalCompanySchema.omit({ name_options: true }).extend({\n id: idOf(\"lgc\"),\n object: z.literal(\"legal_company\"),\n identity_id: idOf(\"idn\"),\n status: LegalCompanyStatusSchema,\n entity_type: z.literal(\"llc\"),\n name_options: z.array(LegalNameOptionSchema),\n legal_name: z.string().nullable(),\n ein_status: LegalEinStatusSchema,\n price_micro_usd: MicroUsdField,\n required_actions: z.array(LegalRequiredActionSchema),\n failure_reason: z.string().max(256).nullable(),\n submitted_at: Timestamp.nullable(),\n formed_at: Timestamp.nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type LegalCompany = z.infer<typeof LegalCompanySchema>;\n\nexport const LegalDocumentSchema = z.object({\n id: idOf(\"lgd\"),\n object: z.literal(\"legal_document\"),\n company_id: idOf(\"lgc\"),\n kind: LegalDocumentKindSchema,\n name: z.string(),\n created_at: Timestamp,\n});\nexport type LegalDocument = z.infer<typeof LegalDocumentSchema>;\n\nexport const LegalDocumentLinkSchema = z.object({\n object: z.literal(\"legal_document_link\"),\n url: z.url(),\n expires_at: Timestamp,\n});\nexport type LegalDocumentLink = z.infer<typeof LegalDocumentLinkSchema>;\n\nexport const NaicsCodeSchema = z.object({\n object: z.literal(\"naics_code\"),\n code: z.string().regex(/^\\d{2,6}$/),\n title: z.string(),\n});\nexport type NaicsCode = z.infer<typeof NaicsCodeSchema>;\n\nexport const LegalStateSchema = z.object({\n object: z.literal(\"legal_state\"),\n code: UsStateSchema,\n name: z.string(),\n formation_fee_micro_usd: MicroUsdField,\n});\nexport type LegalState = z.infer<typeof LegalStateSchema>;\n\n/** What the provider's webhook tells us about one hosted session, vendor words already translated. */\nexport const LegalWebhookEventSchema = z.object({\n provider_session_ref: z.string().min(1),\n status: z.enum([\"verified\", \"failed\", \"pending_review\"]),\n metadata: Metadata,\n});\nexport type LegalWebhookEvent = z.infer<typeof LegalWebhookEventSchema>;\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** The legacy `validateMembers` rules, messages verbatim, as one `validation_failed` (§43.3). */\nexport function checkMembers(members: readonly LegalMemberInput[]): void {\n const refuse = (message: string): never => {\n throw new VettaError(\"validation_failed\", message, \"members\");\n };\n if (members.length === 0) refuse(\"At least one member is required\");\n const primaryCount = members.filter((m) => m.role === \"primary\").length;\n if (primaryCount !== 1) refuse(`Exactly one member must have role 'primary', found ${primaryCount}`);\n const rpCount = members.filter((m) => m.is_responsible_party).length;\n if (rpCount !== 1) refuse(`Exactly one member must be designated as responsible party, found ${rpCount}`);\n for (const m of members) {\n if (m.ownership_percent < 0 || m.ownership_percent > 100) {\n refuse(`Ownership percentage must be 0-100, got ${m.ownership_percent} for ${m.email}`);\n }\n }\n const totalOwnership = members.reduce((sum, m) => sum + m.ownership_percent, 0);\n if (totalOwnership !== 100) refuse(`Ownership percentages must sum to 100, got ${totalOwnership}`);\n for (const m of members) if (!EMAIL.test(m.email)) refuse(`Invalid email address: ${m.email}`);\n}\n\nconst LLC_ENDING = /\\s*(?:,\\s*)?(?:l\\.?l\\.?c\\.?|limited\\s+liability\\s+company)\\s*$/i;\n\n/** Strips any spelling of the LLC ending and answers the canonical `{ name, ending }` (§43.3). */\nexport function canonicalName(raw: string): LegalNameOption {\n const name = raw.replace(LLC_ENDING, \"\").trim();\n if (name.length === 0) throw new VettaError(\"validation_failed\", \"A company name is required\", \"name_options\");\n return { name, ending: \"LLC\" };\n}\n\n/** The display form of a name option: `\"<name> LLC\"`. */\nexport const displayName = (option: LegalNameOption): string => `${option.name} ${option.ending}`;\n\n/** The legacy status machine: any failed → failed; any review → pending_review; all verified → verified. */\nexport function verificationStatus(statuses: readonly LegalMemberStatus[]): LegalVerificationStatus {\n if (statuses.some((s) => s === \"failed\")) return \"failed\";\n if (statuses.some((s) => s === \"pending_review\")) return \"pending_review\";\n if (statuses.length > 0 && statuses.every((s) => s === \"verified\")) return \"verified\";\n return \"in_progress\";\n}\n\n/**\n * What a store keeps for each legal object: the wire shape less its transient/derived fields, plus\n * the provider handles. No handle is a person's data and no hosted-session token is a field here,\n * so a record can only ever project into a safe wire object (§43.1, PII boundary).\n */\nexport type LegalVerificationRecord = Omit<LegalVerification, \"object\" | \"members\" | \"ready_for_formation\">;\nexport type LegalMemberRecord = Omit<LegalMember, \"object\" | \"link_url\"> & {\n provider_session_ref: string | null;\n provider_person_ref: string | null;\n created_at: string;\n updated_at: string;\n};\nexport type LegalCompanyRecord = Omit<LegalCompany, \"object\"> & {\n ledger_entry_id: string | null;\n provider_customer_ref: string | null;\n provider_formation_ref: string | null;\n};\nexport type LegalDocumentRecord = Omit<LegalDocument, \"object\"> & { provider_document_ref: string };\n\n/** Member states a webhook redelivery or a poll may no longer move (§43.2). */\nexport const isTerminalMember = (status: LegalMemberStatus): boolean => status === \"verified\" || status === \"failed\";\n\n/** A provider outcome lands on a member unless the member is already final (§43.2). */\nexport function settleMember(\n member: LegalMemberRecord,\n outcome: { status: LegalMemberStatus; providerPersonRef: string | null },\n now: string,\n): LegalMemberRecord {\n if (isTerminalMember(member.status) || outcome.status === \"in_progress\") return member;\n return {\n ...member,\n status: outcome.status,\n provider_person_ref: outcome.providerPersonRef ?? member.provider_person_ref,\n completed_at: isTerminalMember(outcome.status) ? now : member.completed_at,\n updated_at: now,\n };\n}\n\n/** The parent follows its members (`verificationStatus`); the same record back means nothing moved. */\nexport function settleVerification(\n record: LegalVerificationRecord,\n members: readonly LegalMemberRecord[],\n now: string,\n): LegalVerificationRecord {\n const status = verificationStatus(members.map((m) => m.status));\n if (status === record.status) return record;\n const done = status === \"verified\" || status === \"failed\";\n return { ...record, status, completed_at: done ? now : null, updated_at: now };\n}\n\n/**\n * What a paid company files as: the row plus its members by verified-person handle. The adapter reads\n * each person's PII back from the provider vault; nothing personal crosses here (§43.1).\n */\nexport function formationInput(record: LegalCompanyRecord, members: readonly LegalMemberRecord[]) {\n const { postal_code: postalCode, ...address } = record.mailing_address;\n return {\n idempotencyKey: record.id,\n state: record.state,\n nameOptions: record.name_options,\n naicsCode: record.naics_code,\n description: record.description,\n mailingAddress: { ...address, postalCode },\n members: members.map((m) => {\n if (m.provider_person_ref === null) {\n throw new VettaError(\"state_conflict\", \"every member must be verified before the formation is filed\");\n }\n return {\n role: m.role,\n is_responsible_party: m.is_responsible_party,\n ownership_percent: m.ownership_percent,\n providerPersonRef: m.provider_person_ref,\n };\n }),\n };\n}\n\n/** Folds the provider's view of a filing into the row; `formed` and `failed` are final. */\nexport function foldFormation(\n record: LegalCompanyRecord,\n state: {\n providerFormationRef: string;\n status: Extract<LegalCompanyStatus, \"submitted\" | \"formed\" | \"failed\">;\n legalName: string | null;\n einStatus: LegalCompany[\"ein_status\"];\n requiredActions: LegalRequiredAction[];\n failureReason: string | null;\n },\n now: string,\n): LegalCompanyRecord {\n return {\n ...record,\n status: state.status,\n legal_name: state.legalName,\n ein_status: state.einStatus,\n required_actions: state.requiredActions,\n failure_reason: state.failureReason,\n provider_formation_ref: state.providerFormationRef,\n submitted_at: record.submitted_at ?? now,\n formed_at: state.status === \"formed\" ? (record.formed_at ?? now) : record.formed_at,\n updated_at: now,\n };\n}\n\n/** The wire member; `linkUrl` is only ever the link this very call minted (create / resend). */\nexport function toLegalMember(record: LegalMemberRecord, linkUrl: string | null = null): LegalMember {\n const { provider_session_ref: _s, provider_person_ref: _p, created_at: _c, updated_at: _u, ...safe } = record;\n return { object: \"legal_member\", ...safe, link_url: linkUrl };\n}\n\nexport function toLegalVerification(record: LegalVerificationRecord, members: LegalMember[]): LegalVerification {\n return { object: \"legal_verification\", ...record, members, ready_for_formation: record.status === \"verified\" };\n}\n\n/** Links are only ever the ones this call minted; a read never carries one (§43.1). */\nexport const verificationView = (\n record: LegalVerificationRecord,\n members: readonly LegalMemberRecord[],\n links = new Map<string, string>(),\n): LegalVerification =>\n toLegalVerification(record, members.map((m) => toLegalMember(m, links.get(m.id) ?? null)));\n\nexport function toLegalCompany(record: LegalCompanyRecord): LegalCompany {\n const { ledger_entry_id: _l, provider_customer_ref: _c, provider_formation_ref: _f, ...safe } = record;\n return { object: \"legal_company\", ...safe };\n}\n\nexport function toLegalDocument(record: LegalDocumentRecord): LegalDocument {\n const { provider_document_ref: _r, ...safe } = record;\n return { object: \"legal_document\", ...safe };\n}\n","/** Identity-owned custodied wallet with x402 payments (`canonical-spec.md §44`). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\n\n/** CAIP-2 on the wire: Base Sepolia (the default) and Base mainnet. */\nexport const WALLET_NETWORKS = [\"eip155:84532\", \"eip155:8453\"] as const;\nexport const WalletNetworkSchema = z.enum(WALLET_NETWORKS);\nexport type WalletNetwork = z.infer<typeof WalletNetworkSchema>;\nexport const DEFAULT_WALLET_NETWORK: WalletNetwork = \"eip155:84532\";\n\n/** The CLI / IaC aliases, resolved client-side to the CAIP-2 value. */\nexport const WALLET_NETWORK_ALIASES: Record<\"base-testnet\" | \"base\", WalletNetwork> = {\n \"base-testnet\": \"eip155:84532\",\n base: \"eip155:8453\",\n};\n\n/** `?network=` on every wallet route: which of the identity's wallets a call addresses. */\nexport const WalletSelectSchema = z.object({ network: WalletNetworkSchema.optional() });\nexport type WalletSelect = z.infer<typeof WalletSelectSchema>;\n\nexport const WALLET_STATUSES = [\"active\", \"frozen\", \"swept\"] as const;\nexport const WalletStatusSchema = z.enum(WALLET_STATUSES);\nexport type WalletStatus = z.infer<typeof WalletStatusSchema>;\n\nexport const WALLET_TRANSACTION_KINDS = [\"fund\", \"transfer\", \"pay\", \"sweep\"] as const;\nexport const WalletTransactionKindSchema = z.enum(WALLET_TRANSACTION_KINDS);\nexport type WalletTransactionKind = z.infer<typeof WalletTransactionKindSchema>;\n\nexport const WALLET_TRANSACTION_STATUSES = [\"pending\", \"confirmed\", \"failed\"] as const;\nexport const WalletTransactionStatusSchema = z.enum(WALLET_TRANSACTION_STATUSES);\nexport type WalletTransactionStatus = z.infer<typeof WalletTransactionStatusSchema>;\n\nexport const WalletDirectionSchema = z.enum([\"in\", \"out\"]);\nexport const WalletFundSourceSchema = z.enum([\"faucet\", \"treasury\"]);\n\nexport const EvmAddressSchema = z.string().regex(/^0x[0-9a-fA-F]{40}$/, \"expected a 0x address\");\nexport const TxHashSchema = z.string().regex(/^0x[0-9a-fA-F]{64}$/, \"expected a 0x transaction hash\");\n\n/** $0.50: the legacy default per-transaction cap. */\nexport const DEFAULT_PER_TX_CAP_MICRO_USD = 500_000;\n\nexport const WalletPolicySchema = z.object({\n per_tx_cap_micro_usd: MicroUsdField.nonnegative(),\n daily_cap_micro_usd: MicroUsdField.positive().nullable(),\n low_balance_micro_usd: MicroUsdField.nonnegative().nullable(),\n});\nexport type WalletPolicy = z.infer<typeof WalletPolicySchema>;\n\nexport const isTestnet = (network: WalletNetwork): boolean => network === \"eip155:84532\";\n\n/** The UTC day a `wallet_spend_counter` row is keyed by. */\nexport const walletDay = (nowIso: string): string => nowIso.slice(0, 10);\n\n/**\n * Why an outward amount is refused by the wallet's own policy, or `null` when it fits. The one\n * rule the route and the agent tool both enforce before the custody provider sees a request.\n */\nexport function walletCapViolation(\n policy: WalletPolicy,\n amountMicroUsd: number,\n spentTodayMicroUsd: number,\n): string | null {\n if (amountMicroUsd > policy.per_tx_cap_micro_usd) return \"the amount exceeds per_tx_cap_micro_usd\";\n if (policy.daily_cap_micro_usd !== null && spentTodayMicroUsd + amountMicroUsd > policy.daily_cap_micro_usd) {\n return \"the amount exceeds daily_cap_micro_usd for today\";\n }\n return null;\n}\n\n/** The cheapest requirement on the wallet's own network — the one a quote reports and a pay signs. */\nexport function pickPaymentRequirement<T extends { network: WalletNetwork; amountMicroUsd: number }>(\n requirements: readonly T[],\n network: WalletNetwork,\n): T | undefined {\n return requirements\n .filter((requirement) => requirement.network === network)\n .sort((a, b) => a.amountMicroUsd - b.amountMicroUsd)[0];\n}\n\nexport const WalletSchema = z.object({\n id: idOf(\"wlt\"),\n object: z.literal(\"wallet\"),\n identity_id: idOf(\"idn\"),\n status: WalletStatusSchema,\n network: WalletNetworkSchema,\n address: EvmAddressSchema,\n asset: z.literal(\"usdc\"),\n balance_micro_usd: MicroUsdField,\n policy: WalletPolicySchema,\n spent_today_micro_usd: MicroUsdField,\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Wallet = z.infer<typeof WalletSchema>;\n\nexport const CreateWalletSchema = z.object({\n network: WalletNetworkSchema.optional(),\n policy: WalletPolicySchema.partial().optional(),\n});\nexport type CreateWallet = z.infer<typeof CreateWalletSchema>;\n\nexport const UpdateWalletPolicySchema = WalletPolicySchema.partial();\n\nexport const FundWalletSchema = z.object({\n amount_micro_usd: MicroUsdField.positive(),\n source: WalletFundSourceSchema,\n});\nexport type FundWallet = z.infer<typeof FundWalletSchema>;\n\nexport const TransferWalletSchema = z.object({\n to: z.union([EvmAddressSchema, idOf(\"idn\")]),\n amount_micro_usd: MicroUsdField.positive(),\n purpose: z.string().min(1).max(256),\n});\nexport type TransferWallet = z.infer<typeof TransferWalletSchema>;\n\nexport const SweepWalletSchema = z.object({ to: EvmAddressSchema.optional() });\n\nexport const WalletTransactionSchema = z.object({\n id: idOf(\"wtx\"),\n object: z.literal(\"wallet_transaction\"),\n wallet_id: idOf(\"wlt\"),\n kind: WalletTransactionKindSchema,\n direction: WalletDirectionSchema,\n amount_micro_usd: MicroUsdField,\n counterparty: z.string().nullable(),\n origin: z.string().nullable(),\n purpose: z.string().nullable(),\n tx_hash: TxHashSchema.nullable(),\n session_id: idOf(\"ses\").nullable(),\n status: WalletTransactionStatusSchema,\n created_at: Timestamp,\n});\nexport type WalletTransaction = z.infer<typeof WalletTransactionSchema>;\n\nexport const ListWalletTransactionsSchema = z.object({\n kind: WalletTransactionKindSchema.optional(),\n direction: WalletDirectionSchema.optional(),\n origin: z.string().optional(),\n since: Timestamp.optional(),\n});\nexport type ListWalletTransactions = z.infer<typeof ListWalletTransactionsSchema>;\n\nconst HttpMethodSchema = z.enum([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nexport const WalletQuoteRequestSchema = z.object({ url: z.url(), method: HttpMethodSchema.optional() });\nexport type WalletQuoteRequest = z.infer<typeof WalletQuoteRequestSchema>;\n\nexport const WalletQuoteSchema = z.object({\n object: z.literal(\"wallet_quote\"),\n url: z.url(),\n payable: z.boolean(),\n network: WalletNetworkSchema.nullable(),\n asset: z.literal(\"usdc\").nullable(),\n amount_micro_usd: MicroUsdField.nullable(),\n pay_to: EvmAddressSchema.nullable(),\n description: z.string().nullable(),\n max_timeout_seconds: z.number().int().nullable(),\n});\nexport type WalletQuote = z.infer<typeof WalletQuoteSchema>;\n\nexport const WalletPayRequestSchema = WalletQuoteRequestSchema.extend({\n max_amount_micro_usd: MicroUsdField.positive().optional(),\n});\nexport type WalletPayRequest = z.infer<typeof WalletPayRequestSchema>;\n\n/** The paid response's body is echoed up to this many bytes. */\nexport const WALLET_RESPONSE_BODY_MAX = 64 * 1024;\n\nexport const WalletPaymentSchema = z.object({\n object: z.literal(\"wallet_payment\"),\n paid: z.boolean(),\n transaction_id: idOf(\"wtx\").nullable(),\n amount_micro_usd: MicroUsdField.nullable(),\n response_status: z.number().int(),\n response_body: z.string().max(WALLET_RESPONSE_BODY_MAX),\n});\nexport type WalletPayment = z.infer<typeof WalletPaymentSchema>;\n\nexport * from \"./wallet-flow\";\n","/** Identity-owned prepaid virtual cards (`canonical-spec.md §45`). */\n\nimport { z } from \"zod\";\nimport { Metadata, MicroUsdField, Timestamp, idOf } from \"./common\";\n\nexport const CARD_STATUSES = [\"pending_payment\", \"issuing\", \"active\", \"failed\", \"cancelled\", \"refunded\"] as const;\nexport const CardStatusSchema = z.enum(CARD_STATUSES);\nexport type CardStatus = z.infer<typeof CardStatusSchema>;\n\n/** The prepaid product's floor and the hard ceiling; the live bounds come from `card_quote`. */\nexport const CARD_MIN_LOAD_MICRO_USD = 1_000_000;\nexport const CARD_MAX_LOAD_MICRO_USD = 150_000_000;\n/**\n * A load is priced to the issuer as a decimal amount of dollars, so it has to land on a whole\n * cent: 21_000_009 µUSD would be ordered as `21.000009` and the row would then overstate the card\n * by the remainder for the rest of its life.\n */\nexport const CARD_LOAD_GRANULARITY_MICRO_USD = 10_000;\n\n/** `GET …/transactions?limit=`: the legacy defaults, kept. */\nexport const CARD_TRANSACTIONS_DEFAULT_LIMIT = 50;\nexport const CARD_TRANSACTIONS_MAX_LIMIT = 200;\n\nexport const CardSchema = z.object({\n id: idOf(\"vcd\"),\n object: z.literal(\"card\"),\n identity_id: idOf(\"idn\"),\n kind: z.literal(\"prepaid\"),\n status: CardStatusSchema,\n label: z.string().min(1).max(128),\n brand: z.string().nullable(),\n last4: z.string().regex(/^\\d{4}$/).nullable(),\n load_micro_usd: MicroUsdField,\n spent_micro_usd: MicroUsdField,\n currency: z.literal(\"usd\"),\n expires_at: Timestamp.nullable(),\n failure_reason: z.string().max(256).nullable(),\n created_at: Timestamp,\n updated_at: Timestamp,\n});\nexport type Card = z.infer<typeof CardSchema>;\n\nexport const IssueCardSchema = z.object({\n label: CardSchema.shape.label,\n load_micro_usd: MicroUsdField.min(CARD_MIN_LOAD_MICRO_USD)\n .max(CARD_MAX_LOAD_MICRO_USD)\n .multipleOf(CARD_LOAD_GRANULARITY_MICRO_USD),\n});\nexport type IssueCard = z.infer<typeof IssueCardSchema>;\n\nexport const CardQuoteRequestSchema = IssueCardSchema.pick({ load_micro_usd: true });\n\nexport const CardQuoteSchema = z.object({\n object: z.literal(\"card_quote\"),\n load_micro_usd: MicroUsdField,\n price_micro_usd: MicroUsdField,\n brand: z.string().nullable(),\n min_load_micro_usd: MicroUsdField,\n max_load_micro_usd: MicroUsdField,\n});\nexport type CardQuote = z.infer<typeof CardQuoteSchema>;\n\n/** The one shape that ever carries a secret; answered by one route, never cached, never stored in a row type. */\nexport const CardCredentialsSchema = z.object({\n object: z.literal(\"card_credentials\"),\n card_id: idOf(\"vcd\"),\n number: z.string().min(1),\n pin: z.string().nullable(),\n cvv: z.string().nullable(),\n expiry: z.string().nullable(),\n url: z.url().nullable(),\n instructions: z.string().nullable(),\n revealed_at: Timestamp,\n});\nexport type CardCredentials = z.infer<typeof CardCredentialsSchema>;\n\nexport const CardTransactionSchema = z.object({\n id: idOf(\"vct\"),\n object: z.literal(\"card_transaction\"),\n card_id: idOf(\"vcd\"),\n amount_micro_usd: MicroUsdField,\n merchant: z.string().nullable(),\n description: z.string().nullable(),\n session_id: idOf(\"ses\").nullable(),\n metadata: Metadata,\n created_at: Timestamp,\n});\nexport type CardTransaction = z.infer<typeof CardTransactionSchema>;\n\nexport const LogCardTransactionSchema = z.object({\n amount_micro_usd: MicroUsdField.positive(),\n merchant: z.string().max(256).optional(),\n description: z.string().max(1024).optional(),\n metadata: Metadata.optional(),\n});\nexport type LogCardTransaction = z.infer<typeof LogCardTransactionSchema>;\n\nexport const ListCardsSchema = z.object({ status: CardStatusSchema.optional() });\n\n/**\n * The stored card: the wire object plus the server columns no projection returns — what was paid,\n * the ledger key that paid it, and the issuer's references. Routes and tools both hold one and hand\n * out `wireCard(record)`, never the record.\n */\nexport interface CardRecord extends Card {\n price_micro_usd: number;\n ledger_entry_id: string | null;\n provider_product_ref: string | null;\n provider_order_ref: string | null;\n idempotency_key: string | null;\n}\n\nexport function wireCard(record: CardRecord): Card {\n const {\n price_micro_usd: _price,\n ledger_entry_id: _ledger,\n provider_product_ref: _product,\n provider_order_ref: _order,\n idempotency_key: _key,\n ...card\n } = record;\n return card;\n}\n","/**\n * The proxy call trace (`canonical-spec §26.5`, ADR-0745, migration 0077) — what a call to\n * `/v1/proxy/*` actually said, beside the ledger debit that says what it cost.\n *\n * A hosted agent turn leaves a transcript. A proxy call left exactly one row in the whole schema:\n * its `ledger_entry` debit. This object is the other half — the same call's prompt, reply, routing\n * and upstream attribution. Since ADR-0762 it also records every hosted-harness model call\n * (`source: \"harness\"`), literally and joinably to its session and event `seq`, and keeps it:\n * `expires_at` is null on new rows and the bodies are inline (`content_scope: full`, ADR-0794).\n *\n * `id` IS THE JOIN. It is the request id the proxy already uses three ways — `x-request-id`, the\n * reply's message id, and the ledger entry's `idempotency_key` — so a trace and its debit need no\n * correlation column to find each other.\n */\nimport { z } from \"zod\";\nimport { MicroUsdField, PrincipalSchema, Timestamp, TokenUsageSchema, WindowSchema, idOf } from \"./common\";\n\n/**\n * Which door the call came in by. `anthropic` / `openai` are the two public proxy envelopes; `native`\n * is a hosted harness's own call through `ChatTransport`, which has no public envelope (ADR-0762).\n */\nexport const ProxyDialectSchema = z.enum([\"anthropic\", \"openai\", \"native\"]);\nexport type ProxyDialect = z.infer<typeof ProxyDialectSchema>;\n\n/**\n * Where a trace row's bodies are, written onto the row itself (ADR-0762, superseding ADR-0745's\n * configurable scope — capture is always full now).\n *\n * `full` — the bodies are inline on the row, in Postgres: every new row (ADR-0794 — records in\n * Postgres, files in object storage). `object` was ADR-0762's object-storage form, never shipped to\n * production and no longer written or read back; `metadata` survives only on rows from before\n * ADR-0762. Both remain in the enum so an old row still parses.\n */\nexport const ProxyTraceContentScopeSchema = z.enum([\"full\", \"metadata\", \"object\"]);\nexport type ProxyTraceContentScope = z.infer<typeof ProxyTraceContentScopeSchema>;\n\n/** A tool call as the model made it: its id is what the tool's own events join on. */\nconst TraceToolCall = z.object({ id: z.string().optional(), name: z.string(), arguments: z.string() });\n\n/**\n * One prompt as the transport saw it: the vendor-neutral `ChatMessage` shape, never a dialect's\n * envelope, and LITERAL since ADR-0762 — assistant `tool_calls` with their ids, `tool_call_id` on a\n * tool result, image links on a user turn, the full tool schema array, the output allowance. Rows\n * from before ADR-0762 carry `{role, content}` messages and `tool_names` only.\n */\nexport const ProxyTraceRequestSchema = z.object({\n model: z.string().optional(),\n window: WindowSchema.optional(),\n system: z.string(),\n messages: z.array(\n z.looseObject({\n role: z.string(),\n content: z.string(),\n tool_calls: z.array(z.looseObject({ id: z.string(), name: z.string() })).optional(),\n tool_call_id: z.string().optional(),\n }),\n ),\n tools: z\n .array(z.object({ name: z.string(), description: z.string(), parameters: z.record(z.string(), z.unknown()) }))\n .optional(),\n tool_schema_hash: z.string().optional(),\n max_output_tokens: z.number().int().optional(),\n tool_names: z.array(z.string()).optional(),\n});\n\n/**\n * One reply as it was assembled from the stream, whichever dialect it was then rendered into —\n * including the model's reasoning and any provider `reasoning_details` blocks, verbatim (ADR-0793).\n */\nexport const ProxyTraceResponseSchema = z.object({\n text: z.string(),\n reasoning: z.string().optional(),\n reasoning_details: z.array(z.unknown()).optional(),\n tool_calls: z.array(TraceToolCall),\n /** A call that threw, was abandoned or never completed (ADR-0794): the reply is what streamed before. */\n is_error: z.literal(true).optional(),\n /** The error's class name — never its message — or `incomplete` for a stream that just stopped. */\n error_class: z.string().optional(),\n partial: z.literal(true).optional(),\n});\n\n/**\n * Lowercase hex sha-256 of the stored body — present on every row. Since ADR-0762 nothing is\n * truncated, so it is the hash of the whole body: the request with its tool array replaced by\n * `tool_schema_hash`, and the reply. It is also the body's object-storage key.\n */\nconst Sha256 = z.string().regex(/^[0-9a-f]{64}$/);\n\nexport const ProxyCallTraceSchema = z.object({\n /** The request id: also `x-request-id`, the reply's `id`, and the ledger entry's idempotency key. */\n id: idOf(\"req\"),\n object: z.literal(\"proxy_call_trace\"),\n dialect: ProxyDialectSchema,\n /** The principal that made the call (§17). An API key here is the answer to \"who sent this\". */\n actor: PrincipalSchema,\n /** The public model id the caller asked for. */\n model: z.string(),\n window: WindowSchema,\n /** The model the reply said served it — where `vetta/auto` resolves — or null if it named none. */\n resolved_model: z.string().nullable(),\n /**\n * The serving provider and the gateway's own generation id. Null on every row written before the\n * adapter stops dropping them (Track A); together they are what lets an upstream invoice line be\n * matched back to an organization, a key and a ledger entry.\n */\n provider: z.string().nullable(),\n generation_id: z.string().nullable(),\n stop: z.enum([\"end_turn\", \"tool_use\", \"length\"]).nullable(),\n usage: TokenUsageSchema,\n /** What the customer was charged, µUSD. The ledger entry is the authority; this is its copy. */\n billed_micro_usd: MicroUsdField.nullable(),\n /** What the vendor said it cost, µUSD. A CROSS-CHECK, NEVER A DEBIT. */\n vendor_cost_micro_usd: MicroUsdField.nullable(),\n duration_ms: z.number().int().nonnegative().nullable(),\n content_scope: ProxyTraceContentScopeSchema,\n /** `proxy` — a `/v1/proxy/*` call; `harness` — a hosted harness's own model call (ADR-0762). */\n source: z.enum([\"proxy\", \"harness\"]),\n /** The session the call belongs to: a harness call's, or a sandbox token's `sub` on the proxy. */\n session_id: z.string().nullable(),\n /**\n * The `seq` of the call's `span.model_request.end` event — or of its `.start` when the call failed\n * or its `.end` was withheld (ADR-0794). Null on the proxy, which writes no event.\n */\n seq: z.number().int().nullable(),\n /** The board card the session was woken for (`session.metadata.board.card_id`), or null. */\n board_card_id: z.string().nullable(),\n /** The ids of the tool calls this reply made — the join to the `tool.*` events they caused. */\n tool_call_ids: z.array(z.string()),\n /** sha-256 of the canonical JSON of the tool schema array the model was offered, or null. */\n tool_schema_hash: Sha256.nullable(),\n request_sha256: Sha256,\n response_sha256: Sha256,\n /** The UTF-8 size of each stored body. */\n request_bytes: z.number().int().nonnegative(),\n response_bytes: z.number().int().nonnegative(),\n /** Inline in `full` scope — every new row. Null on a legacy `metadata` or `object` row. */\n request: ProxyTraceRequestSchema.nullable(),\n response: ProxyTraceResponseSchema.nullable(),\n /** Always false since ADR-0762 (nothing is cut); true only on rows from before it. */\n truncated: z.boolean(),\n created_at: Timestamp,\n /** When the reaper deletes this row. Null since ADR-0762: model I/O is kept, not expired. */\n expires_at: Timestamp.nullable(),\n});\nexport type ProxyCallTrace = z.infer<typeof ProxyCallTraceSchema>;\n","/**\n * A review (`canonical-spec §47`, ADR-0796, migration 0083) — a person's verdict on agent work given\n * outside Vetta's approval box: a post rejected in an app's queue, a caption edited before it ships.\n * The approval box's own decisions are `tool.confirm.resolved` events (ADR-0764); this is the same\n * judgement from everywhere else, joined to the session and board card by the files it names.\n */\nimport { z } from \"zod\";\nimport { idOf } from \"./common\";\n\nexport const ReviewDecisionSchema = z.enum([\"approve\", \"reject\", \"edit\"]);\nexport type ReviewDecision = z.infer<typeof ReviewDecisionSchema>;\n\n/** A reviewed field set (`{caption, title}` for a post); free-form, bounded. */\nconst Fields = z.record(z.string().max(100), z.unknown()).nullable().optional();\n\n/** `POST /v1/reviews`. The actor is the calling principal and is never part of the body. */\nexport const CreateReviewSchema = z.object({\n decision: ReviewDecisionSchema,\n reason: z.string().max(4_000).nullable().optional(),\n file_ids: z.array(idOf(\"fil\")).max(50).optional(),\n session_id: idOf(\"ses\").optional(),\n subject: z.record(z.string().max(100), z.unknown()).optional(),\n before: Fields,\n after: Fields,\n});\nexport type CreateReview = z.infer<typeof CreateReviewSchema>;\n\n/** What `POST /v1/reviews` answers: the review and what it was linked to. */\nexport interface ReviewCreated {\n id: string;\n object: \"review\";\n session_id: string | null;\n board_card_id: string | null;\n}\n","/** Paid advertising managed through an identity-owned connected account (§51). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField } from \"./common\";\n\nexport const AdProviderSchema = z.enum([\"google\"]);\nexport type AdProvider = z.infer<typeof AdProviderSchema>;\n\nexport const AdCampaignStatusSchema = z.enum([\"enabled\", \"paused\", \"removed\", \"unknown\"]);\nexport type AdCampaignStatus = z.infer<typeof AdCampaignStatusSchema>;\n\nexport const AdCampaignSchema = z.object({\n id: z.string().min(1),\n object: z.literal(\"ad_campaign\"),\n provider: AdProviderSchema,\n connection_id: z.string().min(1),\n customer_id: z.string().regex(/^\\d{10}$/),\n resource_name: z.string().min(1),\n name: z.string().min(1),\n type: z.literal(\"search\"),\n status: AdCampaignStatusSchema,\n /** Null for provider campaigns with no ad; list and status reads are campaign-based. */\n final_url: z.url().nullable(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n start_date: z.iso.date(),\n end_date: z.iso.date(),\n});\nexport type AdCampaign = z.infer<typeof AdCampaignSchema>;\n\nexport const AdCampaignInsightsSchema = z.object({\n object: z.literal(\"ad_campaign_insights\"),\n provider: AdProviderSchema,\n campaign_id: z.string().min(1),\n impressions: z.number().int().nonnegative(),\n clicks: z.number().int().nonnegative(),\n conversions: z.number().nonnegative(),\n spend_micro_usd: MicroUsdField.nonnegative(),\n});\nexport type AdCampaignInsights = z.infer<typeof AdCampaignInsightsSchema>;\n","/**\n * The dashboard's short-lived bearer credential (`canonical-spec.md §20`). It is **signed, not\n * stored**: an HMAC over a JSON payload, so a login writes no row, a logout needs no revocation\n * table, and the credential cannot outlive its `exp`.\n *\n * It is presented in `Authorization: Bearer` exactly like an API key, and like an API key it is a\n * server-side secret — the dashboard keeps it in an httpOnly session and never sends it to a\n * browser (ADR-0017).\n */\nimport { VettaError } from \"./errors\";\nimport { SCOPES, type Role, type Scope } from \"./schema/index\";\n\n/** `test` or `live` — the tier a credential spends in. Mirrors the column `api_key.mode`. */\nexport type KeyMode = \"test\" | \"live\";\n\nexport const SESSION_TOKEN_PREFIX = \"vt_\";\n/** Thirty days. The dashboard has no refresh credential, so this is also its absolute sign-in. */\nexport const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;\n\nexport interface SessionClaims {\n /** The `usr_` member id in `org`, or the provider subject when the person has no membership. */\n sub: string;\n email: string;\n /** `null` until the person picks or creates an organization (`canonical-spec.md §20.4`). */\n org: string | null;\n /** The member's role in `org`, and what `scopes` was derived from. `null` when `org` is. */\n role: Role | null;\n mode: KeyMode;\n /** Derived from `role`, never chosen by the caller (`canonical-spec.md §20.4`). */\n scopes: Scope[];\n /** Epoch seconds. */\n exp: number;\n /**\n * MINTED FOR A SANDBOX, NOT FOR A PERSON. A class-B harness runs as a process inside a customer's\n * micro-VM and needs a credential to reach our metered model door; this marks that token so\n * `authenticate` gives it a `system` principal instead of inventing a `usr_` that names a `ses_`.\n *\n * It is deliberately a claim rather than an inference from `scopes`: the day a person's token\n * happens to carry one scope, an inference would silently reclassify them.\n */\n sandbox?: boolean;\n /**\n * MINTED FOR ONE AGENT'S TURN: the `agt_` id whose platform tools this token opens\n * (`apps/runtime-do/src/platform-tools.ts`). Like `sandbox`, it names a subsystem, never a person,\n * and it reaches only the routes marked `agent: true` (`apps/api/src/router.ts`). That list is the\n * boundary. `scopes` only has to cover it.\n */\n agent?: string;\n /**\n * MINTED FOR THE CEO'S TURN, NOT FOR A PERSON (ADR-1100): the `agt_` id of the agent the\n * control-plane credential is bound to (ADR-1097). Like `sandbox`, it names a subsystem, so the\n * token files as `system:agent:<id>` and is never `ctx.user`. Its `scopes` are the least of what\n * every person who drove the session holds, within `ORCHESTRATOR_SCOPES`, derived by the runtime\n * when it mints (`apps/runtime-do/src/drivers.ts`).\n */\n orchestrator?: string;\n}\n\n/**\n * The scopes an agent's platform token carries: enough for every route marked `agent: true`, and\n * the API's test checks they still are. They do not limit the token. The route list does, because\n * `agents:read` alone would open every persona's inbox (ADR-1096).\n */\nexport const AGENT_TOKEN_SCOPES: Scope[] = [\"billing:read\", \"agents:read\"];\n\n/**\n * Role → scopes (`canonical-spec.md §20.4`). A plain member gets everything except the three that\n * can spend money, mint credentials or redirect the org's outbound traffic; `admin` implies the\n * rest, so an owner needs the one entry. Derived here and never taken from the caller. Here rather\n * than in `apps/api` because the runtime derives the CEO's turn from it too.\n */\nconst MEMBER_DENIED: Scope[] = [\"admin\", \"billing:write\", \"webhooks:*\"];\n\nexport function scopesForRole(role: Role): Scope[] {\n if (role === \"owner\" || role === \"admin\") return [\"admin\"];\n return SCOPES.filter((scope) => !MEMBER_DENIED.includes(scope));\n}\n\n/**\n * The most the CEO's turn may hold (ADR-0190): everything a person can drive, minus `admin`, which\n * would let it mint keys and seal credentials — the two that turn a prompt injection into a\n * standing one. A turn holds less when the people driving it do (ADR-1100).\n */\nexport const ORCHESTRATOR_SCOPES: readonly Scope[] = [\n \"agents:read\",\n \"agents:write\",\n \"sessions:read\",\n \"sessions:write\",\n \"computers:write\",\n \"files:read\",\n \"files:write\",\n \"billing:read\",\n \"billing:write\",\n \"webhooks:*\",\n \"audit:read\",\n];\n\nconst encoder = new TextEncoder();\n\nfunction b64url(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...bytes)).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nfunction unb64url(text: string): Uint8Array {\n const padded = text.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const binary = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n}\n\nasync function sign(secret: string, payload: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return b64url(new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(payload))));\n}\n\n/** Length-checked before the byte compare, so a wrong-length signature cannot be timed (§14). */\nfunction equalsConstantTime(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let difference = 0;\n for (let index = 0; index < a.length; index += 1) difference |= a.charCodeAt(index) ^ b.charCodeAt(index);\n return difference === 0;\n}\n\nexport async function mintSessionToken(secret: string, claims: SessionClaims): Promise<string> {\n const payload = b64url(encoder.encode(JSON.stringify(claims)));\n return `${SESSION_TOKEN_PREFIX}${payload}.${await sign(secret, payload)}`;\n}\n\n/** Bad signature, bad shape and expiry are one answer: `unauthorized`, naming no internal detail. */\nexport async function readSessionToken(\n secret: string | null,\n token: string,\n nowSeconds: number,\n): Promise<SessionClaims> {\n if (secret === null || secret === \"\") {\n throw new VettaError(\"feature_not_configured\", \"dashboard sign-in is not configured\");\n }\n const [payload, signature] = token.slice(SESSION_TOKEN_PREFIX.length).split(\".\");\n if (!payload || !signature) throw new VettaError(\"unauthorized\", \"invalid session token\");\n if (!equalsConstantTime(await sign(secret, payload), signature)) {\n throw new VettaError(\"unauthorized\", \"invalid session token\");\n }\n const claims = JSON.parse(new TextDecoder().decode(unb64url(payload))) as SessionClaims;\n if (typeof claims.exp !== \"number\" || claims.exp <= nowSeconds) {\n throw new VettaError(\"unauthorized\", \"this sign-in has expired; sign in again\");\n }\n // One token speaks for one kind of caller: a box, an agent's turn, the CEO's turn, or a person.\n const named = (claim: unknown): boolean => claim !== undefined;\n const kinds = [claims.sandbox === true, named(claims.agent), named(claims.orchestrator)].filter(Boolean).length;\n const blank = [claims.agent, claims.orchestrator].some((claim) => named(claim) && (typeof claim !== \"string\" || claim === \"\"));\n if (kinds > 1 || blank) throw new VettaError(\"unauthorized\", \"invalid session token\");\n return claims;\n}\n","/**\n * The company's logo, as the SVG a person or an agent wrote (`canonical-spec §20.7`, ADR-1085).\n * `checkLogoSvg` is the only gate: the API's `PATCH /v1/organizations/{id}` and the agent's\n * `company.set_logo` both call it, and store what it answers.\n *\n * An allow-list read by a small tokenizer, not a DOM (a Worker has none) and not a deny-list: every\n * byte must be an allowed element, an allowed attribute with a quoted value of plain characters,\n * whitespace, or words inside `<title>`/`<desc>`. Anything the tokenizer cannot account for is\n * refused, with a sentence the writer can act on.\n */\n\nconst MAX_BYTES = 16 * 1024;\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nconst ELEMENTS = new Set([\n \"svg\", \"g\", \"path\", \"rect\", \"circle\", \"ellipse\", \"line\", \"polyline\", \"polygon\", \"defs\",\n \"linearGradient\", \"radialGradient\", \"stop\", \"title\", \"desc\", \"clipPath\", \"mask\",\n]);\n\nconst ATTRIBUTES = new Set([\n \"viewBox\", \"xmlns\", \"width\", \"height\", \"x\", \"y\", \"x1\", \"y1\", \"x2\", \"y2\", \"cx\", \"cy\", \"r\", \"rx\",\n \"ry\", \"d\", \"points\", \"fill\", \"stroke\", \"stroke-width\", \"stroke-linecap\", \"stroke-linejoin\",\n \"stroke-miterlimit\", \"stroke-dasharray\", \"opacity\", \"fill-opacity\", \"stroke-opacity\", \"fill-rule\",\n \"clip-rule\", \"transform\", \"offset\", \"stop-color\", \"stop-opacity\", \"gradientUnits\",\n \"gradientTransform\", \"id\", \"clip-path\", \"mask\", \"preserveAspectRatio\", \"fx\", \"fy\", \"spreadMethod\",\n \"role\", \"aria-hidden\",\n]);\n\n/** Elements that hold words and nothing else. */\nconst WORDS = new Set([\"title\", \"desc\"]);\n\nconst HINTS: Record<string, string> = {\n text: \"draw the letters as paths\",\n tspan: \"draw the letters as paths\",\n textPath: \"draw the letters as paths\",\n image: \"draw it with shapes; a logo embeds no image\",\n foreignObject: \"draw it with shapes\",\n script: \"a logo runs no code\",\n style: \"set fill and stroke as attributes on each shape\",\n use: \"draw the shape again where it repeats\",\n a: \"a logo links nowhere\",\n};\n\nconst OPEN = /<([A-Za-z][\\w:.-]*)/y;\nconst CLOSE = /<\\/([A-Za-z][\\w:.-]*)[ \\t\\r\\n]*>/y;\nconst ATTRIBUTE = /[ \\t\\r\\n]+([A-Za-z_:][\\w:.-]*)[ \\t\\r\\n]*=[ \\t\\r\\n]*(?:\"([^\"]*)\"|'([^']*)')/y;\n/** Characters XML refuses, or Postgres `text` does (NUL). Matching them is the point. */\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/;\nconst TAG_END = /[ \\t\\r\\n]*(\\/?)>/y;\nconst LOCAL_URL = /url\\(#[A-Za-z_][\\w.-]*\\)/g;\nconst VALUE_CHARS = /^[\\w \\t\\r\\n#.,%()+-]*$/;\nconst VIEW_BOX = /^\\s*-?[\\d.]+(?:[\\s,]+-?[\\d.]+){3}\\s*$/;\n/** A checked root's start tag: no value holds `>` or `=`, so this reads only its own attributes. */\nconst ROOT_NS = /^<svg[^>]*\\sxmlns\\s*=/;\n\nexport type LogoCheck = { ok: true; svg: string } | { ok: false; reason: string };\n\n/**\n * An `<svg>` with `xmlns` on its root. The studio draws a logo as an `<img>` of a data URL, and a\n * browser draws an SVG without its namespace there as nothing. The web calls it too, on a logo an\n * agent proposes, before any check has run.\n */\nexport function withSvgNamespace(input: string): string {\n const svg = input.trim();\n return !/^<svg[\\s>]/.test(svg) || ROOT_NS.test(svg) ? svg : `<svg xmlns=\"${SVG_NS}\"${svg.slice(\"<svg\".length)}`;\n}\n\n/** The answer always carries `xmlns` on its root (`withSvgNamespace`). */\nexport function checkLogoSvg(input: string): LogoCheck {\n const svg = input.trim();\n const reason = firstProblem(svg);\n if (reason !== undefined) return { ok: false, reason };\n return { ok: true, svg: withSvgNamespace(svg) };\n}\n\nfunction firstProblem(svg: string): string | undefined {\n if (new TextEncoder().encode(svg).length > MAX_BYTES) {\n return `the logo is over 16 KB: simplify it — fewer points, shorter paths`;\n }\n // XML's own whitespace only, in tags and between them: a no-break space reads as a separator to a\n // regex and as an error to a browser, and a NUL is refused by the database.\n if (CONTROL.test(svg)) return \"control characters are not allowed: remove them\";\n if (!svg.startsWith(\"<svg\")) return `the logo must be one <svg viewBox=\"…\">…</svg> element, with nothing around it`;\n const open: string[] = [];\n let at = 0;\n let closed = false;\n while (at < svg.length) {\n const lt = svg.indexOf(\"<\", at);\n const text = svg.slice(at, lt === -1 ? svg.length : lt);\n const problem = textProblem(text, open.at(-1));\n if (problem) return problem;\n if (lt === -1) break;\n if (closed) return \"nothing may follow the closing </svg>\";\n const special = declaration(svg, lt);\n if (special) return special;\n CLOSE.lastIndex = lt;\n const close = CLOSE.exec(svg);\n if (close) {\n const name = close[1] ?? \"\";\n const expected = open.pop();\n if (expected !== name) return expected ? `</${name}> closes <${expected}>: close it with </${expected}>` : `</${name}> closes nothing`;\n closed = open.length === 0;\n at = CLOSE.lastIndex;\n continue;\n }\n const tag = readElement(svg, lt, open);\n if (typeof tag === \"string\") return tag;\n if (!tag.selfClosing) open.push(tag.name);\n at = tag.end;\n }\n return open.length > 0 ? `<${open.at(-1)}> is never closed` : undefined;\n}\n\nfunction textProblem(text: string, parent: string | undefined): string | undefined {\n if (text.includes(\"&\")) return \"entities (&…;) are not allowed: write the character itself, or leave it out\";\n if (text.trim() !== \"\" && !(parent !== undefined && WORDS.has(parent))) {\n return \"words outside <title> or <desc> are not allowed: draw letters as paths\";\n }\n return undefined;\n}\n\nfunction declaration(svg: string, lt: number): string | undefined {\n if (svg.startsWith(\"<!--\", lt)) return \"comments are not allowed: remove them\";\n if (svg.startsWith(\"<![CDATA[\", lt)) return \"CDATA is not allowed: remove it\";\n if (svg.startsWith(\"<!\", lt)) return \"a DOCTYPE or entity declaration is not allowed: remove it\";\n if (svg.startsWith(\"<?\", lt)) return \"processing instructions (<?…?>) are not allowed: remove them\";\n return undefined;\n}\n\n/** One start tag at `lt`: its name, whether it closes itself, and where it ends — or why it is refused. */\nfunction readElement(svg: string, lt: number, open: string[]): { name: string; selfClosing: boolean; end: number } | string {\n OPEN.lastIndex = lt;\n const name = OPEN.exec(svg)?.[1];\n if (name === undefined) return \"a `<` must start an element: write shapes, not markup fragments\";\n const refused = elementProblem(name, open);\n if (refused) return refused;\n const attributes = new Map<string, string>();\n let at = OPEN.lastIndex;\n for (;;) {\n TAG_END.lastIndex = at;\n const end = TAG_END.exec(svg);\n if (end) {\n const selfClosing = end[1] === \"/\";\n const root = name === \"svg\" ? rootProblem(attributes, selfClosing) : undefined;\n return root ?? { name, selfClosing, end: TAG_END.lastIndex };\n }\n ATTRIBUTE.lastIndex = at;\n const attribute = ATTRIBUTE.exec(svg);\n if (!attribute) return `<${name}>'s attributes must each be name=\"value\", quoted, separated by spaces`;\n const [, key = \"\", double, single] = attribute;\n const value = double ?? single ?? \"\";\n if (attributes.has(key)) return `\\`${key}\\` is set twice on <${name}>: keep one`;\n const problem = attributeProblem(name, key, value);\n if (problem) return problem;\n attributes.set(key, value);\n at = ATTRIBUTE.lastIndex;\n }\n}\n\nfunction elementProblem(name: string, open: string[]): string | undefined {\n const parent = open.at(-1);\n if (parent === undefined && name !== \"svg\") return `the logo must be one <svg> element, not <${name}>`;\n if (parent !== undefined && name === \"svg\") return \"one <svg> only: group shapes with <g>, not a nested <svg>\";\n if (parent !== undefined && WORDS.has(parent)) return `<${parent}> holds words only, not <${name}>`;\n if (ELEMENTS.has(name)) return undefined;\n const hint = HINTS[name] ?? (name.startsWith(\"animate\") || name === \"set\" ? \"a logo holds still\" : undefined);\n if (hint) return `<${name}> is not allowed: ${hint}`;\n const lower = [...ELEMENTS].find((allowed) => allowed.toLowerCase() === name.toLowerCase());\n if (lower) return `<${name}> must be written <${lower}>`;\n return `<${name}> is not allowed: use only ${[...ELEMENTS].map((element) => `<${element}>`).join(\", \")}`;\n}\n\nfunction attributeProblem(element: string, name: string, value: string): string | undefined {\n if (/^on/i.test(name)) return `\\`${name}\\` is not allowed: a logo runs no code`;\n if (/href$/i.test(name)) return `\\`${name}\\` is not allowed: a logo links to nothing; draw the shape where it is used`;\n if (name === \"style\") return \"`style` is not allowed: set fill, stroke and opacity as attributes\";\n if (name === \"class\") return \"`class` is not allowed: set fill and stroke as attributes on each shape\";\n if (!ATTRIBUTES.has(name)) return `\\`${name}\\` is not allowed on <${element}>: drop it (presentation and geometry attributes only)`;\n if (name === \"xmlns\") return value === SVG_NS ? undefined : `xmlns must be \"${SVG_NS}\" or left out`;\n const lower = value.toLowerCase();\n if (lower.includes(\"javascript:\")) return `\\`${name}\\` holds a script: a logo runs no code`;\n if (lower.includes(\"data:\")) return `\\`${name}\\` embeds data: draw it with shapes instead`;\n if (lower.includes(\"http\")) return `\\`${name}\\` points to the web: a logo loads nothing`;\n if (value.includes(\"&\")) return `\\`${name}\\` holds an entity (&…;): write the character itself`;\n if (value.includes(\"<\")) return `\\`${name}\\` holds a \\`<\\`: values are numbers, colours and names`;\n if (lower.replace(LOCAL_URL, \"\").includes(\"url(\")) return `\\`${name}\\` may reference only url(#id), written exactly so`;\n if (!VALUE_CHARS.test(value)) return `\\`${name}\\` holds a character a logo does not need: use numbers, names, #colours and url(#id)`;\n return undefined;\n}\n\nfunction rootProblem(attributes: Map<string, string>, selfClosing: boolean): string | undefined {\n const viewBox = attributes.get(\"viewBox\");\n if (viewBox === undefined) return `the <svg> needs a viewBox, such as viewBox=\"0 0 64 64\"`;\n if (!VIEW_BOX.test(viewBox)) return `viewBox must be four numbers, such as \"0 0 64 64\"`;\n if (selfClosing) return \"the <svg> is empty: draw the mark inside it\";\n return undefined;\n}\n","import { z } from \"zod\";\nimport { BRAND_TYPEFACES, BrandKitSchema, type BrandKit } from \"./schema/org\";\n\n/**\n * THE COMPANY'S BRAND KIT, DRAWN IN CODE (ADR-1163). One colour chooses it: the palette is built\n * around that colour — a dark, the colour itself, a tint, a paper and an accent — in one of a few\n * harmonies. The CEO names the colour (`company.set_brand`); the code draws the swatches, so a kit\n * always reads, whatever the model would have picked. The same colour and harmony, the same kit.\n */\n\n/** Where the accent sits from the colour, one harmony per shuffle. */\nconst HARMONIES = [165, 40, 120, 200] as const;\nexport const BRAND_HARMONIES = HARMONIES.length;\n\ntype Rgb = [number, number, number];\n\nconst hexToRgb = (hex: string): Rgb => {\n const full = hex.length === 4 ? `#${[...hex.slice(1)].map((c) => c + c).join(\"\")}` : hex;\n return [0, 2, 4].map((at) => parseInt(full.slice(1 + at, 3 + at), 16)) as Rgb;\n};\n\nconst hueOf = ([r, g, b]: Rgb): number => {\n const [rn, gn, bn] = [r / 255, g / 255, b / 255];\n const max = Math.max(rn, gn, bn);\n const d = max - Math.min(rn, gn, bn);\n if (d === 0) return 0;\n const h = max === rn ? (gn - bn) / d + (gn < bn ? 6 : 0) : max === gn ? (bn - rn) / d + 2 : (rn - gn) / d + 4;\n return Math.round(h * 60);\n};\n\nconst hslToHex = (h: number, s: number, l: number): string => {\n const sn = s / 100;\n const ln = l / 100;\n const k = (n: number) => (n + h / 30) % 12;\n const a = sn * Math.min(ln, 1 - ln);\n const f = (n: number) => ln - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));\n return `#${[0, 8, 4].map((n) => Math.round(f(n) * 255).toString(16).padStart(2, \"0\")).join(\"\")}`;\n};\n\n/** Names a person would use for a swatch; the nearest one names it. */\nconst NAMES: [string, string][] = [\n [\"Midnight\", \"#191970\"], [\"Ink\", \"#1b1f3b\"], [\"Espresso\", \"#3b2a24\"], [\"Forest\", \"#1f3d2b\"], [\"Aubergine\", \"#3b1f35\"],\n [\"Navy\", \"#1b2a4a\"], [\"Charcoal\", \"#2b2b2b\"], [\"Oxblood\", \"#4a1c1c\"], [\"Deep Teal\", \"#0f3b3b\"], [\"Plum\", \"#4b2342\"],\n [\"Tomato\", \"#e5533d\"], [\"Tangerine\", \"#f28c28\"], [\"Marigold\", \"#f2b705\"], [\"Lemon\", \"#f7e04b\"], [\"Lime\", \"#a3d93b\"],\n [\"Emerald\", \"#1faa6b\"], [\"Jade\", \"#1fa39a\"], [\"Teal\", \"#1b9aaa\"], [\"Azure\", \"#2d8cf0\"], [\"Cobalt\", \"#2f5bea\"],\n [\"Ultramarine\", \"#3f3fd6\"], [\"Iris\", \"#6b5bea\"], [\"Violet\", \"#8b5cf6\"], [\"Orchid\", \"#c05bd6\"], [\"Magenta\", \"#d63fa0\"],\n [\"Rose\", \"#e5487a\"], [\"Coral\", \"#f07260\"], [\"Terracotta\", \"#c8623f\"], [\"Ochre\", \"#c89b3c\"], [\"Olive\", \"#8a8f3c\"],\n [\"Moss\", \"#6b8f4e\"], [\"Periwinkle\", \"#c5c9ff\"], [\"Lavender\", \"#dcd0ff\"], [\"Blush\", \"#ffd6de\"], [\"Peach\", \"#ffd9bf\"],\n [\"Butter\", \"#fff1b8\"], [\"Pistachio\", \"#d6f5a8\"], [\"Mint\", \"#c9f2dc\"], [\"Seafoam\", \"#c2efe8\"], [\"Sky\", \"#cde8ff\"],\n [\"Lilac\", \"#eed2f7\"], [\"Linen\", \"#f5f0e8\"], [\"Ivory\", \"#fbf8ef\"], [\"Porcelain\", \"#f3f5f7\"], [\"Bone\", \"#eee9df\"],\n [\"Mist\", \"#eef2f7\"], [\"Sand\", \"#efe6d8\"],\n];\n\n/** The nearest name not already taken, by a weighted distance the eye roughly agrees with. */\nfunction nameOf(hex: string, taken: Set<string>): string {\n const [r, g, b] = hexToRgb(hex);\n const distance = ([nr, ng, nb]: Rgb) => 2 * (r - nr) ** 2 + 4 * (g - ng) ** 2 + 3 * (b - nb) ** 2;\n const ranked = NAMES.map(([name, at]) => ({ name, d: distance(hexToRgb(at)) })).sort((a, b) => a.d - b.d);\n const name = (ranked.find((one) => !taken.has(one.name)) ?? ranked[0]!).name;\n taken.add(name);\n return name;\n}\n\n/** Black or white, whichever reads on `hex`. */\nexport function inkOn(hex: string): \"#ffffff\" | \"#111111\" {\n const [r, g, b] = hexToRgb(hex).map((c) => {\n const v = c / 255;\n return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n }) as Rgb;\n return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.4 ? \"#111111\" : \"#ffffff\";\n}\n\n/** The five swatches, darkest first: the dark, the colour, its tint, the paper, the accent. */\nexport function paletteFrom(hue: number, harmony: number): BrandKit[\"palette\"] {\n const h = ((hue % 360) + 360) % 360;\n const accent = (h + HARMONIES[((harmony % BRAND_HARMONIES) + BRAND_HARMONIES) % BRAND_HARMONIES]!) % 360;\n const hexes = [hslToHex(h, 45, 13), hslToHex(h, 72, 52), hslToHex(h, 80, 82), hslToHex(h, 30, 95), hslToHex(accent, 78, 72)];\n const taken = new Set<string>();\n return hexes.map((hex) => ({ name: nameOf(hex, taken), hex }));\n}\n\n/**\n * What `company.set_brand` takes. One schema for the tool and for the studio's card, so the card\n * never previews a kit the tool would refuse.\n */\nexport const BrandKitArgsSchema = z.object({\n colour: z\n .string()\n .regex(/^#[0-9a-fA-F]{6}$/)\n .describe(\"The brand's main colour, as #rrggbb — usually the logo's own. The palette is drawn around it.\"),\n harmony: z\n .number()\n .int()\n .min(0)\n .max(BRAND_HARMONIES - 1)\n .optional()\n .describe(\"Which accent the palette takes, 0–3. Change it when asked for other colours with the same main one.\"),\n typeface: z.enum(BRAND_TYPEFACES).describe(\"grotesk (clean), serif (classic), rounded (friendly) or mono (technical).\"),\n tagline: z.string().max(80).optional().describe(\"One short line under the name. Leave it out when there is none.\"),\n});\nexport type BrandKitArgs = z.infer<typeof BrandKitArgsSchema>;\n\n/** The kit a colour, a harmony, a typeface and a line make; the schema has passed it. */\nexport function brandKitFrom(input: { colour: string; harmony?: number | undefined; typeface: BrandKit[\"typeface\"]; tagline?: string | undefined }): BrandKit {\n return BrandKitSchema.parse({\n palette: paletteFrom(hueOf(hexToRgb(input.colour.toLowerCase())), input.harmony ?? 0),\n typeface: input.typeface,\n tagline: (input.tagline ?? \"\").trim().slice(0, 80),\n });\n}\n","/**\n * The §40 signed read for one stored file — the HMAC and the address, in one place.\n *\n * It lives here for the reason `session-token.ts` does: `apps/api` already depends on\n * `apps/runtime-do`, so a *session tool* that must MINT one of these could not import the minter\n * from the route that verifies it without a cycle. One definition, so what mints and what verifies\n * cannot drift — and they must not, because a link that verifies differently than it was signed is\n * a 403 on a URL the model was told to look at.\n *\n * The construction is unchanged from the one `apps/api/src/routes/files.ts` has served since §40:\n * an HMAC over **every other field in the URL**, so there is nothing in it a holder can edit, and\n * `{name}` rides in the path rather than a query parameter so the URL ends in a real file extension\n * — which is what lets a `<video>` tag, a fetch-once publishing provider, and now a model provider\n * fetching an `image_url` type the thing from its address alone.\n */\n\nconst encoder = new TextEncoder();\n\n/**\n * The bound for a link minted BY A SESSION rather than by a person or an API key (ADR-0725).\n *\n * What it hands back is an unauthenticated bearer capability to raw org media: whoever holds the\n * string reads the bytes, with no credential and no further check. Seven days is the right trade\n * for a review link a person opens out of an email tomorrow (`files.ts` `FILE_URL_TTL_MS`). It is\n * the wrong trade for a link whose only consumer is a provider fetching it once, seconds from now,\n * minted on the one path a prompt injection can reach — so the window is sized to that fetch.\n *\n * It is here rather than in `files.ts` because three callers now mint at this bound — the\n * `POST /v1/files/{id}/url` route, the social publish, and the image link a tool result carries\n * (§16.2) — and the three must agree.\n */\nexport const SESSION_FILE_URL_TTL_MS = 15 * 60_000;\n\n/**\n * WHERE A GENERATED ASSET'S BYTES ARE (`canonical-spec §33.5`, ADR-0885): the media bucket, under a\n * `media:` scheme no other key can begin with — every other writer's key starts with an org id,\n * `naive/`, `model-io/` or a blueprint slug, none of which holds a colon. The row's `storage_key`\n * says it, and the storage adapter routes by it; nothing infers it from a path segment.\n */\nexport const mediaStorageKey = (org: string, id: string): string => `media:${org}/${id}`;\nexport const isMediaStorageKey = (key: string): boolean => key.startsWith(\"media:\");\n\n/** Everything the MAC covers. Change one field and every URL ever minted stops verifying. */\nexport interface FileUrlParts {\n org: string;\n id: string;\n name: string;\n /** Epoch milliseconds. */\n expires: number;\n /** The bytes are a generated asset's, in the media bucket; absent for every other file. */\n store?: \"media\" | undefined;\n}\n\n/** The store a file's link reads from, by its row's key. */\nexport const storeOf = (storageKey: string): FileUrlParts[\"store\"] =>\n isMediaStorageKey(storageKey) ? \"media\" : undefined;\n\nfunction b64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** The MAC alone. `v1` is in the signed string so a future construction cannot be replayed as this one. */\nexport async function signFileUrl(secret: string, parts: FileUrlParts): Promise<string> {\n const key = await crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n // A media link signs its store, so it cannot be edited into a read of the other bucket; every\n // other link signs exactly what it always did, so no URL already handed out stops working.\n const store = parts.store === \"media\" ? \":media\" : \"\";\n const message = `vetta.file-url.v1:${parts.org}:${parts.id}:${parts.name}:${parts.expires}${store}`;\n return b64url(new Uint8Array(await crypto.subtle.sign(\"HMAC\", key, encoder.encode(message))));\n}\n\n/** Constant-time over equal-length strings; unequal lengths are already a mismatch. */\nexport function fileUrlMacMatches(expected: string, given: string): boolean {\n if (expected.length !== given.length) return false;\n let diff = 0;\n for (let i = 0; i < expected.length; i += 1) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * The whole address, at `origin`. Callers own the TTL, because the two callers want very different\n * ones: seven days for a review link a person opens tomorrow, fifteen minutes for a capability\n * minted on a path a prompt injection can reach (`files.ts`, ADR-0725).\n */\nexport async function fileUrl(secret: string, origin: string, parts: FileUrlParts): Promise<string> {\n const url = new URL(`/v1/files/${parts.id}/${encodeURIComponent(parts.name)}`, origin);\n url.searchParams.set(\"org\", parts.org);\n url.searchParams.set(\"expires\", String(parts.expires));\n if (parts.store === \"media\") url.searchParams.set(\"in\", \"media\");\n url.searchParams.set(\"sig\", await signFileUrl(secret, parts));\n return url.toString();\n}\n","/**\n * `defineProject` — the whole blueprint DSL (`workstreams/10-blueprints.md §2`). Five resource\n * kinds, keyed by name; every declared field is a field the public API accepts (`canonical-spec\n * §12, §29`), never a translation layer. Refusals happen at define time, in the author's own\n * vocabulary, because the old system's lesson is that a refusal surfaced anywhere later gets\n * misread as a toolchain problem (see `load.ts`).\n */\nimport {\n APP_NAME,\n AppMcpPathSchema,\n AppTypeSchema,\n BudgetSchema,\n CreateLegalCompanySchema,\n CreateWalletSchema,\n DEFAULT_WALLET_NETWORK,\n CreateBucketSchema,\n ENV_NAME,\n HandoffsField,\n IdentitySchema,\n IssueCardSchema,\n JsonSchemaDocument,\n McpServerSchema,\n MiniAppDeclsSchema,\n Metadata,\n MicroUsdField,\n QuestionFieldSchema,\n SkillRefSchema,\n SocialPlatformSchema,\n TEMPLATE_QUESTIONS_MAX,\n ToolsetSchema,\n VaultCredentialKindSchema,\n VaultSchema,\n WindowSchema,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\nimport { DeclMultiagentField, hasRoster, rosterNames } from \"./roster\";\nimport { BLUEPRINTS, chooseTemplate, type Template } from \"./template\";\n\n/**\n * A config that loaded but refuses itself. A distinct class so the loader can tell \"the author's\n * declaration is wrong\" apart from \"the module could not be evaluated\" — the two failure modes the\n * old `naive up` collapsed into one, silently.\n */\nexport class BlueprintRefusal extends Error {\n override readonly name = \"BlueprintRefusal\";\n}\n\n/**\n * Where an app's environment value COMES FROM — a literal, a variable read at apply time, or a\n * value nobody has yet (`canonical-spec §29.7`). A secret never sits in the config file either way.\n *\n * `{ generate: true }` is the third source and it names one: *the platform invents this, once, on\n * the apply that first sets it.* It exists because `DASHBOARD_TOKEN`'s own comment in both live\n * blueprints reads \"set it to any long random string\" — a human inventing entropy is a defect, not\n * a setup question — and because a hosted apply has no shell to read one from.\n *\n * It carries no length or alphabet knob: there is exactly one kind of value worth inventing, and a\n * knob no author can reason about is a knob that will be got wrong. `z.literal(true)` rather than a\n * boolean, so `generate: false` is not a second, silent spelling of \"required\" — `from_env` is the\n * only spelling of that.\n *\n * NOTHING GENERATES FOR AN UNSET VARIABLE. A declaration has to ask, because inventing a value for\n * whatever happens to be missing would silently manufacture a credential for something that\n * genuinely needed the operator's, and the app would come up holding a secret nobody can reproduce.\n */\nconst EnvValueSchema = z.union([\n z.string(),\n z.object({ from_env: z.string().min(1) }),\n z.object({ generate: z.literal(true) }),\n]);\n\nconst AppDeclSchema = z.object({\n /** Becomes a hostname, so the grammar is the platform's `APP_NAME` (a DNS label). */\n name: z.string().regex(APP_NAME, \"a lowercase DNS label, 63 characters or fewer\"),\n type: AppTypeSchema,\n description: z.string().optional(),\n /** A directory whose files are collected and shipped as the app's file-map deployment. */\n deploy_dir: z.string().min(1).optional(),\n /** The path the app itself serves MCP on (§29.5); `fullstack` only. Absent means none. */\n mcp: AppMcpPathSchema.optional(),\n /** Written as the app's write-only secrets (§29.2) on every apply; names follow the platform's `ENV_NAME`. */\n env: z\n .record(z.string().regex(ENV_NAME), EnvValueSchema, { error: \"keyed by environment variable name (A-Z, 0-9, _)\" })\n .optional(),\n /** An install may not leave this app out of its `selection` (§31.2). Absent means it may. */\n required: z.boolean().optional(),\n // core-gaps: U8-database\n /** SQL files applied in order to the app's database after it is provisioned (§37); `fullstack` only. */\n migrations: z.array(z.string().min(1)).optional(),\n // core-gaps: storage-stock\n /** Buckets the app's object store must hold (§38.2); `fullstack` only. `public` defaults to false. */\n buckets: z.array(CreateBucketSchema).optional(),\n});\n\n/**\n * A cron on the agent — a platform deployment (§12) minus what `up` fills in: `agent_id`, and the\n * `identity`, a declared persona *name* like the agent's own. `cron` is the key the reconciler\n * matches live rows by (deployments have no name), so it must be unique within one agent.\n * `budget_micro_usd` has no default on `POST /v1/deployments`, so it is required here for the\n * same reason the agent's `budget` is.\n */\nconst ScheduleDeclSchema = z.object({\n cron: z.string().min(1),\n timezone: z.string().min(1).optional(),\n /** The message every fire opens its session with (`input_template` on the wire). */\n input: z.string().min(1),\n /**\n * What a fire does, in a few words a person reads (\"Weekly report\") — the launch card's line for it\n * and the receipt's (`canonical-spec §31.3`, ADR-1172). Printed, never provisioned; absent, the\n * platform reads the opening of `input`.\n */\n summary: z.string().min(1).max(48).optional(),\n budget_micro_usd: MicroUsdField.nonnegative(),\n identity: z.string().min(1).optional(),\n enabled: z.boolean().optional(),\n});\n\n/** `ToolsetSchema` already refuses a malformed `tools.configs.browser.config` by field (`canonical-spec §32.2`). */\nconst ToolsDeclSchema = ToolsetSchema;\n\n/** Exactly the `POST /v1/agents` fields a blueprint declares — `model` and `budget` are required by that route, so requiring them here turns a guaranteed apply-time refusal into a define-time one. */\nconst AgentDeclSchema = z.object({\n name: z.string().min(1),\n model: z.string().min(1),\n budget: BudgetSchema,\n description: z.string().optional(),\n /** Two or three words the studio prints beside the name (§31.5) — \"Head of content\", not a sentence. */\n role: z.string().min(1).optional(),\n /** An install may not leave this agent out of its `selection` (§31.2). Absent means it may. */\n required: z.boolean().optional(),\n system: z.string().optional(),\n tools: ToolsDeclSchema.optional(),\n skills: z.array(SkillRefSchema).optional(),\n mcp_servers: z.array(McpServerSchema).optional(),\n /** The rest of the runtime's agent config (§31.6), each the core schema; absent means the route's default and never drift. */\n window: WindowSchema.optional(),\n /** A roster names crew members by declared *name*; `up` resolves them to `agt_` ids in a second pass (`roster.ts`). */\n multiagent: DeclMultiagentField.optional(),\n output_schema: JsonSchemaDocument.nullable().optional(),\n structured_output_required: z.boolean().optional(),\n metadata: Metadata.optional(),\n /** Declared app *names*; `up` resolves them to `app_` ids in `tools.configs.apps` (§29.3). */\n allowed_apps: z.array(z.string()).optional(),\n /** A declared identity *name*; `up` attaches it after the agent upsert (§22). */\n identity: z.string().min(1).optional(),\n /**\n * Who this agent may `send_to_agent` (§31.7, §28.12): `true` (anyone in the organization),\n * `false` (nobody), `\"team\"` (its `multiagent` roster), or declared agent *names*, checked\n * against the roster here. Absent means the route's default, `true`, and is never drift.\n */\n handoffs: HandoffsField.optional(),\n /** The agent's deployments as a complete set: declared → owned, and the rest are pruned (ADR-0355). */\n schedules: z.array(ScheduleDeclSchema).optional(),\n /**\n * The first thing this agent reads, once, on the apply that **creates** it (`canonical-spec\n * §31.4`). It is what turns a provisioned crew into a crew that has started working.\n *\n * Neither of its neighbours can carry it. A `schedule` fires again and again; an intake happens\n * exactly once, at creation, and never on a later apply of the same agent. `system` is standing\n * instruction re-read every turn; an intake is a message the agent is sent.\n *\n * `budget_micro_usd` is optional here and required on a schedule, because a cron spends\n * repeatedly and unattended while an intake spends once, at an apply a person is watching. Absent\n * means the agent's own `budget` governs.\n */\n intake: z\n .object({ message: z.string().min(1), budget_micro_usd: MicroUsdField.nonnegative().optional() })\n .optional(),\n});\n\n/**\n * A vault credential (§23) minus what `up` fills in. `value` is a real third-party secret, so it is\n * `{ from_env }` only — never a literal — and travels once, on create. Values are write-only and\n * rows immutable, so `kind`, `key` and `host` / `mcp_server_url` are all the reconciler can match a\n * live row by.\n */\nconst CredentialDeclSchema = z.object({\n kind: VaultCredentialKindSchema,\n key: z.string().min(1).max(128),\n /** The one exact destination host an `env_var` is bound to. */\n host: z.string().min(1).optional(),\n /** The MCP server URL a `static_bearer` / `mcp_oauth` token is matched to. */\n mcp_server_url: z.url().optional(),\n value: z.object({ from_env: z.string().min(1) }),\n});\n\n/** `name` is the vault's `display_name`, the key it is found by; `identity` a declared persona *name*. */\nconst VaultDeclSchema = z.object({\n name: VaultSchema.shape.display_name,\n identity: z.string().min(1).optional(),\n credentials: z.array(CredentialDeclSchema),\n});\n\n/** `file` holds the skill body, resolved against the config's directory; the slug grammar is `POST /v1/skills`' (§13). */\nconst SkillDeclSchema = z.object({\n slug: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, \"lowercase letters, digits and dashes\"),\n file: z.string().min(1),\n});\n\n/**\n * A company the identity should hold (`canonical-spec §43.6`), keyed by `label`. Members are people\n * and never sit in a repo, so `up` only REPORTS whether a company matching a name option exists; it\n * never starts a hosted check and never debits a fee.\n */\nconst LegalDeclSchema = CreateLegalCompanySchema.pick({\n state: true,\n name_options: true,\n naics_code: true,\n description: true,\n}).extend({ label: z.string().min(1).max(128) });\n\n/**\n * `POST /v1/identities/{id}/wallet`'s body (§44.5): created if absent, policy patched on drift, never\n * swept. One declaration per network — a single object (the testnet wallet unless it names a network)\n * or a list for a persona holding both.\n */\nconst WalletDeclSchema = CreateWalletSchema.or(\n z.array(CreateWalletSchema).refine(\n (list) => new Set(list.map((w) => w.network ?? DEFAULT_WALLET_NETWORK)).size === list.length,\n { message: \"one wallet per network\" },\n ),\n);\n\n/** `POST /v1/identities/{id}/cards`' body (§45.5): presence by `label`; a live non-terminal card is `unchanged`. */\nconst CardDeclSchema = IssueCardSchema;\n\nconst IdentityDeclSchema = IdentitySchema.pick({ name: true, description: true })\n .partial({ description: true })\n .extend({\n legal: z.array(LegalDeclSchema).optional(),\n wallet: WalletDeclSchema.optional(),\n cards: z.array(CardDeclSchema).optional(),\n });\n\n/** Names to delete on `up` — the declarative tombstone for a resource dropped from the config. */\nconst RemovedSchema = z.object({\n apps: z.array(z.string().min(1)).default([]),\n agents: z.array(z.string().min(1)).default([]),\n skills: z.array(z.string().min(1)).default([]),\n identities: z.array(z.string().min(1)).default([]),\n vaults: z.array(z.string().min(1)).default([]),\n});\n\n/**\n * Names this apply widens over instead of narrowing away: an agent another template of the same\n * blueprint declares and the chosen one does not. `up` reports each one that is live and writes\n * nothing — the switch rule, WIDEN NEVER NARROW. It is the mirror of `removed`, which stays the\n * only way anything is deleted, and `defineProject` fills it in from `templates`.\n */\nconst KeptSchema = z.object({ agents: z.array(z.string().min(1)).default([]) });\n\n/**\n * One card the apply seeds on the organization's board (`canonical-spec §31.11`). `key` is the\n * card's idempotency handle — `<project>:<key>` on the wire — so a re-apply finds the card it wrote;\n * `assignee` is an agent NAME, which is what a board card carries (§28.11); `blocked_by` names\n * sibling tasks by key and becomes their `crd_` ids at apply time.\n */\nconst TaskDeclSchema = z.object({\n key: z.string().min(1),\n title: z.string().min(1).max(200),\n body: z.string().max(8192).optional(),\n assignee: z.string().min(1).optional(),\n blocked_by: z.array(z.string().min(1)).optional(),\n});\n\nexport const ProjectSchema = z.object({\n name: z.string().min(1),\n /** The machine this project runs: its repo, its screens, its `/api/*` (`template.ts`). */\n blueprint: z.string().min(1).optional(),\n /** Which of that blueprint's templates provides the crew; a blueprint with a default may omit it. */\n template: z.string().min(1).optional(),\n /**\n * What a person calls this template, one line on what its crew does, and the networks it\n * publishes to (`canonical-spec §31.5`). Printed on the artifact and never provisioned: where the\n * crew posts is the accounts connected to its persona, not this list.\n */\n title: z.string().min(1).max(80).optional(),\n description: z.string().min(1).max(280).optional(),\n platforms: z.array(SocialPlatformSchema).optional(),\n /**\n * The first week in the template's own words, for the launch card (`canonical-spec §31.5`,\n * ADR-1172): `day_one` is what Day 1 comes to (\"Set up and publish the first post\"), `every_day`\n * what each day after it carries (\"New posts · Performance analysis\"), and `after` what the card's\n * \"Day 8 on\" line says follows the week (\"The week repeats · the CEO finds sponsors…\"). Printed,\n * never provisioned; absent, the card reads the seeded cards and the timers, and \"Day 8 on\" says\n * only \"The week repeats\".\n */\n roadmap: z\n .object({\n day_one: z.string().min(1).max(60).optional(),\n every_day: z.string().min(1).max(60).optional(),\n after: z.string().min(1).max(80).optional(),\n })\n .optional(),\n /**\n * The company's mini apps (`canonical-spec §50`): each a name, an icon and pages of the platform's\n * blocks — data only, checked with the platform's catalog here and again when a page is read. The\n * studio draws every one with one general UI, under Apps.\n */\n mini_apps: MiniAppDeclsSchema.optional(),\n /**\n * What a person is asked BEFORE the crew is provisioned (`canonical-spec §31.2`).\n *\n * `QuestionField` is reused rather than restated: a setup question and a question a parked agent\n * asks mid-run are the same object asked at different times, so a blueprint author writes one\n * shape and one component renders both. These are published on the artifact — they are the whole\n * reason the catalog has a `questions` column — and the answers a person gives go on the install\n * (§29.6), never into the tree, because the tree is identical for everyone.\n *\n * **Configuration only.** A secret is a vault credential or an app secret; neither is an answer.\n */\n questions: z.array(QuestionFieldSchema).default([]),\n skills: z.array(SkillDeclSchema).default([]),\n identities: z.array(IdentityDeclSchema).default([]),\n vaults: z.array(VaultDeclSchema).default([]),\n apps: z.array(AppDeclSchema).default([]),\n agents: z.array(AgentDeclSchema).default([]),\n /**\n * The agents this template creates PER CLIENT the operator signs (`canonical-spec §31.1`) —\n * printed on the artifact so a person sees the whole company, never provisioned by an apply,\n * because the apply does not know the clients yet. Names only: a model and a budget are the\n * crew's business at the moment a client is signed, not the declaration's.\n */\n crew_per_client: z\n .array(z.object({ name: z.string().min(1), role: z.string().min(1).optional(), description: z.string().optional() }))\n .optional(),\n /** The crew's first work, as cards on the organization's board rather than N private intakes (§31.11). */\n tasks: z.array(TaskDeclSchema).default([]),\n removed: RemovedSchema.default({ apps: [], agents: [], skills: [], identities: [], vaults: [] }),\n kept: KeptSchema.default({ agents: [] }),\n});\n\nexport type AppDecl = z.infer<typeof AppDeclSchema>;\nexport type AgentDecl = z.infer<typeof AgentDeclSchema>;\nexport type CrewPerClientDecl = NonNullable<ProjectConfig[\"crew_per_client\"]>[number];\nexport type ScheduleDecl = z.infer<typeof ScheduleDeclSchema>;\nexport type SkillDecl = z.infer<typeof SkillDeclSchema>;\nexport type IdentityDecl = z.infer<typeof IdentityDeclSchema>;\nexport type VaultDecl = z.infer<typeof VaultDeclSchema>;\nexport type CredentialDecl = z.infer<typeof CredentialDeclSchema>;\nexport type TaskDecl = z.infer<typeof TaskDeclSchema>;\nexport type ProjectConfig = z.infer<typeof ProjectSchema>;\n\nfunction refuse(message: string): never {\n throw new BlueprintRefusal(message);\n}\n\nfunction assertUniqueNames(kind: \"app\" | \"agent\" | \"skill\" | \"identity\" | \"vault\" | \"bucket\" | \"task\", names: string[]): void {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n refuse(`duplicate ${kind} name \"${name}\" — resources are keyed by name, so each ${kind} must be declared exactly once`);\n }\n seen.add(name);\n }\n}\n\n/**\n * The tasks with every blocker ahead of the card it blocks, declaration order otherwise — the order\n * `up` creates them in, since a card's `blocked_by` carries ids only an earlier create has answered.\n * A set that never empties is a cycle, refused by name.\n */\nexport function inDependencyOrder(tasks: readonly TaskDecl[]): TaskDecl[] {\n const placed = new Set<string>();\n const out: TaskDecl[] = [];\n while (out.length < tasks.length) {\n const next = tasks.find((task) => !placed.has(task.key) && (task.blocked_by ?? []).every((key) => placed.has(key)));\n if (next === undefined) {\n const stuck = tasks.filter((task) => !placed.has(task.key)).map((task) => `\"${task.key}\"`);\n refuse(`tasks ${stuck.join(\", \")}: blocked_by forms a cycle — a card cannot wait on a card that waits on it`);\n }\n placed.add(next.key);\n out.push(next);\n }\n return out;\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value)) deepFreeze(child);\n Object.freeze(value);\n }\n return value;\n}\n\n/**\n * The blueprint / template pair, judged before anything else: an unknown one is refused here, not\n * discovered at apply time against a half-provisioned org. A blueprint with a default fills the\n * template in, so the config that comes back always names the crew that was applied.\n */\nfunction applyChoice(config: ProjectConfig): void {\n const chosen = chooseTemplate(config.blueprint, config.template);\n if (!chosen.ok) refuse(chosen.message);\n if (chosen.template !== undefined) config.template = chosen.template;\n}\n\n/** Validate an untyped value (a loaded `.json`, an evaluated module) into a frozen project. */\nexport function parseProject(input: unknown): Readonly<ProjectConfig> {\n const parsed = ProjectSchema.safeParse(input);\n if (!parsed.success) {\n // A union (`wallet: {…} | [{…}]`) reports \"Invalid input\" at its own path; the branch that got past\n // the shape check carries the author's actual mistake, so name that instead.\n const unwrap = (i: z.core.$ZodIssue): z.core.$ZodIssue[] => {\n if (i.code !== \"invalid_union\") return [i];\n const branch = i.errors.find((b) => !b.some((e) => e.code === \"invalid_type\" && e.path.length === 0));\n return branch ? branch.map((e) => ({ ...e, path: [...i.path, ...e.path] })) : [i];\n };\n const lines = parsed.error.issues.flatMap(unwrap).map((i) => `${i.path.join(\".\") || \"config\"}: ${i.message}`);\n refuse(`invalid project config — ${lines.join(\"; \")}`);\n }\n const config = parsed.data;\n applyChoice(config);\n // The cap is on what the studio puts in front of a buyer, not on what a hand-written config may\n // ask (§7.1). It was three; the fourth slot was bought by `optional` — a question that may be\n // left blank costs a person a glance, not an answer, so a form of four whose tail is optional is\n // still the one sitting the cap exists to protect. A fifth is not (ADR-0757).\n if (config.template !== undefined && config.questions.length > TEMPLATE_QUESTIONS_MAX) {\n refuse(`template \"${config.template}\" asks ${config.questions.length} questions, but a template asks at most ${TEMPLATE_QUESTIONS_MAX} before anything is provisioned — a fifth belongs to the crew's first conversation`);\n }\n assertUniqueNames(\"app\", [...config.apps.map((a) => a.name), ...config.removed.apps]);\n assertUniqueNames(\"agent\", [...config.agents.map((a) => a.name), ...config.removed.agents, ...config.kept.agents]);\n assertUniqueNames(\"skill\", [...config.skills.map((s) => s.slug), ...config.removed.skills]);\n assertUniqueNames(\"identity\", [...config.identities.map((i) => i.name), ...config.removed.identities]);\n assertUniqueNames(\"vault\", [...config.vaults.map((v) => v.name), ...config.removed.vaults]);\n const appNames = new Set(config.apps.map((a) => a.name));\n for (const app of config.apps) {\n if (app.type === \"frontend_only\" && app.mcp !== undefined) {\n refuse(`app \"${app.name}\": mcp is set, but a frontend_only app has no server to answer on it — declare type \"fullstack\" or drop mcp`);\n }\n // core-gaps: U8-database\n if (app.type === \"frontend_only\" && app.migrations !== undefined) {\n refuse(`app \"${app.name}\": migrations are set, but a frontend_only app has no database — declare type \"fullstack\" or drop migrations`);\n }\n // core-gaps: storage-stock\n if (app.type === \"frontend_only\" && app.buckets !== undefined) {\n refuse(`app \"${app.name}\": buckets are set, but a frontend_only app has no object store — declare type \"fullstack\" or drop buckets`);\n }\n assertUniqueNames(\"bucket\", (app.buckets ?? []).map((bucket) => bucket.name));\n }\n const identityNames = new Set(config.identities.map((i) => i.name));\n for (const vault of config.vaults) {\n if (vault.identity !== undefined && !identityNames.has(vault.identity)) {\n refuse(`vault \"${vault.name}\": identity names \"${vault.identity}\", but no identity with that name is declared in this project`);\n }\n const seen = new Set<string>();\n for (const credential of vault.credentials) {\n if (credential.kind === \"env_var\") {\n refuse(\n `vault \"${vault.name}\": credential \"${credential.key}\" is an env_var, which needs substitution at the sandbox egress boundary — not available on this platform, so the API would refuse it; use a static_bearer or mcp_oauth credential with an mcp_server_url, which is injected before the sandbox sees it`,\n );\n }\n const at = [credential.kind, credential.key, credential.host ?? credential.mcp_server_url ?? \"\"].join(\" \");\n if (seen.has(at)) {\n refuse(`vault \"${vault.name}\": credential ${credential.kind} \"${credential.key}\" is declared twice for the same destination — credentials are matched to live rows by kind, key and destination, so each must be unique per vault`);\n }\n seen.add(at);\n }\n }\n const agentNames = new Set([...config.agents.map((a) => a.name), ...config.kept.agents]);\n for (const agent of config.agents) {\n const rostered = new Set<string>();\n for (const name of hasRoster(agent.multiagent) ? rosterNames(agent.multiagent) : []) {\n if (name === agent.name) refuse(`agent \"${agent.name}\": multiagent roster names itself — a coordinator delegates to a copy of itself with { type: \"self\" }`);\n if (config.removed.agents.includes(name)) refuse(`agent \"${agent.name}\": multiagent roster names \"${name}\", which this config removes — drop it from the roster or keep the agent`);\n if (!agentNames.has(name)) refuse(`agent \"${agent.name}\": multiagent roster names \"${name}\", but no agent with that name is declared in this project`);\n if (rostered.has(name)) refuse(`agent \"${agent.name}\": multiagent roster names \"${name}\" twice — a team names each member once`);\n rostered.add(name);\n }\n for (const name of agent.allowed_apps ?? []) {\n if (!appNames.has(name)) {\n refuse(`agent \"${agent.name}\": allowed_apps names \"${name}\", but no app with that name is declared in this project`);\n }\n }\n if (agent.identity !== undefined && !identityNames.has(agent.identity)) {\n refuse(`agent \"${agent.name}\": identity names \"${agent.identity}\", but no identity with that name is declared in this project`);\n }\n if (agent.handoffs === \"team\" && !hasRoster(agent.multiagent)) {\n refuse(`agent \"${agent.name}\": handoffs is \"team\", but the agent declares no multiagent roster — there is no team to hand to`);\n }\n const handoffs = new Set<string>();\n for (const name of Array.isArray(agent.handoffs) ? agent.handoffs : []) {\n if (name === agent.name) refuse(`agent \"${agent.name}\": handoffs names itself — an agent cannot send_to_agent its own seat`);\n if (config.removed.agents.includes(name)) refuse(`agent \"${agent.name}\": handoffs names \"${name}\", which this config removes — drop it from handoffs or keep the agent`);\n if (!agentNames.has(name)) refuse(`agent \"${agent.name}\": handoffs names \"${name}\", but no agent with that name is declared in this project`);\n if (handoffs.has(name)) refuse(`agent \"${agent.name}\": handoffs names \"${name}\" twice`);\n handoffs.add(name);\n }\n const crons = new Set<string>();\n for (const schedule of agent.schedules ?? []) {\n if (crons.has(schedule.cron)) {\n refuse(`agent \"${agent.name}\": schedule cron \"${schedule.cron}\" is declared twice — schedules are matched to live deployments by cron, so each must be unique per agent`);\n }\n crons.add(schedule.cron);\n if (schedule.identity !== undefined && !identityNames.has(schedule.identity)) {\n refuse(`agent \"${agent.name}\": schedule \"${schedule.cron}\" identity names \"${schedule.identity}\", but no identity with that name is declared in this project`);\n }\n }\n }\n assertUniqueNames(\"task\", config.tasks.map((task) => task.key));\n const taskKeys = new Set(config.tasks.map((task) => task.key));\n for (const task of config.tasks) {\n if (`${config.name}:${task.key}`.length > 128) {\n refuse(`task \"${task.key}\": \"${config.name}:${task.key}\" is longer than the 128 characters a card key holds — shorten the key`);\n }\n if (task.assignee !== undefined && !agentNames.has(task.assignee)) {\n refuse(`task \"${task.key}\": assignee names \"${task.assignee}\", but no agent with that name is declared in this project`);\n }\n for (const key of task.blocked_by ?? []) {\n if (key === task.key) refuse(`task \"${task.key}\": blocked_by names itself — a card cannot wait on itself`);\n if (!taskKeys.has(key)) refuse(`task \"${task.key}\": blocked_by names \"${key}\", but no task with that key is declared in this project`);\n }\n }\n inDependencyOrder(config.tasks);\n return deepFreeze(config);\n}\n\n/** A config, plus the template data modules its blueprint repo carries (`template.ts`). */\nexport interface DefineInput extends z.input<typeof ProjectSchema> {\n /**\n * Every template this blueprint has — all of them, not just the chosen one. The chosen one's\n * agents become the project's crew; the others are what the switch rule keeps, which is why a\n * repo that carries only some of them is refused: switching would silently narrow.\n */\n templates?: readonly Template[];\n}\n\n/**\n * Fold the chosen template into the config: its crew joins whatever the config declares itself,\n * and every agent only a sibling template declares becomes a `kept` name. `removed` wins over\n * `kept` — an explicit tombstone is the operator narrowing on purpose.\n */\nfunction withTemplate(input: DefineInput, templates: readonly Template[]): DefineInput {\n const chosen = chooseTemplate(input.blueprint, input.template);\n if (!chosen.ok) refuse(chosen.message);\n if (chosen.template === undefined) refuse(\"templates are declared but no blueprint is — add `blueprint: \\\"…\\\"`\");\n const declared = BLUEPRINTS[input.blueprint!]!.templates;\n const carried = templates.map((one) => one.name);\n if ([...declared].sort().join(\" \") !== [...carried].sort().join(\" \")) {\n refuse(\n `blueprint \"${input.blueprint}\" has templates ${declared.join(\", \")}, but this repo carries ${carried.join(\", \") || \"none\"} — one repo carries every template of its blueprint, so switching is an edit and never a re-clone`,\n );\n }\n const picked = templates.find((one) => one.name === chosen.template)!;\n const agents = [...picked.agents, ...(input.agents ?? [])];\n const mine = new Set(agents.map((one) => one.name));\n const removed = new Set(input.removed?.agents ?? []);\n const kept = templates\n .filter((one) => one.name !== chosen.template)\n .flatMap((one) => one.agents.map((agent) => agent.name))\n .filter((name) => !mine.has(name) && !removed.has(name));\n return { ...input, template: chosen.template, agents, kept: { agents: [...new Set([...(input.kept?.agents ?? []), ...kept])] } };\n}\n\n/** The one export a `naive.config.ts` calls. Identity plus validation; the object comes back frozen. */\nexport function defineProject({ templates, ...input }: DefineInput): Readonly<ProjectConfig> {\n return parseProject(templates === undefined ? input : withTemplate(input, templates));\n}\n","/**\n * A coordinator's roster, declared by NAME (`canonical-spec §31.6`, §28).\n *\n * At runtime a roster entry is `{type:\"agent\", id:\"agt_…\", version?}`; in a declaration no agent has\n * an id yet, so the entry carries the declared `name` where the id goes and is otherwise the\n * runtime's own `RosterEntrySchema` — `self` and `advisor` unchanged. `up()` resolves the names in\n * a second pass, once every agent of the declaration has been created or patched and so has an id.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { MultiagentSchema, normaliseMultiagent, type Agent, type Multiagent } from \"@vetta/core\";\nimport { z } from \"zod\";\nimport type { AgentDecl } from \"./define\";\nimport { changed, type ResourceReport } from \"./report\";\n\nconst NAME = z.string().min(1);\nconst RosterNameSchema = z.union([\n NAME.transform((name) => ({ type: \"agent\" as const, name })),\n z.object({ type: z.literal(\"agent\"), name: NAME, version: z.number().int().positive().optional() }),\n z.object({ type: z.literal(\"self\") }),\n z.object({ type: z.literal(\"advisor\"), model: z.string().min(1) }),\n]);\n\n/** `MultiagentField` with the roster by name: `true | false | null | {type:\"coordinator\", agents, board?}`. */\nexport const DeclMultiagentField = z.union([\n z.boolean(),\n z.object({ ...MultiagentSchema.shape, agents: z.array(RosterNameSchema).min(1).max(20) }),\n z.null(),\n]);\nexport type DeclMultiagent = z.infer<typeof DeclMultiagentField>;\nexport type DeclRoster = Extract<DeclMultiagent, { type: \"coordinator\" }>;\n\nexport const hasRoster = (value: DeclMultiagent | undefined): value is DeclRoster =>\n typeof value === \"object\" && value !== null;\n\n/** The declared names a roster refers to, in roster order. */\nexport const rosterNames = (roster: DeclRoster): string[] =>\n roster.agents.flatMap((entry) => (entry.type === \"agent\" ? [entry.name] : []));\n\n/** `true`/`false`/`null` need no id and travel with the agent in pass one; a roster waits for pass two. */\nexport const teamWithoutRoster = (value: DeclMultiagent | undefined): boolean | null | undefined =>\n hasRoster(value) ? undefined : value;\n\n/**\n * The live roster as the declaration would compare it: the API pins every member to its current\n * `version` on save (§28), so a pin the declaration did not write is not drift.\n */\nfunction unpinned(desired: Multiagent, live: Multiagent): Multiagent {\n return {\n ...live,\n agents: live.agents.map((entry, i) => {\n const want = desired.agents[i];\n const pinned = want !== undefined && \"version\" in want && want.version !== undefined;\n return entry.type === \"agent\" && !pinned ? { type: \"agent\", id: entry.id } : entry;\n }),\n };\n}\n\n/**\n * Pass two for one agent: its roster's names become the ids the crew now has, and `multiagent` is\n * patched where the live roster differs. The agent's own report line is amended in place — an\n * `unchanged` agent whose team changed is `updated`; a name with no live agent is `refused`, which\n * also holds back its intake (a coordinator is not briefed without its team).\n */\nexport async function patchRoster(\n client: VettaClient,\n decl: AgentDecl,\n roster: DeclRoster,\n existing: Agent[],\n ids: Map<string, string>,\n dryRun: boolean,\n lines: ResourceReport[],\n): Promise<void> {\n const line = lines.find((one) => one.name === decl.name);\n if (line === undefined || line.action === \"refused\") return;\n const updated = (): void => {\n if (line.action === \"unchanged\") line.action = \"updated\";\n };\n const missing = rosterNames(roster).find((name) => !ids.has(name));\n if (missing !== undefined) {\n // A member this plan would create has no id yet, so the roster cannot be live: drift, not a refusal.\n if (dryRun && lines.some((one) => one.name === missing && one.action === \"created\")) return updated();\n line.action = \"refused\";\n line.reason = `multiagent roster needs agent \"${missing}\", which was not provisioned in this run`;\n return;\n }\n const desired: Multiagent = {\n ...roster,\n agents: roster.agents.map((entry) =>\n entry.type === \"agent\"\n ? { type: \"agent\", id: ids.get(entry.name)!, ...(\"version\" in entry && entry.version !== undefined ? { version: entry.version } : {}) }\n : entry,\n ),\n };\n const current = existing.find((agent) => agent.name === decl.name);\n const live = current === undefined ? null : normaliseMultiagent(current.multiagent);\n if (live !== null && !changed(desired, unpinned(desired, live))) return;\n if (!dryRun && line.id !== undefined) {\n try {\n await client.agents.update(line.id, { multiagent: desired });\n } catch (error) {\n line.action = \"refused\";\n line.reason = error instanceof Error ? error.message : String(error);\n return;\n }\n }\n updated();\n}\n","/**\n * The report vocabulary `up` speaks (`workstreams/10-blueprints.md §2` item 4) and the handful of\n * client-side moves every resource kind shares: one line per attempt with refusals caught into\n * the report, drift as \"a declared field whose live value differs\", 404 as \"not yet\", full\n * cursor pagination, and the by-name tombstone behind `removed`.\n */\nimport { ApiError, send, type ClientConfig } from \"@usenaive-sdk/vetta\";\nimport type { ResourceAction, ResourceReportLine } from \"@vetta/core\";\nimport { z } from \"zod\";\n\n/**\n * The report vocabulary is `@vetta/core`'s (`schema/install.ts`), re-exported here rather than\n * declared here, because the hosted apply publishes this report on the install row (§29.6) — which\n * makes it a wire shape, and a wire shape has one definition (`CLAUDE.md §2`). The names and the\n * fields are unchanged, so every reader of this package sees exactly what it always saw.\n */\nexport type { ResourceAction };\nexport type ResourceReport = ResourceReportLine;\n\nfunction message(error: unknown): string {\n // An API refusal carries a `request_id` even when its body was not the envelope (§3): a bare\n // \"HTTP 503\" off an edge is untraceable without it, and it is the one thing an operator hands\n // support. Named here, once, so every refusal in the report is traceable — not just an app's.\n if (error instanceof ApiError && error.requestId !== \"\") return `${error.message} (request ${error.requestId})`;\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * One report line per attempt: a thrown API refusal becomes `refused`, never an escape.\n *\n * `id` resolves the resource this attempt was working on, read only when the work threw — an app\n * that was created and then failed its deploy upload exists, and a `refused` line that dropped its\n * id would tell the operator nothing was made (ADR-0375's `refused`-with-id is the precedent). The\n * resolver is asked after the throw, so it reads whatever the failed work had already recorded.\n *\n * Split from `attempt` for the one caller that runs its attempts at once and files them in\n * DECLARATION order rather than completion order (`agents.ts`) — a report whose lines arrive in\n * whichever order the server answered would name the same resources in a different order on every\n * apply, which is exactly what a person reads the report to compare.\n */\nexport async function line(\n name: string,\n work: () => Promise<ResourceReport>,\n id?: () => string | undefined,\n): Promise<ResourceReport> {\n try {\n return await work();\n } catch (error) {\n const resolved = id?.();\n return { name, action: \"refused\", ...(resolved !== undefined ? { id: resolved } : {}), reason: message(error) };\n }\n}\n\n/**\n * HOW MANY WRITES OF ONE KIND AN APPLY HAS IN FLIGHT AT ONCE, AND WHY THERE IS A CEILING.\n *\n * Independent writes run together — that is what took a hosted install's four timers from 18 s to\n * under 5. But the fan-out cannot be the length of the list: a hosted apply admits up to 96 timers\n * (`apps/api/src/reconcile.ts`), and 96 requests launched at once queue behind the API's own\n * per-isolate connection gate until they time out and come back as refusals. Six at a time is the\n * whole of the win — the lists a blueprint actually declares are shorter than that — with none of\n * the fan-out, and it is the same number the API admits concurrently at its end.\n */\nconst AT_ONCE = 6;\n\n/** `work` over every item, six in flight, results in the order the items were given. */\nexport async function eachInFlight<T, R>(items: readonly T[], work: (item: T) => Promise<R>): Promise<R[]> {\n const out: R[] = [];\n for (let at = 0; at < items.length; at += AT_ONCE) {\n out.push(...(await Promise.all(items.slice(at, at + AT_ONCE).map(work))));\n }\n return out;\n}\n\n/** …and filed in the report, in the order the attempts were made. */\nexport async function attempt(into: ResourceReport[], name: string, work: () => Promise<ResourceReport>): Promise<ResourceReport> {\n const one = await line(name, work);\n into.push(one);\n return one;\n}\n\n/**\n * The same value, written with object keys in a fixed order, so two spellings of one value compare\n * equal. Arrays keep their order — in a toolset, a skill list or an `allowed_apps` it is meaning.\n */\nconst canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value === null || typeof value !== \"object\") return value;\n return Object.fromEntries(\n Object.keys(value as Record<string, unknown>)\n .sort()\n .map((key) => [key, canonical((value as Record<string, unknown>)[key])]),\n );\n};\n\n/**\n * A declared field whose live value differs; an undeclared field is never drift.\n *\n * Compared canonically, because the server is free to echo an object back with its keys in another\n * order and that is not a change. It did: a toolset went out as `{default_config, configs}` and\n * came back as `{configs, default_config}` with the tool names in a different order too, so every\n * agent carrying a `tools` block was judged drifted and PATCHed on every single apply. `naive up`\n * is supposed to converge — `sales` had reached version 8 doing nothing.\n */\nexport const changed = <T>(declared: T | undefined, live: T): declared is T =>\n declared !== undefined && JSON.stringify(canonical(declared)) !== JSON.stringify(canonical(live));\n\n/** A by-ref `GET` (skills and identities resolve their name) where 404 means \"not yet\". */\nexport async function absent<T>(work: Promise<T>): Promise<T | null> {\n try {\n return await work;\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) return null;\n throw error;\n }\n}\n\n/** A cursor page, shape only — the rows inside it are parsed one at a time. */\nconst PageShape = z.object({\n data: z.array(z.unknown()),\n has_more: z.boolean(),\n next_cursor: z.string().nullable(),\n});\n\n/** `deployment dep_…`, from whatever of a row we could not read still survives. */\nfunction rowLabel(row: unknown): string {\n const { object, id } = (row ?? {}) as { object?: unknown; id?: unknown };\n const words = [object, id].filter((one): one is string => typeof one === \"string\");\n return words.length > 0 ? words.join(\" \") : \"a row\";\n}\n\nconst why = (error: z.ZodError): string =>\n error.issues.map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`).join(\"; \");\n\n/**\n * Every row of a cursor-paginated list (§9), parsed **one row at a time** and read over `send`\n * rather than the SDK method, because the SDK parses a whole page against one strict schema.\n *\n * `up` reads every list before it writes anything, so one row the current contract no longer\n * admits aborted the entire apply — nothing written, nothing named, for the whole organization.\n * Measured on staging: two pre-ADR-0161 deployments still holding an `http://` `on_idle` stopped\n * `naive up` dead, and any customer carrying a pre-migration row meets it on their first apply.\n * A row the engine cannot read is a row it cannot reconcile: it is skipped and named in\n * `UpReport.skipped`, never thrown.\n */\nexport async function listAll<T>(\n config: ClientConfig,\n path: string,\n item: z.ZodType<T>,\n skipped: string[],\n query: Record<string, string | number | undefined> = {},\n): Promise<T[]> {\n const rows: T[] = [];\n let after: string | undefined;\n for (;;) {\n const response = await send(config, { method: \"GET\", path, query: { ...query, limit: 100, after } }, \"application/json\");\n const text = await response.text();\n if (!response.ok) throw new Error(`could not list ${path} (HTTP ${response.status})`);\n const body = PageShape.parse(JSON.parse(text));\n for (const row of body.data) {\n const parsed = item.safeParse(row);\n if (parsed.success) rows.push(parsed.data);\n else skipped.push(`${rowLabel(row)} in ${path} could not be read and was skipped: ${why(parsed.error)}`);\n }\n if (!body.has_more || body.next_cursor === null) return rows;\n after = body.next_cursor;\n }\n}\n\n/**\n * `removed` names delete by the same by-name lookup the upserts use. A name that is already\n * absent is `unchanged`, so a `removed` entry can stay in the config forever and re-running\n * stays safe; only a name that resolves to a live resource issues the DELETE.\n */\nexport async function tombstone(\n name: string,\n current: { id: string } | null | undefined,\n remove: (id: string) => Promise<unknown>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n if (!current) return { name, action: \"unchanged\", reason: \"already absent\" };\n if (!dryRun) await remove(current.id);\n return { name, action: \"deleted\", id: current.id };\n}\n","/**\n * Load `naive.config.{ts,js,mjs,json}` from a directory. The critical property, learned the hard\n * way in the old system: \"the toolchain could not evaluate the file\" and \"the file loaded and its\n * config is wrong\" are DIFFERENT failures. The old loader was `catch { return null }`, so every\n * deliberate define-time refusal was reported as a missing install and exited 0. Here the two are\n * separate variants with the author's message carried verbatim.\n */\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { BlueprintRefusal, parseProject, type ProjectConfig } from \"./define\";\n\nexport const CONFIG_CANDIDATES = [\n \"naive.config.ts\",\n \"naive.config.js\",\n \"naive.config.mjs\",\n \"naive.config.json\",\n] as const;\n\nexport type ConfigLoad =\n | { ok: true; path: string; config: Readonly<ProjectConfig> }\n /** No candidate file exists in the directory. */\n | { ok: false; reason: \"not_found\"; message: string }\n /** The module system could not evaluate the file: the toolchain/deps are missing. */\n | { ok: false; reason: \"unloadable\"; message: string }\n /** The file loaded and its config is wrong — a refusal or a bad shape. Fix the config. */\n | { ok: false; reason: \"invalid\"; message: string };\n\n/**\n * A module-resolution failure, as opposed to the config refusing itself. Matched on the CODE, not\n * the message: a refusal is free to mention a package name in its prose.\n */\nfunction isMissingModule(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\";\n}\n\nfunction message(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction validate(path: string, raw: unknown): ConfigLoad {\n try {\n return { ok: true, path, config: parseProject(raw) };\n } catch (error) {\n if (error instanceof BlueprintRefusal) return { ok: false, reason: \"invalid\", message: error.message };\n throw error;\n }\n}\n\nexport async function loadConfig(dir: string): Promise<ConfigLoad> {\n // Absolute from the start: the CLI's default `--dir` is `.`, and a relative path handed to\n // jiti is a bare specifier it cannot resolve (\"Cannot find module 'naive.config.ts'\").\n const path = CONFIG_CANDIDATES.map((name) => resolve(join(dir, name))).find(existsSync);\n if (!path) {\n return {\n ok: false,\n reason: \"not_found\",\n message: `no ${CONFIG_CANDIDATES.join(\" / \")} in ${dir}`,\n };\n }\n if (path.endsWith(\".json\")) {\n // A committed .json needs no toolchain, so a parse failure is only ever the file's own fault.\n try {\n return validate(path, JSON.parse(readFileSync(path, \"utf8\")));\n } catch (error) {\n if (error instanceof SyntaxError) return { ok: false, reason: \"invalid\", message: message(error) };\n throw error;\n }\n }\n let importFile: (specifier: string) => Promise<unknown>;\n try {\n const { createJiti } = await import(\"jiti\");\n importFile = createJiti(pathToFileURL(path).href).import;\n } catch (error) {\n return { ok: false, reason: \"unloadable\", message: message(error) };\n }\n let raw: unknown;\n try {\n const mod = await importFile(path);\n raw = (mod as { default?: unknown } | null)?.default ?? mod;\n } catch (error) {\n // The config's own imports failing to resolve is a toolchain problem; the config THROWING is\n // almost always a named define-time refusal, surfaced verbatim rather than replaced by a guess.\n return { ok: false, reason: isMissingModule(error) ? \"unloadable\" : \"invalid\", message: message(error) };\n }\n if (raw === null || typeof raw !== \"object\") {\n return {\n ok: false,\n reason: \"invalid\",\n message: `${path} evaluated to ${raw === undefined ? \"undefined\" : typeof raw}; it must \\`export default defineProject({...})\\``,\n };\n }\n return validate(path, raw);\n}\n","/**\n * Collect a `deploy_dir` into the file map `POST /v1/apps/{id}/deployments` takes: relative\n * POSIX path → base64 bytes (`canonical-spec §29.2`). Local state and secrets never ship:\n * `node_modules`, `.git`, `dist`-less build caches are the host's, `.env*` is the customer's.\n *\n * `contentHash` digests that map so `naive up` can send it as the deployment's `content_hash` and,\n * on the next apply, skip the upload when the newest live deployment carries the same one.\n */\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\n\nconst SKIP_DIRS = new Set([\"node_modules\", \".git\", \"dist\"]);\nconst MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n/**\n * A built tree, from either place one can be. A **directory** is the apply a person runs: a\n * checkout on their laptop or in CI. A **file map** is the apply the platform runs on their\n * behalf — the tree comes out of a published artifact's object-store entry (`canonical-spec §31.1`)\n * and there is no checkout anywhere, because a hosted run never clones a blueprint.\n */\nexport type FileSource = string | Record<string, string>;\n\n/**\n * ONE FILTER, ONE DIGEST, BOTH SOURCES — which is the whole of why the map arm exists rather than\n * the caller handing its map straight to `contentHash`.\n *\n * A published artifact's `content_hash` is compared against the newest deployment's to decide\n * whether to upload at all (§31.1), and the two sides of that comparison are collected in different\n * places: the deployment's from a directory here, the artifact's from a map on the server. If the\n * map arm skipped one exclusion or one size cap, the digests would differ for two trees that ship\n * the same bytes and every hosted install would re-upload, forever, with nothing to point at.\n */\nexport function collectFiles(source: FileSource): Record<string, string> {\n if (typeof source !== \"string\") return fromMap(source);\n const root = source;\n const files: Record<string, string> = {};\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n // `.env`, `.env.local`, `.env.production`, … — never upload secrets to a deploy.\n if (SKIP_DIRS.has(entry.name) || entry.name.startsWith(\".env\")) continue;\n const full = join(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (entry.isFile() && statSync(full).size <= MAX_FILE_BYTES) {\n files[relative(root, full).split(sep).join(\"/\")] = readFileSync(full).toString(\"base64\");\n }\n }\n };\n walk(root);\n return files;\n}\n\n/**\n * The same rules read off the path instead of off `readdirSync`. A map's keys are already the POSIX\n * relative paths the walk produces, so an excluded file is one whose path has an excluded segment —\n * and the size cap is measured on the decoded bytes, which is what the walk's `statSync` measured.\n */\nfunction fromMap(map: Record<string, string>): Record<string, string> {\n const files: Record<string, string> = {};\n for (const [path, base64] of Object.entries(map)) {\n const segments = path.split(\"/\");\n if (segments.some((segment) => SKIP_DIRS.has(segment) || segment.startsWith(\".env\"))) continue;\n if (Buffer.from(base64, \"base64\").length > MAX_FILE_BYTES) continue;\n files[path] = base64;\n }\n return files;\n}\n\n/**\n * sha-256 over the files in path order, each as `path NUL byte-length NUL bytes`: the same tree\n * hashes the same from any walk order, and the length prefix keeps two trees from sharing an\n * encoding. Hex, so it travels as a plain string.\n */\nexport function contentHash(files: Record<string, string>): string {\n const hash = createHash(\"sha256\");\n for (const [path, base64] of Object.entries(files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n const bytes = Buffer.from(base64, \"base64\");\n hash.update(`${path}\\0${bytes.length}\\0`).update(bytes);\n }\n return hash.digest(\"hex\");\n}\n","/**\n * The reconciler behind `naive up` (`workstreams/10-blueprints.md §2`): a pure client of the\n * public REST API through the SDK — upsert-by-name over routes that are already idempotent. No\n * server-side diff engine, no manifest store; re-running is always safe because every resource is\n * keyed by its config name.\n *\n * Nothing is deleted by omission (ADR-0352): `removed` names are the only tombstones, with one\n * bounded exception — a declared agent's `schedules` are owned as a complete set (`agents.ts`).\n * Skills and identities live here; apps, agents and vaults each have their own module, sharing the\n * report vocabulary in `report.ts`.\n *\n * One thing here is not a reconcile: an agent this apply **created** that declares an `intake` is\n * sent its briefing as a started session (`agents.ts`, `canonical-spec §31.4`). It is what turns a\n * provisioned crew into a crew that has started working, and it is idempotent for the same reason\n * everything else here is — the agent is created exactly once. `tasks` (`tasks.ts`, §31.11) is the\n * reconcile that supersedes it: cards on the organization's board, keyed so a re-apply finds them,\n * woken by the API's tick rather than started here.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { AgentSchema, DeploymentSchema, VaultCredentialSchema, VaultSchema, type Agent, type BlueprintSelection, type Vault } from \"@vetta/core\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { openIntake, reconcileSchedules, upsertAgent, type Ids } from \"./agents\";\nimport { findApp, ownershipRefusal, upsertApp, PLATFORM_ENV, type Owner, type PlatformEnv } from \"./apps\";\nimport { BlueprintRefusal, type AgentDecl, type AppDecl, type IdentityDecl, type ProjectConfig, type SkillDecl } from \"./define\";\nimport { reconcileCards } from \"./reconcile-cards\";\nimport { reportLegal } from \"./reconcile-legal\";\nimport type { MigrationFile } from \"./migrations\";\nimport { absent, attempt, eachInFlight, line, listAll, tombstone, type ResourceAction, type ResourceReport } from \"./report\";\nimport { hasRoster, patchRoster } from \"./roster\";\nimport { seedTasks } from \"./tasks\";\nimport { upsertCredential, upsertVault } from \"./vaults\";\nimport { reconcileWallet, walletName } from \"./reconcile-wallet\";\n\nexport interface UpReport {\n dry_run: boolean;\n /** The machine, and the template within it whose crew this apply provisioned (`template.ts`). */\n blueprint?: string;\n template?: string;\n skills: ResourceReport[];\n identities: ResourceReport[];\n /** One line per vault, then one per declared credential named `<vault> / <key>`. */\n vaults: ResourceReport[];\n apps: ResourceReport[];\n agents: ResourceReport[];\n /** One line per declared cron and per pruned live row, named `<agent> @ <cron>`. */\n schedules: ResourceReport[];\n /**\n * One line per agent this apply **created** that declares an `intake` — the session that was\n * started, named by the agent, `id` the `ses_`. Empty on every later apply of the same crew: an\n * agent is created once, so it is briefed once (`agents.ts`).\n */\n intake: ResourceReport[];\n /**\n * One line per declared task, named by its key, `id` the `crd_` (`tasks.ts`, `canonical-spec\n * §31.11`): `created` on the apply that seeded the card, `unchanged` on every later one — the\n * card's key stands for the task. The board's owner is a line under `agents` like any member.\n */\n tasks: ResourceReport[];\n /**\n * Live rows this client could not parse, named and stepped over (`report.ts`). One legacy row\n * used to abort the whole apply before any write; it is now a line here and nothing else.\n */\n skipped: string[];\n /**\n * Declared agents and apps the operator's `select` left out (`canonical-spec §31.2`): not created,\n * not armed, not briefed, and — when one already exists — left exactly as it is. A choice, kept\n * apart from `skipped` (rows this client could not read) and from a `refused` line (an attempt).\n */\n deselected: string[];\n}\n\nexport interface UpOptions {\n /** Plan only: reads happen, writes do not, and the report says what apply would do. */\n dry_run?: boolean;\n /** Base directory `deploy_dir` is resolved against — the config file's directory. */\n dir?: string;\n /**\n * `naive up --adopt`: take every app this run touches whose row names another project, or none\n * (ADR-0375). Off by default — adopting by default is what overwrote a live deployment.\n */\n adopt?: boolean;\n /**\n * The built trees, by app name, for an apply that runs where there is no checkout: the platform\n * applying a published artifact on an operator's behalf (`canonical-spec §31.1`). The bytes come\n * out of the artifact's object-store entry, in the same file map `deploy_dir` would have been\n * collected into — which is why `collectFiles` takes both and there is one digest (`files.ts`).\n *\n * Present ⇒ the disk is never read for an app, and an app whose tree is not in the map is refused\n * by name rather than deployed empty. Absent ⇒ `dir` + `deploy_dir`, exactly as before.\n */\n trees?: Record<string, Record<string, string>>;\n /**\n * Why a declared app is absent from `trees`, by app name — an object-store read that failed\n * rather than an object that was never uploaded. Both come out of `builtTree` as one refusal;\n * only the caller that did the reading can tell them apart, so only it can say (`apps.ts`).\n */\n tree_errors?: Record<string, string>;\n /**\n * core-gaps: U8-database — each app's `migrations`, by app name, as the publisher shipped them on\n * its built tree (`canonical-spec §31.1`); read only when `trees` is present. An app that declares\n * migrations and is absent here is refused by name (`migrations.ts`).\n */\n migrations?: Record<string, MigrationFile[]>;\n /**\n * A skill's bytes by slug, for a hosted apply of a published declaration that carries them\n * inline (`canonical-spec §42.8`). A hosted skill absent from this map is still refused by name.\n */\n skills?: Record<string, string>;\n /**\n * What an app's `{ from_env }` reads (`apps.ts`). The process's own environment by default —\n * the author's shell, which is the whole point of `from_env` on a laptop. A hosted apply has no\n * shell and passes the operator's **answers** instead (`canonical-spec §31.2`): the same\n * declaration, resolved against the only environment that apply has.\n */\n env?: Record<string, string | undefined>;\n /**\n * THE PLATFORM ENVIRONMENT (`canonical-spec §29.7`) — what the platform itself provides an app,\n * read BEFORE `env` and written whether or not the declaration names it.\n *\n * Present only on a hosted apply, and that is the whole of the local/hosted difference: `naive up`\n * from a checkout passes none, reads the author's shell, and behaves exactly as it always has.\n *\n * `NAIVE_IDENTITY_ID` is filled in here rather than by the caller, because the id does not exist\n * until this run has created the identity — identities are upserted before apps for the same\n * reason agents reference them by name.\n */\n platform?: PlatformEnv;\n /**\n * Which of the declared crew to provision, by name (§31.2). Omitted means everything, which is what\n * every apply before this option did. A name the declaration lacks, or a `required` one left out,\n * is a `BlueprintRefusal` before anything is read — the one thrown escape `up` has, because it is\n * the caller's input that is wrong and not a resource that could not be made.\n */\n select?: BlueprintSelection;\n /**\n * The install this crew belongs to — what a template agent's `metadata.project` names (§31.8).\n * Defaults to `config.name`, which is the install `naive up` files under. A hosted apply files\n * under the customer's own `project` and passes it here, so the runtime's lookup of the latest\n * applied install lands on the row that exists.\n */\n project?: string;\n /**\n * An install that shares the organization by its own names (ADR-1104, `scoped.ts`): its crew is\n * filed under `project` rather than the template, and an identity is stamped with `project` and\n * adopted only when it already carries it — another project's persona, or one nobody stamped, is\n * refused rather than taken. Absent is every apply before that rule, exactly as it was.\n */\n isolated?: boolean;\n /**\n * What dials an app's own address before its crew is briefed (`awaitServing`). The platform's\n * `fetch` by default; a test hands in a fake. It is NOT the client's `fetch`, which on a hosted\n * apply loops back into the API and never leaves the isolate.\n */\n probe?: typeof globalThis.fetch;\n}\n\n/** Bounded: an address still not answering after this is briefed anyway, and the turn says so. */\nconst SERVING_TRIES = 90;\nconst SERVING_MS = 2_000;\n\n/**\n * WAIT UNTIL EVERY APP THE CREW REACHES ANSWERS ON ITS OWN ADDRESS.\n *\n * A deployment reads `ready` — and the apply's `settleDeploy` returns — a moment before the host\n * serves the lasting hostname. Measured on staging: an install whose seven intakes opened 21 s\n * after the deploy row was written briefed six agents whose first turn found no `dashboard.*`\n * tools at all and one, 1 s later, that found them and filed fifteen leads. The runtime resolves\n * an app's MCP tools by dialing `url + mcp` at the turn (§29.5), so an intake that opens before\n * the address answers is a first turn spent asking for tools the declaration already granted.\n * A 401 or a 405 to a bare `/mcp` GET is the endpoint answering — reachability is the question,\n * not authorization. A 404 is not: the host answers 404 for an alias it has not propagated yet\n * (measured on staging, a second run — the wait returned at once and every first turn was again\n * tool-less), so it is waited out like a refused connection. Nor is a 5xx: a fullstack app's\n * database lands after its first build and the host re-ships it, and until that re-ship serves,\n * `/mcp` answers 503 on a bare GET (the dashboards open their store before the 405) — measured\n * on staging as a first turn told \"tool not found\" for every tool the declaration granted. The\n * bound is three minutes because a re-ship is a build, not an alias flip.\n */\nasync function awaitServing(addresses: readonly string[], probe: typeof globalThis.fetch): Promise<void> {\n await Promise.all(\n addresses.map(async (address) => {\n for (let poll = 0; poll < SERVING_TRIES; poll++) {\n try {\n const { status } = await probe(address, { method: \"GET\" });\n if (status < 500 && status !== 404) return;\n } catch {\n // Not serving yet: a refused connection or an unresolved name is the state being waited out.\n }\n await new Promise((resolve) => setTimeout(resolve, SERVING_MS));\n }\n }),\n );\n}\n\n/** The crew this apply takes (`UpOptions.select`), and the names it leaves out. */\nexport function selectCrew(\n config: Readonly<ProjectConfig>,\n select: BlueprintSelection | undefined,\n): { apps: readonly AppDecl[]; agents: readonly AgentDecl[]; deselected: string[] } {\n if (select === undefined) return { apps: config.apps, agents: config.agents, deselected: [] };\n const named = (kind: \"app\" | \"agent\", names: readonly string[]) => names.map((name) => `${kind} \"${name}\"`);\n const unknown = [\n ...named(\"app\", select.apps.filter((name) => !config.apps.some((decl) => decl.name === name))),\n ...named(\"agent\", select.agents.filter((name) => !config.agents.some((decl) => decl.name === name))),\n ];\n if (unknown.length > 0) {\n throw new BlueprintRefusal(`selection names ${unknown.join(\", \")}, which this declaration does not declare`);\n }\n const apps = config.apps.filter((decl) => select.apps.includes(decl.name));\n const agents = config.agents.filter((decl) => select.agents.includes(decl.name));\n const missing = [\n ...named(\"app\", config.apps.filter((decl) => decl.required === true && !apps.includes(decl)).map((decl) => decl.name)),\n ...named(\"agent\", config.agents.filter((decl) => decl.required === true && !agents.includes(decl)).map((decl) => decl.name)),\n ];\n if (missing.length > 0) {\n throw new BlueprintRefusal(\n `selection leaves out ${missing.join(\", \")}, which this template requires — ${missing.length === 1 ? \"it\" : \"they\"} cannot be deselected`,\n );\n }\n const deselected = [\n ...config.apps.filter((decl) => !apps.includes(decl)).map((decl) => decl.name),\n ...config.agents.filter((decl) => !agents.includes(decl)).map((decl) => decl.name),\n ];\n return { apps, agents, deselected };\n}\n\n/**\n * The one identity an app runs as, when the declaration declares exactly one (§29.7). A declaration\n * with several has not said which, and handing an app the wrong persona would give it the wrong\n * connected accounts; a declaration with none has no answer at all. Both live blueprints declare one.\n */\nfunction identityEnv(config: Readonly<ProjectConfig>, ids: Map<string, string>): Record<string, string> {\n if (config.identities.length !== 1) return {};\n const id = ids.get(config.identities[0]!.name);\n return id === undefined ? {} : { [PLATFORM_ENV.identity_id]: id };\n}\n\n/**\n * Skills are content-addressed (§13): the server mints a version only when the bytes differ, so\n * the local digest against the newest version says `unchanged` vs `updated` without a write —\n * which is also what makes the dry-run line exact.\n */\nasync function upsertSkill(\n client: VettaClient,\n decl: SkillDecl,\n opts: { dryRun: boolean; dir: string; hosted: boolean; skills: Record<string, string> },\n): Promise<ResourceReport> {\n // A HOSTED APPLY HAS NO CHECKOUT, so there is no file to read and `resolve(\"\", decl.file)` would\n // fail with an ENOENT naming a path that exists on nobody's disk. `trees` carries an app's bytes\n // and only a creator's published declaration carries a skill's inline (§13, §31.1, §42.8), so the\n // honest answer otherwise is a refusal that says which published thing is missing rather than a\n // filesystem error the operator cannot act on.\n const inline = opts.skills[decl.slug];\n if (opts.hosted && inline === undefined) {\n throw new Error(\n `skill \"${decl.slug}\" is declared as the file \"${decl.file}\", and a hosted apply has no ` +\n `checkout to read it from. Push it with \\`naive up\\` from a clone, or publish it as part of the blueprint.`,\n );\n }\n const content = inline ?? readFileSync(resolve(opts.dir, decl.file), \"utf8\");\n const sha256 = createHash(\"sha256\").update(content).digest(\"hex\");\n const current = await absent(client.skills.get(decl.slug));\n const latest = current ? (await client.skills.listVersions(decl.slug, { limit: 1 })).data[0] : undefined;\n const action: ResourceAction = !current ? \"created\" : latest?.sha256 === sha256 ? \"unchanged\" : \"updated\";\n if (action === \"unchanged\" || opts.dryRun) {\n return { name: decl.slug, action, ...(current ? { id: current.id } : {}) };\n }\n const pushed = await client.skills.push({ slug: decl.slug, content, sha256 });\n return { name: decl.slug, action, id: pushed.id };\n}\n\n/** `owner` is the isolated install's project (`UpOptions.isolated`); `undefined` adopts by name, as ever. */\nasync function upsertIdentity(\n client: VettaClient,\n decl: IdentityDecl,\n dryRun: boolean,\n identityIds: Map<string, string>,\n owner: string | undefined,\n): Promise<ResourceReport> {\n const current = await absent(client.identities.get(decl.name));\n if (!current) {\n if (dryRun) return { name: decl.name, action: \"created\" };\n const created = await client.identities.create({\n name: decl.name,\n ...(decl.description !== undefined ? { description: decl.description } : {}),\n ...(owner !== undefined ? { metadata: { project: owner } } : {}),\n });\n identityIds.set(decl.name, created.id);\n return { name: decl.name, action: \"created\", id: created.id };\n }\n const held = typeof current.metadata[\"project\"] === \"string\" ? current.metadata[\"project\"] : null;\n if (owner !== undefined && held !== owner) {\n return { name: decl.name, action: \"refused\", id: current.id, reason: ownershipRefusal(decl.name, owner, held, \"identity\") };\n }\n identityIds.set(decl.name, current.id);\n const drifted = decl.description !== undefined && decl.description !== current.description;\n if (drifted && !dryRun) await client.identities.update(current.id, { description: decl.description ?? null });\n return { name: decl.name, action: drifted ? \"updated\" : \"unchanged\", id: current.id };\n}\n\n/**\n * The `removed` tombstones, agents first so an agent never outlives an app it pointed at, and a\n * vault before its identity: deleting the vault is what hard-deletes the credentials (§23).\n */\nasync function applyRemoved(\n client: VettaClient,\n removed: ProjectConfig[\"removed\"],\n live: { agents: Agent[]; vaults: Vault[] },\n owner: Owner,\n report: UpReport,\n): Promise<void> {\n const dryRun = report.dry_run;\n for (const name of removed.agents) {\n const current = live.agents.find((agent) => agent.name === name);\n await attempt(report.agents, name, () => tombstone(name, current, (id) => client.agents.delete(id), dryRun));\n }\n // The same predicate as the upsert (ADR-0375): a delete tears down the hosting project and the\n // app database, so deleting another project's app is worse than overwriting it.\n for (const name of removed.apps) {\n await attempt(report.apps, name, async () => {\n const current = await findApp(client, name, owner.skipped);\n if (current !== null && current.project !== owner.project && !owner.adopt) {\n return { name, action: \"refused\", id: current.id, reason: ownershipRefusal(name, owner.project, current.project) };\n }\n return tombstone(name, current, (id) => client.apps.delete(id), dryRun);\n });\n }\n for (const slug of removed.skills) {\n await attempt(report.skills, slug, async () =>\n tombstone(slug, await absent(client.skills.get(slug)), (id) => client.skills.delete(id), dryRun),\n );\n }\n for (const name of removed.vaults) {\n const current = live.vaults.find((vault) => vault.display_name === name);\n await attempt(report.vaults, name, () => tombstone(name, current, (id) => client.vaults.delete(id), dryRun));\n }\n for (const name of removed.identities) {\n await attempt(report.identities, name, async () =>\n tombstone(name, await absent(client.identities.get(name)), (id) => client.identities.delete(id), dryRun),\n );\n }\n}\n\n/** The crew this apply provisioned, named in the report whenever the config declares it. */\nconst applied = (config: Readonly<ProjectConfig>) => ({\n ...(config.blueprint !== undefined ? { blueprint: config.blueprint } : {}),\n ...(config.template !== undefined ? { template: config.template } : {}),\n});\n\n/**\n * The switch rule (ADR-0389): a template switch WIDENS and never narrows. An agent the previous\n * template declared and this one does not is named in the report and left exactly as it is — the\n * same thing that already happens to a resource dropped from the config, said out loud so the\n * operator can see what the old crew left behind and retire it themselves with `removed`.\n */\nfunction reportKept(config: Readonly<ProjectConfig>, live: Agent[], into: ResourceReport[]): void {\n const by = config.template === undefined ? \"this template\" : `template \"${config.template}\"`;\n for (const name of config.kept.agents) {\n const current = live.find((agent) => agent.name === name);\n if (current !== undefined) into.push({ name, action: \"unchanged\", id: current.id, reason: `not declared by ${by}; kept, never deleted` });\n }\n}\n\n/**\n * Whether the agent's toolset grants a tool this app serves. An app's MCP tools reach the turn as\n * `<app>.<tool>` (§29.5) and only while the app is live, so a first message that sends the agent to\n * an app this run declined to create would only be the agent asking for tools that do not exist.\n */\nfunction reaches(decl: AgentDecl, app: string): boolean {\n return Object.entries(decl.tools?.configs ?? {}).some(\n ([name, one]) => name.startsWith(`${app}.`) && one.enabled && one.permission !== \"deny\",\n );\n}\n\n/** Plan → apply → report. Every refusal is one line in the report, never a thrown escape. */\nexport async function up(\n config: Readonly<ProjectConfig>,\n client: VettaClient,\n opts: UpOptions = {},\n): Promise<UpReport> {\n const dryRun = opts.dry_run ?? false;\n const dir = opts.dir ?? process.cwd();\n const ids: Ids = { apps: new Map(), identities: new Map() };\n // Judged before the first read: a selection that is wrong is the caller's to fix, not a report line.\n const taken = selectCrew(config, opts.select);\n const report: UpReport = { dry_run: dryRun, ...applied(config), skills: [], identities: [], vaults: [], apps: [], agents: [], schedules: [], intake: [], tasks: [], skipped: [], deselected: taken.deselected };\n // The stamp every app in this run is judged against is the config's own name (ADR-0375).\n const owner: Owner = { project: config.name, adopt: opts.adopt ?? false, skipped: report.skipped };\n const project = opts.project ?? config.name;\n const isolated = opts.isolated === true ? project : undefined;\n // Skills and identities first: agents reference both by name.\n // `trees` is present exactly when this apply runs where there is no checkout (`UpOptions`).\n const hosted = opts.trees !== undefined;\n for (const decl of config.skills) {\n await attempt(report.skills, decl.slug, () => upsertSkill(client, decl, { dryRun, dir, hosted, skills: opts.skills ?? {} }));\n }\n for (const decl of config.identities) {\n await attempt(report.identities, decl.name, () => upsertIdentity(client, decl, dryRun, ids.identities, isolated));\n const identityId = ids.identities.get(decl.name);\n report.identities.push(...(await reportLegal(client, decl.legal ?? [], identityId, report.skipped)));\n for (const wallet of decl.wallet === undefined ? [] : Array.isArray(decl.wallet) ? decl.wallet : [decl.wallet]) {\n await attempt(report.identities, walletName(decl.name, wallet), () =>\n reconcileWallet(client, { name: decl.name, id: identityId }, wallet, dryRun),\n );\n }\n await reconcileCards(client, decl.name, identityId, decl.cards ?? [], dryRun, report.identities, report.skipped);\n }\n // Vaults have no by-name lookup; one list serves every upsert and tombstone below.\n const vaults =\n config.vaults.length > 0 || config.removed.vaults.length > 0\n ? await listAll(client.config, \"/v1/vaults\", VaultSchema, report.skipped)\n : [];\n for (const decl of config.vaults) {\n const line = await attempt(report.vaults, decl.name, () => upsertVault(client, decl, vaults, ids.identities, dryRun));\n const vaultId = line.action === \"unchanged\" ? line.id : undefined;\n const rows =\n vaultId === undefined\n ? []\n : await listAll(client.config, `/v1/vaults/${vaultId}/credentials`, VaultCredentialSchema, report.skipped);\n for (const cred of decl.credentials) {\n await attempt(report.vaults, `${decl.name} / ${cred.key}`, () =>\n upsertCredential(client, line, cred, rows, dryRun, opts.env ?? process.env),\n );\n }\n }\n // After the identities, because one of the platform's known values is an identity this run made.\n // The install's project is another: it is the row the app's `/api/context` looks up, and a hosted\n // apply files it under the customer's slug, not the declaration's name.\n const platform = opts.platform && {\n ...opts.platform,\n known: {\n ...opts.platform.known,\n [PLATFORM_ENV.project]: project,\n ...identityEnv(config, ids.identities),\n },\n };\n // Together, filed in declaration order: one app's create, secrets and build wait share nothing\n // with the next app's, and a hosted install was paying each build's wait once per app.\n report.apps.push(\n ...(await eachInFlight(taken.apps, (decl) =>\n line(\n decl.name,\n () =>\n upsertApp(\n client,\n decl,\n {\n ...owner,\n dryRun,\n dir,\n trees: opts.trees,\n tree_errors: opts.tree_errors,\n migrations: opts.migrations,\n env: opts.env ?? process.env,\n platform,\n },\n ids.apps,\n ),\n // The app's id is recorded the moment it exists — before its secrets and deploy — so a\n // failure in that upload reports `refused` naming the created app, not one the operator\n // cannot find. A pre-create refusal (an unset `from_env`, a missing tree) has set nothing.\n () => ids.apps.get(decl.name),\n ),\n )),\n );\n const existing =\n taken.agents.length > 0 || config.removed.agents.length > 0 || config.kept.agents.length > 0 || config.tasks.length > 0\n ? await listAll(client.config, \"/v1/agents\", AgentSchema, report.skipped)\n : [];\n const deployments = taken.agents.some((decl) => decl.schedules !== undefined)\n ? await listAll(client.config, \"/v1/deployments\", DeploymentSchema, report.skipped)\n : [];\n /**\n * The apps THIS project provisioned, which is what its agents may reach — see `upsertAgent`.\n * `undefined` when the declaration declares none at all, because scoping an agent to an empty\n * list would be a removal by omission; empty when every declared app was refused, because an\n * agent must not be handed tool names for an app this run declined to create.\n */\n const scoped = config.apps.length > 0 ? [...ids.apps.values()] : undefined;\n // Each agent with its own timers, the crew together: an agent is keyed by its name and its\n // schedules by its id, so nothing one member writes is read by the next.\n const crew = await eachInFlight(taken.agents, async (decl) => {\n const of = { project, ...applied(config), adopt: opts.adopt ?? false, ...(isolated === undefined ? {} : { group: project }) };\n const agent = await line(decl.name, () => upsertAgent(client, decl, existing, ids, dryRun, scoped, of));\n const schedules: ResourceReport[] = [];\n if (decl.schedules !== undefined) {\n await reconcileSchedules(client, agent, decl.schedules, deployments, ids.identities, dryRun, schedules);\n }\n return { decl, agent, schedules };\n });\n const briefed: [ResourceReport, NonNullable<AgentDecl[\"intake\"]>][] = [];\n // A dry run creates no app, so it has nothing to hold against a briefing.\n // Every app the DECLARATION names, not the ones the selection kept: a deselected app is as\n // absent from this run as a refused one, and `reaches()` must be asked about it too (§31.4).\n const unbuilt = dryRun ? [] : config.apps.map((decl) => decl.name).filter((name) => !ids.apps.has(name));\n for (const { decl, agent, schedules } of crew) {\n report.agents.push(agent);\n report.schedules.push(...schedules);\n // `created` is the whole condition (§31.4): the agent that already existed was briefed on the\n // apply that made it, and a refused one has nothing to brief.\n if (decl.intake === undefined || agent.action !== \"created\") continue;\n const needs = unbuilt.find((app) => reaches(decl, app));\n if (needs === undefined) briefed.push([agent, decl.intake]);\n else report.intake.push({ name: decl.name, action: \"refused\", reason: `needs app \"${needs}\", which was not provisioned in this run` });\n }\n // Pass two (§31.6): every agent of the declaration now has an id, so a roster's names can become them.\n const agentIds = new Map(existing.map((agent) => [agent.name, agent.id]));\n for (const line of report.agents) if (line.id !== undefined) agentIds.set(line.name, line.id);\n for (const decl of config.agents) {\n if (hasRoster(decl.multiagent)) await patchRoster(client, decl, decl.multiagent, existing, agentIds, dryRun, report.agents);\n }\n reportKept(config, existing, report.agents);\n // The crew has its ids and its owner's board can seat it (§31.11); the cards it seeds are woken by\n // the API's tick, so an intake below still finds every card of this apply already on the board.\n if (config.tasks.length > 0) await seedTasks(client, config, existing, report.agents, dryRun, report.tasks, report.skipped);\n await applyRemoved(client, config.removed, { agents: existing, vaults }, owner, report);\n // Last, after every write: an intake is the only thing `up` does that makes an agent act, and a\n // crew member that delegates (§28) or reaches for an app must find the rest of the apply landed —\n // including the app's own MCP endpoint answering, which `ready` alone does not promise.\n if (briefed.length > 0 && !dryRun) {\n const serving = taken.apps.flatMap((decl) => {\n const url = report.apps.find((one) => one.name === decl.name)?.url;\n return decl.mcp !== undefined && typeof url === \"string\" ? [url + decl.mcp] : [];\n });\n await awaitServing(serving, opts.probe ?? globalThis.fetch);\n }\n report.intake.push(\n ...(await eachInFlight(briefed, ([agent, decl]) => line(agent.name, () => openIntake(client, agent, decl, dryRun)))),\n );\n return report;\n}\n","/**\n * Apps in `naive up`: upsert by `GET /v1/apps?name=` (§29.2), `env` written as write-only secrets\n * only when the live `value_hash` differs from the local one (ADR-0354, ADR-0357), and the\n * `deploy_dir` shipped only when its content hash differs from the newest live deployment's\n * (ADR-0357). Live secret names the config does not declare are reported, never deleted\n * (ADR-0352). `mcp` is patched on drift, absent meaning `null` (§29.5); the platform mints the\n * app's `VETTA_MCP_TOKEN` itself, so nothing here ever holds that token.\n *\n * A hosted apply also arrives with a PLATFORM ENVIRONMENT (`PlatformEnv`, §29.7) — the base URL, the\n * identity the install runs as, and a scoped key it will mint for an app that asks. That layer is\n * read before `{ from_env }`'s own environment, and a declaration may ask for a value nobody has\n * with `{ generate: true }`. Both are provisioned ONCE per app, because a value the platform invents\n * has no stable digest and rewriting it every apply would rotate a live credential.\n *\n * An app also records the project that made it (ADR-0375), and that stamp is compared before any\n * write: a name this project does not own is refused rather than adopted, which is what standing\n * up a second blueprint did to the first one's live deployment.\n */\nimport type { AppCreate, VettaClient } from \"@usenaive-sdk/vetta\";\nimport { AppSchema, type App } from \"@vetta/core\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { resolve } from \"node:path\";\n// core-gaps: storage-stock\nimport { applyBuckets } from \"./buckets\";\nimport type { AppDecl } from \"./define\";\nimport { collectFiles, contentHash } from \"./files\";\n// core-gaps: U8-database\nimport { applyMigrations, declaredMigrations, type MigrationFile } from \"./migrations\";\nimport { eachInFlight, listAll, type ResourceAction, type ResourceReport } from \"./report\";\n\n/** What every app in one run is judged against: the config's own `name`, and `naive up --adopt`. */\nexport interface Owner {\n project: string;\n adopt: boolean;\n /** Rows the engine could not read (`report.ts`), collected rather than thrown. */\n skipped: string[];\n}\n\n/** `GET /v1/apps?name=` — the by-name lookup that makes app upsert idempotent (§29.2). */\nexport async function findApp(client: VettaClient, name: string, skipped: string[]): Promise<App | null> {\n const rows = await listAll(client.config, \"/v1/apps\", AppSchema, skipped, { name });\n return rows.find((app) => app.name === name) ?? null;\n}\n\n/**\n * ADR-0375's refusal, and the one place its wording lives — upserts and `removed` tombstones read\n * the same predicate, because deleting another project's app is worse than overwriting it.\n */\nexport function ownershipRefusal(name: string, project: string, owner: string | null, kind: \"app\" | \"agent\" | \"identity\" = \"app\"): string {\n const held = owner === null ? \"no project (it was created outside a blueprint)\" : `project \"${owner}\"`;\n const verb = owner === null ? \"take\" : \"transfer\";\n return `${kind} \"${name}\" is owned by ${held}; this project is \"${project}\". Rename the ${kind} in your config, or re-run \\`naive up --adopt\\` to ${verb} it.`;\n}\n\n/**\n * `POST /v1/apps` is the ensure, and the only door provenance moves through (§29.2): a create\n * stamps `project`, and `adopt: true` on a name another project owns transfers the stamp. Widened\n * over the SDK's `AppCreate`, which does not name the two fields yet; when it does, the\n * intersection is redundant and this alias collapses to `AppCreate`.\n */\ntype AppEnsure = AppCreate & { project: string; adopt?: boolean };\nconst ensureApp = (client: VettaClient, body: AppEnsure) => client.apps.create(body);\n\n/** The platform environment's variable names (`canonical-spec §29.7`) — fixed, never inferred. */\nexport const PLATFORM_ENV = {\n /** The base URL of the API this apply ran through. */\n api_url: \"NAIVE_API_URL\",\n /** The identity the install runs as, when the declaration declares exactly one. */\n identity_id: \"NAIVE_IDENTITY_ID\",\n /** The install's `project` — the row the app's own context lookup lands on (§31.8). */\n project: \"NAIVE_PROJECT\",\n /** The base URL of the Studio that installed the app, so it can send a signed-out visitor back. */\n studio_url: \"NAIVE_STUDIO_URL\",\n /** The app's own `app_…` id — the one known value learnt from the row, not from the apply. */\n app_id: \"NAIVE_APP_ID\",\n /** A scoped organization API key minted for the app that asks for it. */\n api_key: \"NAIVE_API_KEY\",\n} as const;\n\n/** The one generated name a *person* types, so it is shaped for a person (§29.7, ADR-0656). */\nconst DASHBOARD_PASSWORD = \"DASHBOARD_PASSWORD\";\n\n/**\n * WHAT THE PLATFORM PROVIDES A HOSTED APPLY, AND THE ONE DISTINCTION THAT MATTERS\n * (`canonical-spec §29.7`).\n *\n * Absent on a laptop apply, which reads the author's shell and nothing else — the hosted path gains\n * a layer, the local path does not lose one.\n *\n * **What the platform KNOWS it always tells the app; what the platform must INVENT it invents only\n * on request, and only once.** That is not a stylistic split. A known value has a stable digest, so\n * the `value_hash` compare that makes `naive up` idempotent (§29.2) can say `unchanged` about it and\n * re-asserting it every apply costs nothing. An invented one never matches its own previous digest,\n * so re-inventing it every apply would rotate a live credential under a build that still holds the\n * old one — and, for a minted key, leave one dead `api_key` row behind per apply.\n */\nexport interface PlatformEnv {\n /**\n * Values the platform knows. Written to every app this apply deploys that declares an `env` —\n * whether or not the declaration names them, which is the `VETTA_MCP_TOKEN` precedent (§29.2) —\n * and read FIRST by a `{ from_env }` that does name them.\n */\n known: Record<string, string>;\n /**\n * Values the platform must invent, by variable name, given the app that asked. Called at most\n * once per app, and only when that app holds no secret of that name.\n */\n minted?: Record<string, (app: string) => Promise<string>>;\n}\n\n/**\n * One declared variable, resolved as far as it can be BEFORE the app is read.\n *\n * The split is what keeps the refusal where it has always been. Anything genuinely missing — a\n * `{ from_env }` no layer supplies — throws out of `planEnv`, before the first request, so an app is\n * never half-written. Only the *invented* values wait, because whether to invent one is a question\n * about the live app that this apply has not asked yet.\n */\ninterface Planned {\n name: string;\n /** Known now: a literal, an answer, the author's shell, or a value the platform holds. */\n value?: string;\n /** Invented, and therefore provisioned once: a generated secret or a minted key. */\n invent?: () => Promise<string>;\n}\n\n/**\n * `{ from_env }` reads the environment the apply is running in, so a value never sits in the config\n * file. An unset variable refuses the app before any write — naming the variable, never a value.\n *\n * WHICH ENVIRONMENT depends on where the apply runs, and there are two. On a laptop or in CI it is\n * the author's shell, which is what `opts.env` defaults to. A hosted apply has no shell: it is\n * given the **platform environment** (`PlatformEnv`, §29.7) layered over the **answers** the\n * operator typed into the setup questions before anything was provisioned (§31.2). Platform first,\n * answers second, refuse third — because none of `NAIVE_API_KEY`, `DASHBOARD_TOKEN`,\n * `NAIVE_API_URL` or `NAIVE_IDENTITY_ID` is a thing an operator has to give, and asking for one is\n * how a hosted install came to provision a crew and never its dashboard.\n */\nfunction planEnv(decl: AppDecl, opts: AppOptions): Planned[] {\n if (decl.env === undefined) return [];\n const plan = new Map<string, Planned>();\n for (const [name, value] of Object.entries(decl.env)) {\n if (typeof value === \"string\") {\n plan.set(name, { name, value });\n continue;\n }\n if (\"generate\" in value) {\n plan.set(name, { name, invent: async () => (name === DASHBOARD_PASSWORD ? generatedPassword() : generatedSecret()) });\n continue;\n }\n const known = opts.platform?.known[value.from_env];\n const mint = opts.platform?.minted?.[value.from_env];\n if (known !== undefined) plan.set(name, { name, value: known });\n else if (mint !== undefined) plan.set(name, { name, invent: () => mint(decl.name) });\n else {\n const local = opts.env[value.from_env];\n if (local === undefined) throw new Error(`env ${name} reads local variable ${value.from_env}, which is not set`);\n plan.set(name, { name, value: local });\n }\n }\n // Last, so a known platform value wins over a literal or an answer of the same name: it is the\n // address of the API this apply just provisioned against, and a declaration that disagrees points\n // the app at a platform that is not holding its agents.\n for (const [name, value] of Object.entries(opts.platform?.known ?? {})) plan.set(name, { name, value });\n return [...plan.values()];\n}\n\n/**\n * The plan, made real. `held` is the set of secret names the live app already carries — empty for an\n * app about to be created — and it is the whole of the provision-once rule: an invented value the\n * app already holds is not re-invented and not written, so it is not rotated under a running build.\n * Rotation is by hand (`DELETE …/secrets/{name}`, then apply again), the §29.2 `mcp` idiom.\n *\n * `--dry-run` must not mint a key or generate a token — planning is a read. So an invented value the\n * app does not already hold is NAMED (`unmade`) and not made, and the plan line still says it would\n * be set.\n */\nasync function materialize(\n plan: Planned[],\n held: ReadonlySet<string>,\n dryRun: boolean,\n): Promise<{ values: Record<string, string>; unmade: string[] }> {\n const values: Record<string, string> = {};\n const unmade: string[] = [];\n for (const one of plan) {\n if (one.value !== undefined) values[one.name] = one.value;\n else if (held.has(one.name)) continue;\n else if (dryRun) unmade.push(one.name);\n else values[one.name] = await invent(one);\n }\n return { values, unmade };\n}\n\n/**\n * A value the platform could not invent refuses this app **by variable name**, exactly as an unset\n * one does. A mint is a real request that can be turned down — a caller that does not hold the\n * scopes the key carries does not get one minted on its behalf — and a missing scope on its own\n * does not tell an operator which of their app's variables went without.\n */\nasync function invent(one: Planned): Promise<string> {\n try {\n return await one.invent!();\n } catch (cause) {\n throw new Error(\n `env ${one.name} is provisioned by the platform, and could not be: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n}\n\n/** A value nobody has: 256 bits, URL-safe, no alphabet an app secret or a header would mangle. */\nexport const generatedSecret = (): string => randomBytes(32).toString(\"base64url\");\n\n/** Lowercase and digits with nothing a person misreads: no `0`/`o`, no `1`/`l`/`i`. */\nconst PASSWORD_ALPHABET = \"abcdefghjkmnpqrstuvwxyz23456789\";\nconst PASSWORD_GROUPS = 4;\nconst PASSWORD_GROUP_LENGTH = 4;\n\n/**\n * `kq7m-x2rt-8bvn-pz4h`: four groups of four from a 31-letter alphabet, 16·log2(31) ≈ 79 bits. Each\n * character is drawn by rejection sampling so the alphabet is used evenly — a modulo over 256 would\n * not be.\n */\nexport function generatedPassword(): string {\n const limit = 256 - (256 % PASSWORD_ALPHABET.length);\n const groups: string[] = [];\n let group = \"\";\n while (groups.length < PASSWORD_GROUPS) {\n for (const byte of randomBytes(PASSWORD_GROUPS * PASSWORD_GROUP_LENGTH * 2)) {\n if (byte >= limit) continue;\n group += PASSWORD_ALPHABET[byte % PASSWORD_ALPHABET.length];\n if (group.length === PASSWORD_GROUP_LENGTH) {\n groups.push(group);\n group = \"\";\n if (groups.length === PASSWORD_GROUPS) break;\n }\n }\n }\n return groups.join(\"-\");\n}\n\n/**\n * `NAIVE_APP_ID` is known, but only once the row exists — so it joins the environment here, after\n * the create or the read, rather than in `planEnv`. Written on the same terms as the other known\n * values: every hosted app that declares an `env`, named or not.\n */\nfunction withAppId(env: Record<string, string>, decl: AppDecl, opts: AppOptions, id: string): Record<string, string> {\n if (decl.env === undefined || opts.platform === undefined) return env;\n return { ...env, [PLATFORM_ENV.app_id]: id };\n}\n\n/** An app about to be created holds nothing. */\nconst EMPTY: ReadonlySet<string> = new Set();\n\n/**\n * The digest sent as the secret's `value_hash` (§29.2): sha-256 over `name NUL value`, hex. A\n * fingerprint, not the value — it lets the next apply see \"the value I hold is the value I last\n * wrote\" without any route ever returning one.\n */\nfunction secretHash(name: string, value: string): string {\n return createHash(\"sha256\").update(`${name}\\0`).update(value).digest(\"hex\");\n}\n\ninterface Tree {\n files: Record<string, string>;\n hash: string;\n}\n\n/**\n * The tree as it would ship, hashed once so it can be held against the newest live deployment.\n *\n * Two sources, one function, because there are two places an apply runs from (`files.ts`). A\n * **directory** is the apply a person runs on a checkout. A **built tree** is the apply the\n * platform runs on their behalf: the bytes come out of a published artifact and there is no\n * checkout anywhere, so `opts.trees` is present and the disk is not.\n *\n * When `trees` is given it is the ONLY source — no silent fall back to `deploy_dir` on a disk that\n * does not exist. An app the declaration says to deploy and the artifact published no tree for is\n * refused by name, before any write, rather than created empty and reported as deployed.\n */\nfunction builtTree(decl: AppDecl, opts: AppOptions): Tree | null {\n if (!decl.deploy_dir) return null;\n const hosted = opts.trees;\n if (hosted !== undefined && hosted[decl.name] === undefined) {\n // Two very different facts wear the same words unless the caller says which. \"No tree was\n // published for this app\" sends an operator to the publisher; \"the object is there and the read\n // of it failed\" sends them to the object store, and telling them the first when it is the\n // second costs them the whole investigation. So the caller that did the reading passes what\n // went wrong (`tree_errors`), and it is named here rather than swallowed.\n const failed = opts.tree_errors?.[decl.name];\n throw new Error(\n `app \"${decl.name}\" declares deploy_dir \"${decl.deploy_dir}\", but this apply was handed no built tree for it` +\n (failed === undefined ? \"\" : `: ${failed}`),\n );\n }\n const files = collectFiles(hosted?.[decl.name] ?? resolve(opts.dir, decl.deploy_dir));\n return { files, hash: contentHash(files) };\n}\n\n/**\n * Secrets before the deploy, so the build that follows runs with the declared environment.\n *\n * Then wait for it. A build is asynchronous and the app's lasting hostname is only assigned when\n * one goes live, so an apply that returns the moment the upload lands reports `url: null` and\n * leaves the platform holding no address for the app — which is also the address a declared `mcp`\n * endpoint is resolved against (§29.5). Deployments advance on read, so reading is the wait.\n */\nasync function writeApp(client: VettaClient, id: string, env: Record<string, string>, tree: Tree | null) {\n // Concurrently: each secret is one full round trip through the API and no declared value depends\n // on another, so writing them in sequence made a hosted install pay that latency once per\n // variable — measured on staging at 3.0-3.7 s each, under 350 ms of which was the hosting\n // provider. The deploy below still waits for every one of them, which is the ordering that\n // matters: the build must run with the declared environment already in place.\n await eachInFlight(Object.entries(env), ([name, value]) =>\n client.apps.setSecret(id, { name, value, value_hash: secretHash(name, value) }),\n );\n if (!tree) return;\n await client.apps.deploy(id, tree.files, tree.hash);\n await settleDeploy(client, id);\n}\n\n/** Bounded: a build that outlasts it is still building, and the next apply reads it again. */\nconst SETTLE_TRIES = 30;\nconst SETTLE_MS = 4_000;\n\nasync function settleDeploy(client: VettaClient, id: string): Promise<void> {\n for (let poll = 0; poll < SETTLE_TRIES; poll++) {\n const newest = (await client.apps.deployments(id, { limit: 1 })).data[0];\n if (newest === undefined || newest.status === \"ready\" || newest.status === \"error\") return;\n await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));\n }\n}\n\nasync function createApp(\n client: VettaClient,\n decl: AppDecl,\n env: Record<string, string>,\n tree: Tree | null,\n migrations: MigrationFile[],\n opts: AppOptions,\n appIds: Map<string, string>,\n): Promise<ResourceReport> {\n const created = await ensureApp(client, {\n name: decl.name,\n type: decl.type,\n project: opts.project,\n ...(decl.description !== undefined ? { description: decl.description } : {}),\n ...(decl.mcp !== undefined ? { mcp: decl.mcp } : {}),\n });\n appIds.set(decl.name, created.id);\n await writeApp(client, created.id, withAppId(env, decl, opts, created.id), tree);\n const notes: string[] = [];\n if (migrations.length > 0) notes.push((await applyMigrations(client, created.id, migrations)).note);\n if (decl.buckets !== undefined) notes.push((await applyBuckets(client, created.id, decl.buckets)).note);\n // Re-read: the hostname is assigned by the build `writeApp` just waited on, not by create.\n return {\n name: decl.name,\n action: \"created\",\n id: created.id,\n url: (await client.apps.get(created.id)).url,\n ...(notes.length > 0 ? { reason: notes.join(\"; \") } : {}),\n };\n}\n\nexport interface AppOptions extends Owner {\n dryRun: boolean;\n /** Base directory `deploy_dir` is resolved against — the config file's directory. */\n dir: string;\n /**\n * Built trees by app name, for an apply that has no checkout (`up.ts`). Present ⇒ the disk is not\n * consulted at all; absent ⇒ `dir` + `deploy_dir` is the source, as it always was.\n */\n trees?: Record<string, Record<string, string>> | undefined;\n /**\n * Why an app's tree is missing from `trees`, by app name, when the caller knows. Only a caller\n * that fetched them can distinguish an object nobody uploaded from one whose read failed, and the\n * refusal above is the only place an operator ever sees either.\n */\n tree_errors?: Record<string, string> | undefined;\n /** core-gaps: U8-database — each app's published migrations, by name, under a hosted apply (`migrations.ts`). */\n migrations?: Record<string, MigrationFile[]> | undefined;\n /** What `{ from_env }` reads. The author's shell by default; a hosted apply's answers instead. */\n env: Record<string, string | undefined>;\n /**\n * What the PLATFORM provides, read before `env` and written whether or not the declaration names\n * it (`PlatformEnv`, `canonical-spec §29.7`). Present only on a hosted apply.\n */\n platform?: PlatformEnv | undefined;\n}\n\n/**\n * An app whose row names another project — or no project at all — is **refused before any write**\n * (ADR-0375), unless `--adopt` takes it; adoption stamps the row through the ensure and reports\n * `updated` with the transfer as its reason.\n *\n * Secret values are write-only (§29.2): nothing reads one back. Drift is judged by `value_hash`,\n * the client digest the list route echoes — a declared name is (re-)set only when its live hash\n * differs from the local one, so an untouched app is honestly `unchanged`. The list also names\n * live secrets the config does not declare; those are reported, never deleted (ADR-0352).\n *\n * A `deploy_dir` ships only when its hash differs from the newest live deployment's `content_hash`\n * (ADR-0357): equal means the site is `unchanged` and nothing is uploaded; a deployment made\n * without a hash (`null`) can never match, so it is redeployed once and carries one from then on.\n */\nexport async function upsertApp(\n client: VettaClient,\n decl: AppDecl,\n opts: AppOptions,\n appIds: Map<string, string>,\n): Promise<ResourceReport> {\n // Planned before the first request, so a variable no layer supplies still refuses this app before\n // anything is written — naming the variable and never a value (`planEnv`).\n const declared = planEnv(decl, opts);\n const writesAppId = decl.env !== undefined && opts.platform !== undefined;\n const names = [...declared.map((one) => one.name), ...(writesAppId ? [PLATFORM_ENV.app_id] : [])];\n const note = (notes: string[]) => (notes.length > 0 ? { reason: notes.join(\"; \") } : {});\n const mcpPlan = decl.mcp !== undefined ? [`will set mcp ${decl.mcp}`] : [];\n const migrationPlan = decl.migrations !== undefined ? [`will apply migrations ${decl.migrations.join(\", \")}`] : [];\n const bucketPlan = decl.buckets !== undefined ? [`will ensure buckets ${decl.buckets.map((one) => one.name).join(\", \")}`] : [];\n const current = await findApp(client, decl.name, opts.skipped);\n if (!current) {\n const willSet = names.length > 0 ? [`will set ${names.join(\", \")}`] : [];\n if (opts.dryRun) {\n return {\n name: decl.name,\n action: \"created\",\n ...note([...willSet, ...mcpPlan, ...(decl.deploy_dir ? [`will deploy ${decl.deploy_dir}`] : []), ...migrationPlan, ...bucketPlan]),\n };\n }\n // Resolved before the create, not inside it: a tree that cannot be read refuses the app\n // rather than leaving a created, empty one behind (`builtTree`). A new app holds no secrets,\n // so every invented value is invented here — once, on the apply that made the app.\n const { values } = await materialize(declared, EMPTY, false);\n return createApp(client, decl, values, builtTree(decl, opts), declaredMigrations(decl, opts), opts, appIds);\n }\n // Ownership is compared before `appIds` and before every write, so `--dry-run` tells the truth\n // and a refused app is neither half-written nor wired into an agent's `allowed_apps` (§29.3).\n const owned = current.project === opts.project;\n if (!owned && !opts.adopt) {\n return {\n name: decl.name,\n action: \"refused\",\n id: current.id,\n reason: ownershipRefusal(decl.name, opts.project, current.project),\n };\n }\n appIds.set(decl.name, current.id);\n if (current.type !== decl.type) {\n return {\n name: decl.name,\n action: \"refused\",\n id: current.id,\n reason: `app \"${decl.name}\" exists as ${current.type} and type cannot change; delete it or declare type \"${current.type}\"`,\n };\n }\n // The ensure is what writes the stamp — the update path never POSTs — so adoption happens here,\n // once, before the writes it authorises.\n const from = current.project === null ? \"(previously unowned)\" : `from project \"${current.project}\"`;\n const adoption = owned ? [] : [`${opts.dryRun ? \"will adopt\" : \"adopted\"} ${from}`];\n if (!owned && !opts.dryRun) {\n await ensureApp(client, { name: decl.name, type: decl.type, project: opts.project, adopt: true });\n }\n const live = declared.length === 0 ? [] : (await client.apps.secrets(current.id)).data;\n // Judged against what the config DECLARES, not against what this apply resolved: an invented value\n // the app already holds is deliberately left out of `env`, and calling it unmanaged would tell an\n // operator their own minted key was set by someone else.\n const managed = new Set(names);\n const unmanaged = live.map((secret) => secret.name).filter((name) => !managed.has(name));\n const held = new Map(live.map((secret) => [secret.name, secret.value_hash]));\n const { values, unmade } = await materialize(declared, new Set(held.keys()), opts.dryRun);\n const env = withAppId(values, decl, opts, current.id);\n // A live hash equal to the local one means the value stands as declared; a null (set before\n // hashes existed, or by hand) never matches, so it is rewritten once and carries one from then on.\n const staleEnv = Object.fromEntries(\n Object.entries(env).filter(([name, value]) => held.get(name) !== secretHash(name, value)),\n );\n const staleNames = [...Object.keys(staleEnv), ...unmade];\n // An undeclared `mcp` is `null` on the wire: dropping it from the config clears the endpoint\n // and forgets its token, the way a dropped resource is removed rather than left behind.\n const patch = {\n ...(decl.description !== undefined && decl.description !== current.description ? { description: decl.description } : {}),\n ...((decl.mcp ?? null) !== current.mcp ? { mcp: decl.mcp ?? null } : {}),\n };\n const drifted = Object.keys(patch).length > 0;\n const tree = builtTree(decl, opts);\n const newest = tree ? (await client.apps.deployments(current.id, { limit: 1 })).data[0] : undefined;\n const stale = tree !== null && newest?.content_hash !== tree.hash;\n let action: ResourceAction = !owned || drifted || stale || staleNames.length > 0 ? \"updated\" : \"unchanged\";\n const plan = opts.dryRun\n ? [\n ...(staleNames.length > 0 ? [`will set ${staleNames.join(\", \")}`] : []),\n ...(\"mcp\" in patch ? (patch.mcp === null ? [\"will clear mcp\"] : mcpPlan) : []),\n ...(decl.deploy_dir ? [stale ? `will deploy ${decl.deploy_dir}` : `${decl.deploy_dir} unchanged`] : []),\n ...migrationPlan,\n ...bucketPlan,\n ]\n : [];\n if (!opts.dryRun) {\n // The server guards the ensure AND the patch by project (ADR-0388), so the patch has to say\n // which project is speaking or it is refused on every drift of an app we ourselves stamped.\n if (drifted) await client.apps.update(current.id, { ...patch, project: opts.project });\n await writeApp(client, current.id, staleEnv, stale ? tree : null);\n // Migrations are idempotent by name (§37), so every apply re-runs the list and the note says\n // how many were new; an app that only gained one is `updated`.\n const migrations = declaredMigrations(decl, opts);\n if (migrations.length > 0) {\n const { fresh, note } = await applyMigrations(client, current.id, migrations);\n if (fresh > 0) action = \"updated\";\n plan.push(note);\n }\n // Buckets likewise: a missing one is made, a held one is left as it is, and nothing is deleted.\n if (decl.buckets !== undefined) {\n const { fresh, note } = await applyBuckets(client, current.id, decl.buckets);\n if (fresh > 0) action = \"updated\";\n plan.push(note);\n }\n }\n return {\n name: decl.name,\n action,\n id: current.id,\n // Re-read only when a build actually ran: a dry run issues no call at all.\n url: !opts.dryRun && stale ? (await client.apps.get(current.id)).url : current.url,\n ...note([...adoption, ...plan, ...(unmanaged.length > 0 ? [`unmanaged secrets: ${unmanaged.join(\", \")}`] : [])]),\n };\n}\n","/**\n * core-gaps: storage-stock — `apps[].buckets` in `naive up` (`canonical-spec §38.2`). A declared\n * bucket the app's object store lacks is created with the declared `public`; one it already holds is\n * left exactly as it is, `public` included, because flipping visibility on a bucket that is serving\n * URLs is a decision for a person. Nothing is ever deleted: a bucket dropped from the config, or made\n * by the app's own code, stays. `DELETE …/storage/buckets/{bucket}` is the only way one goes.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\n\nexport interface BucketDecl {\n name: string;\n public: boolean;\n}\n\n/** One list, then one create per missing name; `fresh` counts the ones that were made. */\nexport async function applyBuckets(\n client: VettaClient,\n appId: string,\n buckets: readonly BucketDecl[],\n): Promise<{ fresh: number; note: string }> {\n const live = new Set((await client.storage.buckets.list({ app: appId })).data.map((row) => row.name));\n const missing = buckets.filter((bucket) => !live.has(bucket.name));\n for (const bucket of missing) await client.storage.buckets.create(bucket.name, { app: appId, public: bucket.public });\n return { fresh: missing.length, note: `${buckets.length} bucket(s), ${missing.length} new` };\n}\n","/**\n * core-gaps: U8-database — `apps[].migrations` in `naive up` (`canonical-spec §37`). Each entry is a\n * path under the config's directory, with `*` allowed in the file name (`sql/*.sql`); files match\n * in name order within one entry and entries in declaration order, so `0001_…`, `0002_…` is the\n * whole ordering story. A file's migration name is its base name without the extension, and\n * `POST /v1/apps/{id}/db/migrations` applies each once: a replay is a no-op, changed SQL under a\n * kept name is `409 version_conflict`, which the report carries by name.\n *\n * A hosted apply has no checkout: the publisher read the files and shipped them on the app's built\n * tree (`canonical-spec §31.1`), so they arrive as `opts.migrations` by app name.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { readFileSync, readdirSync } from \"node:fs\";\nimport { basename, dirname, extname, join, resolve } from \"node:path\";\nimport type { AppDecl } from \"./define\";\n\nexport interface MigrationFile {\n name: string;\n sql: string;\n}\n\n/** `*` matches within one path segment; anything else in the pattern is literal. */\nfunction matcher(pattern: string): (name: string) => boolean {\n const source = pattern\n .split(\"*\")\n .map((part) => part.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n .join(\"[^/]*\");\n const regex = new RegExp(`^${source}$`);\n return (name) => regex.test(name);\n}\n\n/** The files each pattern names, in order, each read once; a pattern that names nothing refuses. */\nexport function migrationFiles(patterns: readonly string[], dir: string): MigrationFile[] {\n const seen = new Set<string>();\n const files: MigrationFile[] = [];\n for (const pattern of patterns) {\n const full = resolve(dir, pattern);\n const paths = pattern.includes(\"*\")\n ? readdirSync(dirname(full), { withFileTypes: true })\n .filter((entry) => entry.isFile() && matcher(basename(full))(entry.name))\n .map((entry) => join(dirname(full), entry.name))\n .sort()\n : [full];\n if (paths.length === 0) throw new Error(`migrations \"${pattern}\" matches no file under ${dir}`);\n for (const path of paths) {\n const name = basename(path, extname(path));\n if (seen.has(name)) continue;\n seen.add(name);\n files.push({ name, sql: readFileSync(path, \"utf8\") });\n }\n }\n return files;\n}\n\n/**\n * The SQL an app declares, read before any write so an unreadable file refuses the app whole. Under\n * a hosted apply (`trees` present) the disk is never read: an artifact published before the SQL\n * rode the tree carries none, and the app is refused by name rather than created unmigrated.\n */\nexport function declaredMigrations(\n decl: AppDecl,\n opts: { dir: string; trees?: object | undefined; migrations?: Record<string, MigrationFile[]> | undefined },\n): MigrationFile[] {\n if (decl.migrations === undefined) return [];\n if (opts.trees === undefined) return migrationFiles(decl.migrations, opts.dir);\n const published = opts.migrations?.[decl.name];\n if (published === undefined) {\n throw new Error(\n `app \"${decl.name}\" declares migrations, but this apply was handed no published SQL for it. Republish the artifact, or apply them with \\`naive up\\` from a clone.`,\n );\n }\n return published;\n}\n\n/** Applies in order; `fresh` counts the ones the app had not seen, and a refused one throws by name. */\nexport async function applyMigrations(\n client: VettaClient,\n appId: string,\n files: readonly MigrationFile[],\n): Promise<{ fresh: number; note: string }> {\n const applied = new Set((await client.database.migrations({ app: appId })).map((row) => row.name));\n for (const file of files) await client.database.migrate(file.name, file.sql, { app: appId });\n const fresh = files.filter((file) => !applied.has(file.name)).length;\n return { fresh, note: `${files.length} migration(s), ${fresh} new` };\n}\n","/**\n * Agents in `naive up`: upsert by name with a drift-only PATCH, `allowed_apps` names resolved to\n * app ids in the `apps` tool config (§29.3), the platform config passthrough (`system`, `skills`,\n * `mcp_servers`) verbatim, and `identity` attached after the upsert, never revoked (ADR-0353).\n *\n * An agent's `schedules` are the one bounded exception to \"nothing is deleted by omission\"\n * (ADR-0355): deployments have no name, so the declared list is owned as a **complete set** keyed\n * by exact `cron`. Matched rows are patched where other fields drifted, missing crons are created,\n * and the agent's rows whose cron is not declared are deleted. The prune reaches only deployments\n * of agents this blueprint declares with `schedules`; an agent without the key keeps whatever it has.\n *\n * **The match is the cron STRING, not the schedule it denotes.** `\"0 8 * * 1\"` and `\"0 08 * * 1\"`\n * fire at the same minute and are two different keys: re-spelling a declared cron is read as the\n * declared one being absent and an undeclared one being live, so it is a DELETE plus a CREATE, not\n * a PATCH. The new row is a new `dep_` id with a fresh `next_run_at`, and whatever the old row's\n * `enabled: false` was holding back is gone. Nothing here parses cron — a client that normalised\n * the string would have to agree with the server's parser forever to stay idempotent, and the day\n * they disagreed every apply would churn every schedule. Edit a cron and expect a new deployment.\n */\nimport type { AgentPatch, DeploymentPatch, VettaClient } from \"@usenaive-sdk/vetta\";\nimport { handoffsEnabled, handoffsOf, normaliseMultiagent, type Agent, type Deployment, type Toolset } from \"@vetta/core\";\nimport type { AgentDecl, ScheduleDecl } from \"./define\";\nimport { attempt, changed, eachInFlight, line, tombstone, type ResourceReport } from \"./report\";\nimport { ownershipRefusal } from \"./apps\";\nimport { teamWithoutRoster } from \"./roster\";\n\n/** Declared-name → live id for the resources agents reference by name. */\nexport interface Ids {\n apps: Map<string, string>;\n identities: Map<string, string>;\n}\n\n/** The install an agent belongs to (`canonical-spec §31.8`): what its `metadata` names, when a template made it. */\nexport interface Membership {\n project: string;\n blueprint?: string;\n template?: string;\n /** `naive up --adopt`: take a same-named agent another project, or none, owns (ADR-0785). */\n adopt?: boolean;\n /** What `metadata.group` files the crew under; the template when absent (ADR-1104). */\n group?: string;\n}\n\n/**\n * What every template agent's `system` opens with (§31.8): the one paragraph that turns the setup\n * answers into something the crew acts on. The `project_context` tool it names is offered only to\n * an agent whose metadata names a project with an applied install — exactly the agents this is\n * prepended for.\n */\nexport const PROJECT_CONTEXT_PREAMBLE =\n \"Before anything else, read the project context with the `project_context` tool. The answers in it \" +\n \"are the client's own — never invent, assume or restate them from memory; what the context does not \" +\n \"say, you ask. Use the context's own words for the company, its offer and its audience.\";\n\n/** `metadata` for a template agent — the declared keys over what the live row carries, the membership over both; the declaration's alone outside a template. */\nfunction desiredMetadata(decl: AgentDecl, of: Membership, current: Agent | null): Record<string, unknown> | undefined {\n if (of.template === undefined) return decl.metadata;\n return {\n ...current?.metadata,\n ...decl.metadata,\n project: of.project,\n ...(of.blueprint !== undefined ? { blueprint: of.blueprint } : {}),\n template: of.template,\n group: of.group ?? of.template,\n };\n}\n\n/**\n * The declared `system`, opened with the preamble when a template made this agent. Computed from\n * the declaration alone and never from the live row, so a re-apply compares the same string it\n * wrote last time and stacks nothing.\n */\nfunction desiredSystem(decl: AgentDecl, of: Membership): string | undefined {\n if (of.template === undefined) return decl.system;\n return decl.system === undefined ? PROJECT_CONTEXT_PREAMBLE : `${PROJECT_CONTEXT_PREAMBLE}\\n\\n${decl.system}`;\n}\n\n/**\n * `allowed_apps` on the wire is app ids in the `apps` tool's config (`canonical-spec §29.3`);\n * the blueprint declares app *names*, resolved here. `ids` is `undefined` when nothing scopes this\n * agent, and then the toolset the config (or the live agent) already carries is left alone.\n */\nfunction desiredTools(\n decl: AgentDecl,\n current: Agent | null,\n ids: string[] | undefined,\n): Toolset | undefined {\n // A declared `handoffs` (§31.7) is the whole grant: the agent tools run `allow`, because a handoff\n // runs unattended; who they reach is the `handoffs` field itself, not a config here.\n const handoff = decl.handoffs !== undefined && handoffsEnabled(decl.handoffs);\n if (ids === undefined && !handoff) return decl.tools;\n const base: Toolset = decl.tools ??\n current?.tools ?? { default_config: { permission: \"allow\" }, configs: {} };\n const appsTool = base.configs[\"apps\"] ?? { enabled: true, permission: base.default_config.permission };\n const allowed = { enabled: true, permission: \"allow\" } as const;\n return {\n default_config: base.default_config,\n configs: {\n ...base.configs,\n ...(ids !== undefined ? { apps: { ...appsTool, config: { ...appsTool.config, allowed_apps: ids } } } : {}),\n ...(handoff ? { send_to_agent: allowed, list_agents: allowed } : {}),\n },\n };\n}\n\nasync function createAgent(\n client: VettaClient,\n decl: AgentDecl,\n tools: Toolset | undefined,\n team: boolean | null | undefined,\n identityId: string | undefined,\n system: string | undefined,\n metadata: Record<string, unknown> | undefined,\n): Promise<ResourceReport> {\n const created = await client.agents.create({\n name: decl.name,\n model: decl.model,\n budget: decl.budget,\n ...(decl.description !== undefined ? { description: decl.description } : {}),\n ...(system !== undefined ? { system } : {}),\n ...(decl.skills !== undefined ? { skills: decl.skills } : {}),\n ...(decl.mcp_servers !== undefined ? { mcp_servers: decl.mcp_servers } : {}),\n ...(tools !== undefined ? { tools } : {}),\n ...(decl.window !== undefined ? { window: decl.window } : {}),\n ...(team !== undefined ? { multiagent: team } : {}),\n ...(decl.handoffs !== undefined ? { handoffs: decl.handoffs } : {}),\n ...(decl.output_schema !== undefined ? { output_schema: decl.output_schema } : {}),\n ...(decl.structured_output_required !== undefined ? { structured_output_required: decl.structured_output_required } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n });\n if (identityId !== undefined) await client.identities.attach(created.id, identityId);\n return { name: decl.name, action: \"created\", id: created.id };\n}\n\n/**\n * *** WHAT AN AGENT MAY REACH IS THIS PROJECT'S APPS, NOT THE ORGANIZATION'S. ***\n *\n * `allowed_apps` absent means \"every app in the organization\" (`canonical-spec §29.3`), which is\n * the right default for an agent somebody wrote by hand and the wrong one for a crew a blueprint\n * declares. Measured: the media crew's first unattended run, session\n * `ses_p3t7rbns376ky36tjztp95yb9f` off its 07:00 producer cron, read its four `channel.*` tools\n * and then called `dashboard.list_clients` — an app belonging to `seo-geo-agency`, an unrelated\n * blueprint installed in the same organization — and parked on `awaiting_approval` with nobody\n * there to approve. 56,849 µUSD, no video. The media blueprint's `default_config` is\n * `permission: \"ask\"`, so a sibling project's whole MCP namespace arrives as a question rather than\n * as a refusal, and its own comment's claim that the leftover \"can only be a tool from an account\n * this channel connected\" is simply false.\n *\n * So a declaration that declares apps scopes the agents it declares to those apps: `scoped` is the\n * ids this run actually provisioned. `undefined` — a declaration with no apps at all — keeps the\n * old behaviour rather than locking such an agent out of apps it was using before this ran, which\n * would be a silent removal by omission (ADR-0355).\n *\n * An app that was REFUSED is not in `scoped`, which is deliberate and is the other half of the\n * hosted-apply problem: granting `<app>.<tool>` for an app the same run declined to create hands\n * the crew a tool surface that does not exist.\n */\nexport async function upsertAgent(\n client: VettaClient,\n decl: AgentDecl,\n existing: Agent[],\n ids: Ids,\n dryRun: boolean,\n scoped: string[] | undefined,\n of: Membership,\n): Promise<ResourceReport> {\n const unresolved = (decl.allowed_apps ?? []).filter((name) => !ids.apps.has(name));\n const identityId = decl.identity === undefined ? undefined : ids.identities.get(decl.identity);\n // Define-time validation pins these to declared resources, so at apply time a miss only means\n // the app or identity itself was refused above — the agent must not silently widen to \"all\n // apps\" (§29.3) or quietly run as nobody (§22).\n const missing =\n unresolved.length > 0\n ? `allowed_apps needs app \"${unresolved[0]}\"`\n : decl.identity !== undefined && identityId === undefined\n ? `identity needs \"${decl.identity}\"`\n : null;\n if (missing !== null && !dryRun) {\n return { name: decl.name, action: \"refused\", reason: `${missing}, which was not provisioned in this run` };\n }\n const appIds =\n decl.allowed_apps !== undefined\n ? decl.allowed_apps.flatMap((name) => ids.apps.get(name) ?? [])\n : scoped;\n const current = existing.find((agent) => agent.name === decl.name) ?? null;\n /**\n * ADR-0785, the apps rule (ADR-0375) for agents. Adoption was by bare name, so installing a\n * template into a company that already had an `analyst` rewrote that agent's prompt, tools and\n * budget — and a second channel from the same template took over the first one's crew. A\n * template agent carries its project; one that names ANOTHER is refused. An untagged agent is\n * still tagged, because template agents from before the stamp (2026-09-09) carry none.\n */\n const owner = typeof current?.metadata?.[\"project\"] === \"string\" ? current.metadata[\"project\"] : null;\n if (current && of.template !== undefined && owner !== null && owner !== of.project && !of.adopt) {\n return { name: decl.name, action: \"refused\", id: current.id, reason: ownershipRefusal(decl.name, of.project, owner, \"agent\") };\n }\n const tools = desiredTools(decl, current, appIds);\n // A roster is resolved to ids in pass two (`roster.ts`), once every crew member has one.\n const team = teamWithoutRoster(decl.multiagent);\n const system = desiredSystem(decl, of);\n const metadata = desiredMetadata(decl, of, current);\n if (!current) {\n return dryRun ? { name: decl.name, action: \"created\" } : createAgent(client, decl, tools, team, identityId, system, metadata);\n }\n const patch = drift(decl, current, tools, team, system, metadata);\n // The grant is attach-only here: `identity` says what the agent may act as, never what to revoke.\n const held = identityId === undefined ? [] : (await client.identities.held(current.id)).data;\n const grant = identityId === undefined || held.some((one) => one.id === identityId) ? null : identityId;\n const drifted = Object.keys(patch).length > 0 || missing !== null || grant !== null;\n if (!drifted) return { name: decl.name, action: \"unchanged\", id: current.id };\n if (!dryRun) {\n if (Object.keys(patch).length > 0) await client.agents.update(current.id, patch);\n if (grant !== null) await client.identities.attach(current.id, grant);\n }\n return { name: decl.name, action: \"updated\", id: current.id };\n}\n\n/** Every declared field that differs from the live agent; an undeclared one is never drift (§31.6). */\nfunction drift(\n decl: AgentDecl,\n current: Agent,\n tools: Toolset | undefined,\n team: boolean | null | undefined,\n system: string | undefined,\n metadata: Record<string, unknown> | undefined,\n): AgentPatch {\n const patch: AgentPatch = {};\n if (changed(decl.model, current.model)) patch.model = decl.model;\n if (changed(decl.budget, current.budget)) patch.budget = decl.budget;\n if (changed(decl.description, current.description)) patch.description = decl.description;\n if (changed(system, current.system)) patch.system = system;\n if (changed(decl.skills, current.skills)) patch.skills = decl.skills;\n if (changed(decl.mcp_servers, current.mcp_servers)) patch.mcp_servers = decl.mcp_servers;\n if (changed(tools, current.tools)) patch.tools = tools;\n if (changed(decl.window, current.window)) patch.window = decl.window;\n if (team !== undefined && changed(normaliseMultiagent(team), normaliseMultiagent(current.multiagent))) patch.multiagent = team;\n // A live agent from before §28.15 carries no `handoffs`; it reads as `true`, so declaring `true` is not drift.\n if (changed(decl.handoffs, handoffsOf(current))) patch.handoffs = decl.handoffs;\n if (changed(decl.output_schema, current.output_schema)) patch.output_schema = decl.output_schema;\n if (changed(decl.structured_output_required, current.structured_output_required)) patch.structured_output_required = decl.structured_output_required;\n if (changed(metadata, current.metadata)) patch.metadata = metadata;\n return patch;\n}\n\n/**\n * The intake (`canonical-spec §31.4`): the first thing an agent reads, on the apply that **created**\n * it and on no other. `POST /v1/sessions` creates *and* starts in one call with `message` as the\n * first user turn (§7) — exactly what a cron fire already does with `deployment.input_template`,\n * pointed for the first time at a newly created agent.\n *\n * **That is the whole idempotency story.** An agent is created exactly once, so `upsertAgent`\n * answers `created` exactly once and a second `naive up` reports `unchanged` and starts nothing.\n * There is no marker column and no metadata flag, so there is nothing to go stale, nothing to\n * migrate and nothing to disagree with the agent's own existence. Delete the agent and re-apply and\n * it intakes again, which is the correct reading of \"this agent is new\".\n *\n * `budget_micro_usd` is optional and absent means the agent's own `budget` governs, so it is\n * omitted from the body rather than sent as a null.\n */\nexport async function openIntake(\n client: VettaClient,\n agent: ResourceReport,\n decl: NonNullable<AgentDecl[\"intake\"]>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n // No id yet means a dry-run `created` agent: the session it would open is planned, not started.\n if (dryRun || agent.id === undefined) return { name: agent.name, action: \"created\" };\n const started = await client.sessions.create({\n agent_id: agent.id,\n message: decl.message,\n ...(decl.budget_micro_usd !== undefined ? { budget_micro_usd: decl.budget_micro_usd } : {}),\n });\n return { name: agent.name, action: \"created\", id: started.id };\n}\n\n/**\n * `identity` on the wire is echoed as an `idn_` id whatever was written (§12), so drift compares\n * the resolved id. A schedule of an agent that was refused is refused with it, and one whose\n * identity was not provisioned is refused rather than created to run as nobody (§22).\n */\n/** The opening sentence of a timer's brief, short enough to sit in a list beside its time. */\nfunction brief(input: string): string {\n const first = input.trim().split(/(?<=[.!?])\\s|\\n/)[0]?.trim() ?? \"\";\n const text = first.replace(/[.\\s]+$/, \"\");\n return text.length > 72 ? `${text.slice(0, 71).trimEnd()}…` : text;\n}\n\nasync function upsertSchedule(\n client: VettaClient,\n agent: ResourceReport,\n decl: ScheduleDecl,\n current: Deployment | undefined,\n identityIds: Map<string, string>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n const name = `${agent.name} @ ${decl.cron}`;\n if (agent.action === \"refused\") throw new Error(`agent \"${agent.name}\" was not provisioned in this run`);\n const identity = decl.identity === undefined ? undefined : identityIds.get(decl.identity);\n const unresolved = decl.identity !== undefined && identity === undefined;\n if (unresolved && !dryRun) throw new Error(`identity needs \"${decl.identity}\", which was not provisioned in this run`);\n if (!current) {\n // No id yet means a dry-run `created` agent — every declared cron would be created with it.\n if (dryRun || agent.id === undefined) return { name, action: \"created\" };\n const created = await client.deployments.create({\n agent_id: agent.id,\n cron: decl.cron,\n input_template: decl.input,\n budget_micro_usd: decl.budget_micro_usd,\n ...(decl.timezone !== undefined ? { timezone: decl.timezone } : {}),\n ...(identity !== undefined ? { identity } : {}),\n ...(decl.enabled !== undefined ? { enabled: decl.enabled } : {}),\n });\n return { name, action: \"created\", id: created.id };\n }\n const patch: DeploymentPatch = {};\n if (changed(decl.timezone, current.timezone)) patch.timezone = decl.timezone;\n if (changed(decl.input, current.input_template)) patch.input_template = decl.input;\n if (changed(decl.budget_micro_usd, current.budget_micro_usd)) patch.budget_micro_usd = decl.budget_micro_usd;\n if (changed(identity, current.identity)) patch.identity = identity;\n if (changed(decl.enabled, current.enabled)) patch.enabled = decl.enabled;\n if (Object.keys(patch).length === 0 && !unresolved) return { name, action: \"unchanged\", id: current.id };\n if (!dryRun) await client.deployments.update(current.id, patch);\n return { name, action: \"updated\", id: current.id };\n}\n\n/** The complete-set reconcile from the header: upsert each declared cron, then prune the agent's rest. */\nexport async function reconcileSchedules(\n client: VettaClient,\n agent: ResourceReport,\n declared: ScheduleDecl[],\n live: Deployment[],\n identityIds: Map<string, string>,\n dryRun: boolean,\n into: ResourceReport[],\n): Promise<void> {\n const rows = live.filter((row) => row.agent_id === agent.id);\n // Concurrently: a declared timer is one write keyed by its own cron and shares nothing with the\n // next, so arming them in sequence made a crew pay the request latency once per timer — measured\n // on staging at 4.4-4.8 s apiece, none of it the provider's. `line` rather than `attempt` because\n // the report is filed in DECLARATION order, not in the order the server happened to answer.\n into.push(\n ...(await eachInFlight(declared, async (decl) => ({\n ...(await line(`${agent.name} @ ${decl.cron}`, () =>\n upsertSchedule(client, agent, decl, rows.find((row) => row.cron === decl.cron), identityIds, dryRun),\n )),\n // `<agent> @ <cron>` says WHEN a timer runs and nothing about what it does, so the dashboard's\n // opening message could only ever draw a timetable from these lines. The brief's first\n // sentence is what turns that timetable into a roadmap (§29.6).\n summary: decl.summary ?? brief(decl.input),\n }))),\n );\n // A refused agent's id, when it has one, is ANOTHER project's agent (ADR-0785): its timers are not ours to prune.\n if (agent.action === \"refused\") return;\n for (const row of rows.filter((row) => !declared.some((decl) => decl.cron === row.cron))) {\n const name = `${agent.name} @ ${row.cron}`;\n await attempt(into, name, () => tombstone(name, row, (id) => client.deployments.delete(id), dryRun));\n }\n}\n","/**\n * `identities[].cards[]` in `naive up` (`canonical-spec §45.5`): presence by `label`. A live card\n * with the declared label that is still `pending_payment | issuing | active` is `unchanged`; one\n * that has ended its life (`failed | cancelled | refunded`) is `refused`, never re-bought; and only\n * a label with no card at all is issued through `POST /v1/identities/{id}/cards`, which debits\n * credits. A prepaid card cannot be reloaded, so there is no drift to patch — only present or not\n * — and nothing here ever cancels, refunds or re-buys. `--dry-run` quotes instead of issuing and\n * says what it would cost, so the operator sees the credits before they move.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { CardSchema, decimalStringFromMicro, microUsd, type Card, type CardStatus, type IssueCard } from \"@vetta/core\";\nimport { attempt, listAll, type ResourceReport } from \"./report\";\n\nconst LIVE: ReadonlySet<CardStatus> = new Set([\"pending_payment\", \"issuing\", \"active\"]);\n\n/** `<identity> / card <label>` — one line per declared card, filed under the identity's report. */\nconst nameOf = (identity: string, decl: IssueCard): string => `${identity} / card ${decl.label}`;\n\nasync function upsertCard(\n client: VettaClient,\n identityId: string,\n decl: IssueCard,\n live: Card[],\n dryRun: boolean,\n name: string,\n): Promise<ResourceReport> {\n const current = live.find((card) => card.label === decl.label && LIVE.has(card.status));\n if (current) return { name, action: \"unchanged\", id: current.id };\n // A card with this label that has already been through its life is NOT re-bought. `up` runs on\n // every deploy: re-issuing would debit credits and place a fresh order once per run against a\n // card the issuer keeps refusing, and would buy back one the customer deliberately cancelled.\n // Presence by label means \"declared once\", not \"buy until one sticks\" — see this file's header.\n const spent = live.find((card) => card.label === decl.label);\n if (spent) {\n return { name, action: \"refused\", id: spent.id, reason: `a card labelled \"${decl.label}\" is ${spent.status}; issue a replacement by hand` };\n }\n if (dryRun) {\n const quote = await client.identities.cards.quote(identityId, { load_micro_usd: decl.load_micro_usd });\n const price = decimalStringFromMicro(microUsd(quote.price_micro_usd));\n return { name, action: \"created\", reason: `would debit ${price} USD of credits (${quote.price_micro_usd} micro-USD)` };\n }\n const issued = await client.identities.cards.issue(identityId, decl);\n return { name, action: \"created\", id: issued.id };\n}\n\n/**\n * Every declared card of one identity, in declaration order. `identityId` is `undefined` when the\n * identity does not exist yet: on a dry run that is the plan (each card `created`, the price left\n * to the apply that makes the identity); on an apply it means the identity was refused, and so is\n * every card that would hang off it.\n */\nexport async function reconcileCards(\n client: VettaClient,\n identity: string,\n identityId: string | undefined,\n decls: readonly IssueCard[],\n dryRun: boolean,\n into: ResourceReport[],\n skipped: string[],\n): Promise<void> {\n if (decls.length === 0) return;\n if (identityId === undefined) {\n for (const decl of decls) {\n into.push(\n dryRun\n ? { name: nameOf(identity, decl), action: \"created\", reason: \"quoted once the identity exists; issuing debits credits\" }\n : { name: nameOf(identity, decl), action: \"refused\", reason: `identity \"${identity}\" was not provisioned in this run` },\n );\n }\n return;\n }\n const live = await listAll(client.config, `/v1/identities/${identityId}/cards`, CardSchema, skipped);\n for (const decl of decls) {\n const name = nameOf(identity, decl);\n await attempt(into, name, () => upsertCard(client, identityId, decl, live, dryRun, name));\n }\n}\n","/**\n * `identities[].legal` under `up` (`workstreams/12 §8`, canonical-spec §43): a company the identity\n * should hold, keyed by `label`, **reported and never provisioned**. A hosted identity check needs a\n * person on the other end and a formation debits the organization's credits, so a repo cannot be\n * the one that starts either. `up` reads what exists — the case status, whether a company matching\n * a declared name option exists and how far along it is — and refuses the rest with the command a\n * person runs to move it.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport {\n canonicalName,\n LegalCompanySchema,\n LegalVerificationSchema,\n type LegalCompany,\n type LegalVerification,\n} from \"@vetta/core\";\nimport type { IdentityDecl } from \"./define\";\nimport { listAll, type ResourceReport } from \"./report\";\n\nexport type LegalDecl = NonNullable<IdentityDecl[\"legal\"]>[number];\n\nconst FILE = \"vetta identity legal form\";\nconst VERIFY = \"vetta identity legal verify\";\n\n/** Newest case first: the one a person is working on is the one the report should name. */\nfunction latest(\n cases: readonly LegalVerification[],\n): LegalVerification | undefined {\n return [...cases].sort((a, b) => b.created_at.localeCompare(a.created_at))[0];\n}\n\n/** A live company whose state and one name option match the declaration. */\nfunction match(\n decl: LegalDecl,\n companies: readonly LegalCompany[],\n): LegalCompany | undefined {\n const wanted = new Set(\n decl.name_options.map((raw) => canonicalName(raw).name),\n );\n return companies.find(\n (c) =>\n c.state === decl.state && c.name_options.some((o) => wanted.has(o.name)),\n );\n}\n\nfunction report(\n decl: LegalDecl,\n company: LegalCompany | undefined,\n verification: LegalVerification | undefined,\n): ResourceReport {\n const name = decl.label;\n if (company !== undefined) {\n const reason =\n company.status === \"failed\"\n ? `failed: ${company.failure_reason ?? \"the filing was rejected\"}`\n : company.status;\n return {\n name,\n action: company.status === \"failed\" ? \"refused\" : \"unchanged\",\n id: company.id,\n reason,\n };\n }\n if (verification === undefined)\n return {\n name,\n action: \"refused\",\n reason: `no verification case — a person must start one with \\`${VERIFY}\\``,\n };\n if (verification.status === \"verified\") {\n return {\n name,\n action: \"refused\",\n id: verification.id,\n reason: `verified; the fee is debited from credits, so a person files it with \\`${FILE}\\``,\n };\n }\n return {\n name,\n action: \"refused\",\n id: verification.id,\n reason: `verification ${verification.status}; nothing to file yet`,\n };\n}\n\n/**\n * One line per declared company. Only reads: `up` issues no POST here, in a dry run or a real one.\n * An identity this run has not created yet has nothing to read, so every line is a refusal naming\n * the first move.\n */\nexport async function reportLegal(\n client: VettaClient,\n decls: readonly LegalDecl[],\n identityId: string | undefined,\n skipped: string[],\n): Promise<ResourceReport[]> {\n if (decls.length === 0) return [];\n if (identityId === undefined)\n return decls.map((decl) => report(decl, undefined, undefined));\n const base = `/v1/identities/${identityId}/legal`;\n const [companies, cases] = await Promise.all([\n listAll(client.config, `${base}/companies`, LegalCompanySchema, skipped),\n listAll(\n client.config,\n `${base}/verifications`,\n LegalVerificationSchema,\n skipped,\n ),\n ]);\n return decls.map((decl) =>\n report(decl, match(decl, companies), latest(cases)),\n );\n}\n","/**\n * `tasks` in `naive up` (`canonical-spec §31.11`): the crew's first work, seeded as cards on the\n * organization's board rather than sent as N private intakes. Three ensures, in order — the board's\n * owner (the standing orchestrator, `metadata.role: \"orchestrator\"`, created as `CEO` when absent\n * and never renamed) with the crew on its roster and `board: true`; its board; one card per task\n * under the key `<project>:<task.key>`, which is what makes a re-apply answer the same card.\n *\n * Nothing here starts a session. A `todo` card with an assignee and no open blocker is *due*, and\n * the API's tick (§28.18) wakes the assignee — which is the whole point: a crew that starts from\n * the board it will keep working from, with the work, its owner and its order durable from day one.\n */\nimport { ApiError, type VettaClient } from \"@usenaive-sdk/vetta\";\nimport { BoardCardSchema, normaliseMultiagent, type Agent, type Multiagent } from \"@vetta/core\";\nimport { BlueprintRefusal, inDependencyOrder, type ProjectConfig } from \"./define\";\nimport { changed, line, listAll, type ResourceReport } from \"./report\";\n\n/** The seat the dashboard's Hire page creates (`apps/web/app/lib/orchestrator.server.ts`): same marker, same shape, so the two never make two. */\nconst ORCHESTRATOR_MARKER = \"orchestrator\";\nconst CEO_LABEL = \"CEO\";\nconst CEO_DETAIL = \"Hires and directs the crew\";\nconst CEO_BUDGET = { cap_micro_usd: 50_000_000, max_task_micro_usd: 5_000_000, period: \"month\" as const };\n\nconst isOrchestrator = (agent: Agent): boolean => agent.metadata[\"role\"] === ORCHESTRATOR_MARKER;\n\n/** The owner's team as the board needs it: whatever roster it had, this crew seated after, board on. */\nfunction seated(live: Multiagent | null, members: readonly string[]): Multiagent {\n const roster = live?.agents ?? [];\n const already = new Set(roster.flatMap((entry) => (entry.type === \"agent\" ? [entry.id] : [])));\n const joining = members.filter((id) => !already.has(id)).map((id) => ({ type: \"agent\" as const, id }));\n return { type: \"coordinator\", board: true, agents: [...roster, ...joining] };\n}\n\n/** One line, handled like any other agent: `created` as CEO, `updated` when the crew joins its roster, else `unchanged`. */\nasync function ensureOrchestrator(client: VettaClient, existing: Agent[], members: readonly string[], dryRun: boolean): Promise<ResourceReport> {\n const current = existing.find(isOrchestrator);\n const live = current === undefined ? null : normaliseMultiagent(current.multiagent);\n const team = seated(live, members);\n if (current === undefined) {\n if (dryRun) return { name: CEO_LABEL, action: \"created\" };\n const model = (await client.models.list({ window: \"immediate\", limit: 1 })).data[0];\n if (model === undefined) throw new BlueprintRefusal(\"no model is served, so the board's owner cannot be created\");\n const made = await client.agents.create({\n name: CEO_LABEL,\n harness: \"pi\",\n model: model.id,\n description: CEO_DETAIL,\n budget: CEO_BUDGET,\n metadata: { role: ORCHESTRATOR_MARKER },\n multiagent: team,\n });\n return { name: CEO_LABEL, action: \"created\", id: made.id };\n }\n if (live !== null && !changed(team, live)) return { name: current.name, action: \"unchanged\", id: current.id };\n if (dryRun) return { name: current.name, action: \"updated\", id: current.id };\n try {\n await client.agents.update(current.id, { multiagent: team });\n } catch (error) {\n // A CEO a vault credential is bound to is an admin's to change (ADR-1097), and a CEO turn's\n // token never is (ADR-1100). Its board is its role's, not its roster's, and a card's assignee is\n // woken by name — so the cards need nothing changed here, and the owner stands as it was (ADR-1134).\n if (!(error instanceof ApiError && error.status === 403)) throw error;\n return { name: current.name, action: \"unchanged\", id: current.id, reason: `crew not seated on its roster: ${error.message} (request ${error.requestId})` };\n }\n return { name: current.name, action: \"updated\", id: current.id };\n}\n\n/**\n * The owner's line joins `agents`; one line per task joins `tasks`. Cards are written one after\n * another in dependency order because a card's `blocked_by` carries the ids the earlier creates\n * answered. `created` or `unchanged` is read off the board: the card's id was, or was not, on it\n * before this apply wrote. A dry run plans every card as `created` — a card carries no key on the\n * wire, so which ones a re-apply would find is only known by writing.\n */\nexport async function seedTasks(\n client: VettaClient,\n config: Readonly<ProjectConfig>,\n existing: Agent[],\n agents: ResourceReport[],\n dryRun: boolean,\n into: ResourceReport[],\n skipped: string[],\n): Promise<void> {\n const members = agents.flatMap((one) => (one.id === undefined ? [] : [one.id]));\n const owner = await line(CEO_LABEL, () => ensureOrchestrator(client, existing, members, dryRun));\n agents.push(owner);\n const board = owner.action === \"refused\" || dryRun || owner.id === undefined ? null : await client.board.create(owner.id);\n const before = board === null ? [] : await listAll(client.config, `/v1/boards/${board.id}/cards`, BoardCardSchema, skipped);\n const known = new Set(before.map((card) => card.id));\n const ids = new Map<string, string>();\n for (const task of inDependencyOrder(config.tasks)) {\n into.push(\n await line(task.key, async () => {\n if (owner.action === \"refused\") return { name: task.key, action: \"refused\", reason: `board owner \"${owner.name}\" was refused: ${owner.reason}` };\n const assignee = task.assignee;\n if (assignee !== undefined && !agents.some((one) => one.name === assignee && one.action !== \"refused\")) {\n return { name: task.key, action: \"refused\", reason: `assignee \"${assignee}\" was not provisioned in this run` };\n }\n if (board === null) return { name: task.key, action: \"created\" };\n const blockers = task.blocked_by ?? [];\n const unmet = blockers.find((key) => !ids.has(key));\n if (unmet !== undefined) return { name: task.key, action: \"refused\", reason: `blocked_by \"${unmet}\" was not seeded in this run` };\n const card = await client.board.cards.create(board.id, {\n key: `${config.name}:${task.key}`,\n title: task.title,\n body: task.body,\n assignee,\n blocked_by: blockers.map((key) => ids.get(key)!),\n });\n ids.set(task.key, card.id);\n // The title and the seat ride the line: `name` is the key a re-apply matches on, and the\n // dashboard's opening message needs the words the board actually shows (§29.6).\n return {\n name: task.key,\n action: known.has(card.id) ? \"unchanged\" : \"created\",\n id: card.id,\n title: task.title,\n ...(assignee === undefined ? {} : { assignee }),\n };\n }),\n );\n }\n}\n","/**\n * Vaults in `naive up` (ADR-0356): upsert by `display_name` from one list (no by-name route, no\n * update route — `identity` is fixed at create), then credentials by **presence** on\n * `(kind, key, host / mcp_server_url)`. Values are write-only and rows immutable (§23), so a live\n * credential is `unchanged`, a missing one is created from the author's shell, and nothing live is\n * ever deleted or overwritten here; rotation stays create-new + delete-old on the platform.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport type { Vault, VaultCredential } from \"@vetta/core\";\nimport type { CredentialDecl, VaultDecl } from \"./define\";\nimport type { ResourceReport } from \"./report\";\n\n/**\n * Vaults have no update route, so `identity` is fixed at create: a live vault held by another\n * identity is refused rather than silently kept, the way an app's `type` is.\n */\nexport async function upsertVault(\n client: VettaClient,\n decl: VaultDecl,\n existing: Vault[],\n identityIds: Map<string, string>,\n dryRun: boolean,\n): Promise<ResourceReport> {\n const identityId = decl.identity === undefined ? undefined : identityIds.get(decl.identity);\n if (decl.identity !== undefined && identityId === undefined && !dryRun) {\n return { name: decl.name, action: \"refused\", reason: `identity needs \"${decl.identity}\", which was not provisioned in this run` };\n }\n const current = existing.find((vault) => vault.display_name === decl.name);\n if (!current) {\n if (dryRun) return { name: decl.name, action: \"created\" };\n const created = await client.vaults.create({\n display_name: decl.name,\n ...(identityId !== undefined ? { identity_id: identityId } : {}),\n });\n return { name: decl.name, action: \"created\", id: created.id };\n }\n if (identityId !== undefined && current.identity_id !== identityId) {\n return {\n name: decl.name,\n action: \"refused\",\n id: current.id,\n reason: `vault \"${decl.name}\" belongs to another identity and that cannot change; remove it or declare the identity it has`,\n };\n }\n return { name: decl.name, action: \"unchanged\", id: current.id };\n}\n\n/**\n * Presence, not drift: with no readable value and no update route, a live row with the declared\n * (kind, key, host / mcp_server_url) *is* the credential. The value is read from the author's\n * shell only when a create is due, and an unset variable refuses that one credential — naming the\n * variable, never a value.\n */\nexport async function upsertCredential(\n client: VettaClient,\n vault: ResourceReport,\n decl: CredentialDecl,\n existing: VaultCredential[],\n dryRun: boolean,\n from: Record<string, string | undefined>,\n): Promise<ResourceReport> {\n const name = `${vault.name} / ${decl.key}`;\n if (vault.action === \"refused\") throw new Error(`vault \"${vault.name}\" was not provisioned in this run`);\n const current = existing.find(\n (row) =>\n row.kind === decl.kind &&\n row.key === decl.key &&\n row.host === (decl.host ?? null) &&\n row.mcp_server_url === (decl.mcp_server_url ?? null),\n );\n if (current) return { name, action: \"unchanged\", id: current.id };\n // `from`, NOT `process.env` — the same environment `apps.ts` resolves an app's `{ from_env }`\n // against, and for a stronger reason. In a Worker, `nodejs_compat` populates `process.env` from\n // the deploy's OWN vars and secrets, so a hosted apply reading it would resolve\n // `{ from_env: \"OPENROUTER_API_KEY\" }` to the PLATFORM's key and write it into a customer's vault\n // as their credential. On a laptop `from` is the author's shell and nothing changes.\n const value = from[decl.value.from_env];\n if (value === undefined) throw new Error(`credential ${decl.key} reads local variable ${decl.value.from_env}, which is not set`);\n if (dryRun || vault.id === undefined) return { name, action: \"created\" };\n const created = await client.vaults.credentials.create(vault.id, {\n kind: decl.kind,\n key: decl.key,\n value,\n ...(decl.host !== undefined ? { host: decl.host } : {}),\n ...(decl.mcp_server_url !== undefined ? { mcp_server_url: decl.mcp_server_url } : {}),\n });\n return { name, action: \"created\", id: created.id };\n}\n","/**\n * An identity's wallets in `naive up` (`canonical-spec §44.5`): each declaration IS\n * `POST /v1/identities/{id}/wallet`'s body and names one network (the testnet when it does not).\n * Created if absent on that network, its policy PATCHed when a declared cap differs, and nothing\n * else — `up` never funds, freezes or sweeps a wallet, and the persona's wallet on the other\n * network is never read or touched (money may be sitting in it).\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { DEFAULT_WALLET_NETWORK, type CreateWallet, type WalletPolicy } from \"@vetta/core\";\nimport { absent, changed } from \"./report\";\nimport type { ResourceReport } from \"./report\";\n\nconst declaredPolicy = (decl: CreateWallet, live: WalletPolicy): Partial<WalletPolicy> =>\n Object.fromEntries(\n Object.entries(decl.policy ?? {}).filter(([key, value]) => value !== undefined && changed(value, live[key as keyof WalletPolicy])),\n );\n\n/** `Ava / wallet` for the testnet one; a mainnet declaration carries its network so the two rows read apart. */\nexport const walletName = (identity: string, decl: CreateWallet): string =>\n decl.network === undefined || decl.network === DEFAULT_WALLET_NETWORK ? `${identity} / wallet` : `${identity} / wallet ${decl.network}`;\n\nexport async function reconcileWallet(\n client: VettaClient,\n identity: { name: string; id: string | undefined },\n decl: CreateWallet,\n dryRun: boolean,\n): Promise<ResourceReport> {\n const name = walletName(identity.name, decl);\n const network = decl.network ?? DEFAULT_WALLET_NETWORK;\n if (identity.id === undefined) {\n if (dryRun) return { name, action: \"created\" };\n return { name, action: \"refused\", reason: `identity \"${identity.name}\" was not provisioned in this run` };\n }\n const current = await absent(client.identities.wallet.get(identity.id, { network }));\n if (!current) {\n if (dryRun) return { name, action: \"created\" };\n const created = await client.identities.wallet.create(identity.id, decl);\n return { name, action: \"created\", id: created.id };\n }\n const patch = declaredPolicy(decl, current.policy);\n if (Object.keys(patch).length === 0) return { name, action: \"unchanged\", id: current.id };\n if (current.status !== \"active\") {\n return { name, action: \"refused\", id: current.id, reason: `wallet is ${current.status}; unfreeze it on the platform before changing its policy` };\n }\n if (!dryRun) await client.identities.wallet.updatePolicy(identity.id, patch, { network });\n return { name, action: \"updated\", id: current.id };\n}\n","/**\n * ONE TEMPLATE, TWICE IN ONE ORGANIZATION (`canonical-spec §29.6`, ADR-1104).\n *\n * Everything `up()` provisions is keyed by name in the organization, and ADR-0785 refuses a name\n * another project holds — so a second install of a template found every agent taken and hired no\n * one. An install that must share the organization with those names takes its own: every agent,\n * app, identity and vault name, and every reference to one, starts with the install's prefix. The\n * API decides the prefix once, when the install row is created, and passes it here on every apply.\n *\n * `config.name` becomes the install's `project`, so app ownership (ADR-0375), `NAIVE_PROJECT` and\n * the board's card keys (`<project>:<key>`) are the install's own and never another install's.\n *\n * Prose is not rewritten. A system prompt that says \"hand the script to the editor\" still says it;\n * the agent is told, in one generated line at the end of its `system`, what each name is here.\n */\nimport type { AgentDecl, ProjectConfig } from \"./define\";\nimport { hasRoster } from \"./roster\";\n\n/**\n * The config an install with `prefix` applies. `\"\"` renames nothing and only files it under `project`.\n * Skills stay shared by slug, so no install's `removed` deletes one another install's crew runs.\n */\nexport function scoped(config: Readonly<ProjectConfig>, prefix: string, project: string): ProjectConfig {\n const removed = { ...config.removed, skills: [] };\n if (prefix === \"\") return { ...config, name: project, removed };\n const as = (name: string): string => prefix + name;\n const apps = new Set(config.apps.map((app) => app.name));\n // An app's MCP tools are `<app>.<tool>` (§29.5); an app name is a DNS label, so it has no dot.\n const tool = (key: string): string => {\n const app = key.split(\".\")[0] ?? \"\";\n return key.includes(\".\") && apps.has(app) ? as(key) : key;\n };\n const team = teamLine(config, as);\n const agent = (decl: AgentDecl): AgentDecl => ({\n ...decl,\n name: as(decl.name),\n system: decl.system === undefined ? team : `${decl.system}\\n\\n${team}`,\n ...(decl.tools === undefined\n ? {}\n : { tools: { ...decl.tools, configs: Object.fromEntries(Object.entries(decl.tools.configs).map(([key, one]) => [tool(key), one])) } }),\n ...(decl.allowed_apps === undefined ? {} : { allowed_apps: decl.allowed_apps.map(as) }),\n ...(decl.identity === undefined ? {} : { identity: as(decl.identity) }),\n ...(Array.isArray(decl.handoffs) ? { handoffs: decl.handoffs.map(as) } : {}),\n ...(hasRoster(decl.multiagent)\n ? { multiagent: { ...decl.multiagent, agents: decl.multiagent.agents.map((one) => (one.type === \"agent\" ? { ...one, name: as(one.name) } : one)) } }\n : {}),\n ...(decl.schedules === undefined\n ? {}\n : { schedules: decl.schedules.map((one) => (one.identity === undefined ? one : { ...one, identity: as(one.identity) })) }),\n });\n return {\n ...config,\n name: project,\n identities: config.identities.map((one) => ({ ...one, name: as(one.name) })),\n vaults: config.vaults.map((one) => ({ ...one, name: as(one.name), ...(one.identity === undefined ? {} : { identity: as(one.identity) }) })),\n apps: config.apps.map((one) => ({ ...one, name: as(one.name) })),\n agents: config.agents.map(agent),\n tasks: config.tasks.map((one) => (one.assignee === undefined ? one : { ...one, assignee: as(one.assignee) })),\n removed: {\n ...removed,\n apps: config.removed.apps.map(as),\n agents: config.removed.agents.map(as),\n identities: config.removed.identities.map(as),\n vaults: config.removed.vaults.map(as),\n },\n kept: { agents: config.kept.agents.map(as) },\n };\n}\n\n/** The one line each agent is told: what every crew member and app of the template is called here. */\nfunction teamLine(config: Readonly<ProjectConfig>, as: (name: string) => string): string {\n const names = [\n ...config.agents.map((one) => `${one.name} is ${as(one.name)}`),\n ...config.apps.map((one) => `the app ${one.name} is ${as(one.name)} (its tools are ${as(one.name)}.*)`),\n ];\n return `Your team's names here: ${names.join(\"; \")}.`;\n}\n"],"mappings":";;;;;;AAqGA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,KAAK,aAAa,KAAK;AAkC/D,SAAS,KAAK,QAAkB,OAAwB;AAC7D,QAAMA,QAAO,GAAG,MAAM;AACtB,MAAI,CAAC,MAAM,WAAWA,KAAI,EAAG,QAAO;AACpC,SAAO,eAAe,KAAK,MAAM,MAAMA,MAAK,MAAM,EAAE,YAAY,CAAC;AACnE;;;AC/HA,IAAM,QAAQ;AAAA,EACZ,oBAAoB,CAAC,mBAAmB,GAAG;AAAA,EAC3C,mBAAmB,CAAC,mBAAmB,GAAG;AAAA,EAC1C,cAAc,CAAC,kBAAkB,GAAG;AAAA,EACpC,WAAW,CAAC,cAAc,GAAG;AAAA,EAC7B,WAAW,CAAC,aAAa,GAAG;AAAA;AAAA,EAE5B,oBAAoB,CAAC,mBAAmB,GAAG;AAAA,EAC3C,iBAAiB,CAAC,SAAS,GAAG;AAAA,EAC9B,sBAAsB,CAAC,SAAS,GAAG;AAAA;AAA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E;AAAA,IAC1I,MAAM,OAAO,KAAK,IAAI,CAAC,SAAS,EAAE,GAAG,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,EAAE;AAAA,IAC/D,QAAQ,OAAO,OAAO,IAAI,KAAK;AAAA,IAC/B,OAAO,OAAO,MAAM,IAAI,CAAC,QAAS,IAAI,aAAa,SAAY,MAAM,EAAE,GAAG,KAAK,UAAU,GAAG,IAAI,QAAQ,EAAE,CAAE;AAAA,IAC5G,SAAS;AAAA,MACP,GAAG;AAAA,MACH,MAAM,OAAO,QAAQ,KAAK,IAAI,EAAE;AAAA,MAChC,QAAQ,OAAO,QAAQ,OAAO,IAAI,EAAE;AAAA,MACpC,YAAY,OAAO,QAAQ,WAAW,IAAI,EAAE;AAAA,MAC5C,QAAQ,OAAO,QAAQ,OAAO,IAAI,EAAE;AAAA,IACtC;AAAA,IACA,MAAM,EAAE,QAAQ,OAAO,KAAK,OAAO,IAAI,EAAE,EAAE;AAAA,EAC7C;AACF;AAGA,SAAS,SAAS,QAAiC,IAAsC;AACvF,QAAM,QAAQ;AAAA,IACZ,GAAG,OAAO,OAAO,IAAI,CAAC,QAAQ,GAAG,IAAI,IAAI,OAAO,GAAG,IAAI,IAAI,CAAC,EAAE;AAAA,IAC9D,GAAG,OAAO,KAAK,IAAI,CAAC,QAAQ,WAAW,IAAI,IAAI,OAAO,GAAG,IAAI,IAAI,CAAC,mBAAmB,GAAG,IAAI,IAAI,CAAC,KAAK;AAAA,EACxG;AACA,SAAO,2BAA2B,MAAM,KAAK,IAAI,CAAC;AACpD;","names":["head","message","message","z","z","z","z","z","z","z","z","message","z","z","z","z","z","z","z","z","z","z","z","z","z","message","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","Count","sources","spec","refuse","message","element","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","Day","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","encoder","z","z","z","words","z","line","z","message","message","readFileSync","join","createHash","readFileSync","resolve","createHash","resolve","readFileSync","readdirSync","join","resolve","applied","createHash","resolve","tree","values","note","scoped","row","ApiError","ApiError","resolve","readFileSync","createHash","latest","report","line","scoped"]}
|