@usenaive-sdk/blueprints 0.3.0 → 0.4.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../core/src/id.ts","../../core/src/session-token.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/session.ts","../../core/src/schema/event.ts","../../core/src/schema/board.ts","../../core/src/schema/identity.ts","../../core/src/schema/resource.ts","../../core/src/schema/org.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/social.ts","../src/define.ts","../src/template.ts","../src/load.ts","../src/files.ts","../src/up.ts","../src/report.ts","../src/agents.ts","../src/apps.ts","../src/vaults.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 /**\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.\n */\n | \"idn\"\n | \"vlt\"\n | \"vcr\"\n | \"dom\"\n | \"eml\"\n | \"pho\"\n | \"inb\"\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 /** 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 /** 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 const bytes = crypto.getRandomValues(new Uint8Array(SUFFIX_LENGTH));\n let suffix = \"\";\n for (const byte of bytes) 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","/**\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 type { Role, 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\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 return claims;\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 \"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.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 \"blueprint.installed\",\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] 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 */\nexport const TOOL_TIERS = [\"search\", \"media\", \"social\"] 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-01\";\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\", 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 = API_VERSION;\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 `.harness-mcp.json`\n * naming the session-scoped bridge and joins `--mcp-config … --strict-mcp-config` to the\n * command, so the platform's tools reach the model as MCP tools of one server. `tools.configs`\n * still governs them, by the same `server.tool` / `<connector>.<tool>` names: the bridge\n * applies `permissionOf` before it answers `tools/list`, so a `deny` is never emitted and\n * cannot be called. `approvals` staying `false` is what makes an `ask` OMITTED rather than\n * gated — nothing under `bypassPermissions` can hold a call, so omission is the only honest\n * enforcement, and `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 { HarnessIdSchema } from \"./harness\";\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 five team tools (§28) are here even though only an agent with a roster is ever offered\n * 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 \"board_read\",\n \"board_write\",\n \"ask_operator\",\n] as const;\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/**\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/** The toolset wrapper — the only `tools` schema (§6). */\nexport const ToolsetSchema = z.object({\n default_config: z.object({ permission: ToolPermissionSchema }),\n configs: z.record(z.string(), ToolConfigSchema),\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 (name === ASK_OPERATOR) {\n return (config?.permission ?? toolset.default_config.permission) === \"deny\" ? \"deny\" : \"ask\";\n }\n // Public publishing defaults to approval; an explicit per-tool policy still wins.\n return config?.permission ?? (name === \"social.post\" ? \"ask\" : toolset.default_config.permission);\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 toolset.configs[ASK_OPERATOR] !== undefined && permissionOf(toolset)(ASK_OPERATOR) !== \"deny\";\n\n/** The built-ins only a micro-VM can serve (ADR-0102). */\nconst SANDBOX_TOOLS = [\"bash\", \"read\", \"write\", \"edit\", \"ls\", \"find\"] as const;\n\n/**\n * Does this toolset leave any sandbox tool reachable? A session that can call none of them needs\n * no box (ADR-0099), and that judgement is now made in two places — at `POST /v1/sessions` for a\n * session a customer starts, and at spawn for a delegated member whose coordinator has no box to\n * lend it (§28). Two copies of the list would drift, and the one that drifted would either bill a\n * box nothing can use or hand a member a `bash` tool with no machine behind it.\n */\nexport const wantsSandbox = (tools: Toolset): boolean =>\n SANDBOX_TOOLS.some((name) => {\n const config = tools.configs[name];\n if (config?.enabled === false) return false;\n return (config?.permission ?? tools.default_config.permission) !== \"deny\";\n });\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/** `slug` floats to the latest version at session start; `slug@N` is an immutable pin (§13). */\nexport const SkillRefSchema = z.string().regex(/^[a-z0-9][a-z0-9-]*(@\\d+)?$/, {\n error: \"expected `slug` or `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/** 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 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","/** Sessions, the transcript message, and tool results (canonical-spec §5, §7, §10, §16). */\n\nimport { z } from \"zod\";\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/** 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/** 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/** Normative tool result — the plugin contract depends on this shape (§16). */\nexport const ToolResultSchema = z.object({\n output: z.unknown(),\n is_error: z.boolean().optional(),\n content: z.string().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\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]);\nexport type QuestionField = z.infer<typeof QuestionFieldSchema>;\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 */\nexport const QuestionSchema = z.object({\n prompt: z.string().min(1).max(1000),\n fields: z.array(QuestionFieldSchema).min(1).max(3),\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 */\nexport const AnswersSchema = 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 <= 3, {\n message: \"a question has at most 3 fields, so an answer has at most 3 keys\",\n });\nexport type Answers = z.infer<typeof AnswersSchema>;\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});\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 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/** `POST /v1/sessions/{id}/messages` — one send contract (§7). */\nexport const SendMessageSchema = z.object({\n message: z.string(),\n interrupt: z.boolean().optional(),\n idempotency_key: z.string().optional(),\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/** `POST /v1/sessions/{id}/tool_confirmations` (§7). */\nexport const ToolConfirmationSchema = z.object({\n tool_call_id: z.string(),\n decision: z.enum([\"allow\", \"deny\"]),\n reason: z.string().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","/** Events — `{domain}.{action}` types on a gap-free `seq` (canonical-spec §8, §10, §15). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, TokenUsageSchema, idOf } from \"./common\";\n\nexport const EventTypeSchema = z.enum([\n \"message.delta\",\n \"message.completed\",\n \"tool.started\",\n \"tool.completed\",\n \"tool.confirm\",\n \"session.running\",\n \"session.usage\",\n \"session.idle\",\n \"budget.exceeded\",\n \"span.model_request.start\",\n \"span.model_request.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]);\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/** `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 a roster member's name — not an id — because that is what a\n * coordinator writes in a tool call and what a member recognises as itself; `null` is unclaimed.\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 body: z.string(),\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 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 { MicroUsdField, Timestamp, WindowSchema, idOf } from \"./common\";\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 browser: z.object({ allowed_domains: z.array(z.string()) }).nullable(),\n volume: VolumeSchema.nullable(),\n snapshot_id: idOf(\"snp\").nullable(),\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\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\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});\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","/** 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\nexport const OrganizationSchema = z.object({\n id: idOf(\"org\"),\n object: z.literal(\"organization\"),\n name: z.string(),\n balance_micro_usd: MicroUsdField,\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 * 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 (`canonical-spec §24`, `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 { Timestamp, idOf } from \"./common\";\n\n// ── Domain ────────────────────────────────────────────────────────────────────\n\n/**\n * Where the domain lives. `purchased` is accepted by the schema because the state machine is the\n * same, but no route can mint one in P2: buying a domain moves money *outward* at a registrar and\n * nothing in the platform can do that (the ledger is inbound credit only, the agent wallet is P5).\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});\nexport type InboundMessage = z.infer<typeof InboundMessageSchema>;\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\";\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 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/** 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 proof that the platform holds that app's `DASHBOARD_TOKEN` — an HMAC\n * keyed by it, never the value — 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\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 * 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 * 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 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.\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 skipped: z.array(z.string()),\n});\nexport type BlueprintReport = z.infer<typeof BlueprintReportSchema>;\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 applied_at: Timestamp,\n created_at: Timestamp,\n});\nexport type BlueprintInstall = z.infer<typeof BlueprintInstallSchema>;\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` and `apps` are the\n * halves lifted out of it that a client genuinely needs — the last two because the screen that asks\n * a person to run a company has to show them the company first (§31.5).\n */\n\nimport { z } from \"zod\";\nimport { AppTypeSchema } from \"./app\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { QuestionFieldSchema } from \"./session\";\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 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.\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});\nexport type BlueprintCrew = z.infer<typeof BlueprintCrewSchema>;\n\n/** One app this template deploys, flattened out of the declaration's `apps[]` (§31.5). */\nexport const BlueprintAppSchema = z.object({\n name: z.string().min(1),\n type: AppTypeSchema,\n description: z.string().nullable(),\n});\nexport type BlueprintApp = z.infer<typeof BlueprintAppSchema>;\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 * The built trees, one per deployable app, ordered as the declaration orders its apps. Never\n * empty: an artifact that built nothing is not an artifact, and the column behind it says so\n * (migration 0040) exactly as the single `content_hash` it replaces was `not null`.\n */\n trees: z.array(BlueprintTreeSchema).min(1),\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 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 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","/** 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/** 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\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\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(SocialTextPlatformSchema),\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 * `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 ENV_NAME,\n IdentitySchema,\n McpServerSchema,\n MicroUsdField,\n QuestionFieldSchema,\n SkillRefSchema,\n ToolsetSchema,\n VaultCredentialKindSchema,\n VaultSchema,\n} from \"@vetta/core\";\nimport { z } from \"zod\";\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});\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/** 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 system: z.string().optional(),\n tools: ToolsetSchema.optional(),\n skills: z.array(SkillRefSchema).optional(),\n mcp_servers: z.array(McpServerSchema).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 /** 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\nconst IdentityDeclSchema = IdentitySchema.pick({ name: true, description: true }).partial({\n description: true,\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\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 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 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 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 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\", 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\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 const lines = parsed.error.issues.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 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 }\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 for (const agent of config.agents) {\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 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 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 * Blueprints and their templates.\n *\n * A **blueprint** is the machine: screens, `/api/*`, the store, build and deploy, the approval\n * flow. It is one repository, and it is shared across its templates. A **template** is DATA — the\n * crew and its prompts, the tool allow-lists, the kinds of work it files, its schedules, the demo\n * seed and the words its screens print. 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/** One kind of work a template files — a deliverable kind, a post kind. `id` is what rows carry. */\nexport interface TemplateKind {\n id: string;\n label: string;\n description?: string;\n}\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 /** The kinds this template's queue holds; the screens list them in this order. */\n kinds: TemplateKind[];\n /** The demo rows the store seeds on first run, keyed by collection (`clients`, `posts`, …). */\n seed: Record<string, unknown>;\n /** Every word a screen prints that changes with the template — headings, labels, onboarding copy. */\n words: Record<string, string>;\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 * two crews spend money in different ways, so defaulting one of them is a bill the operator did\n * not choose.\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 /** Post queue, accounts, calendar, analytics. */\n media: { templates: [\"faceless\", \"clipping\"] },\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.\n */\nimport type { VettaClient } from \"@usenaive-sdk/vetta\";\nimport { AgentSchema, DeploymentSchema, VaultCredentialSchema, VaultSchema, type Agent, 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 type { AgentDecl, IdentityDecl, ProjectConfig, SkillDecl } from \"./define\";\nimport { absent, attempt, listAll, tombstone, type ResourceAction, type ResourceReport } from \"./report\";\nimport { upsertCredential, upsertVault } from \"./vaults\";\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 * 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\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 * 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\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 },\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 nothing carries a skill's (§13, §31.1), so the honest answer is a refusal that says which\n // published thing is missing rather than a filesystem error the operator cannot act on.\n if (opts.hosted) {\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 = 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\nasync function upsertIdentity(\n client: VettaClient,\n decl: IdentityDecl,\n dryRun: boolean,\n identityIds: Map<string, string>,\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 });\n identityIds.set(decl.name, created.id);\n return { name: decl.name, action: \"created\", id: created.id };\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/** 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 const report: UpReport = { dry_run: dryRun, ...applied(config), skills: [], identities: [], vaults: [], apps: [], agents: [], schedules: [], intake: [], skipped: [] };\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 // 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 }));\n }\n for (const decl of config.identities) {\n await attempt(report.identities, decl.name, () => upsertIdentity(client, decl, dryRun, ids.identities));\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 three values is an identity this run made.\n const platform = opts.platform && {\n ...opts.platform,\n known: { ...opts.platform.known, ...identityEnv(config, ids.identities) },\n };\n for (const decl of config.apps) {\n await attempt(report.apps, decl.name, () =>\n upsertApp(\n client,\n decl,\n { ...owner, dryRun, dir, trees: opts.trees, tree_errors: opts.tree_errors, env: opts.env ?? process.env, platform },\n ids.apps,\n ),\n );\n }\n const existing =\n config.agents.length > 0 || config.removed.agents.length > 0 || config.kept.agents.length > 0\n ? await listAll(client.config, \"/v1/agents\", AgentSchema, report.skipped)\n : [];\n const deployments = config.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 const briefed: [ResourceReport, NonNullable<AgentDecl[\"intake\"]>][] = [];\n for (const decl of config.agents) {\n const line = await attempt(report.agents, decl.name, () =>\n upsertAgent(client, decl, existing, ids, dryRun, scoped),\n );\n if (decl.schedules !== undefined) {\n await reconcileSchedules(client, line, decl.schedules, deployments, ids.identities, dryRun, report.schedules);\n }\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 && line.action === \"created\") briefed.push([line, decl.intake]);\n }\n reportKept(config, existing, report.agents);\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 for (const [line, decl] of briefed) {\n await attempt(report.intake, line.name, () => openIntake(client, line, decl, dryRun));\n }\n return report;\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 return error instanceof Error ? error.message : String(error);\n}\n\n/** One report line per attempt: a thrown API refusal becomes `refused`, never an escape. */\nexport async function attempt(into: ResourceReport[], name: string, work: () => Promise<ResourceReport>): Promise<ResourceReport> {\n let line: ResourceReport;\n try {\n line = await work();\n } catch (error) {\n line = { name, action: \"refused\", reason: message(error) };\n }\n into.push(line);\n return line;\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 * 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 type { Agent, Deployment, Toolset } from \"@vetta/core\";\nimport type { AgentDecl, ScheduleDecl } from \"./define\";\nimport { attempt, changed, tombstone, type ResourceReport } from \"./report\";\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/**\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 if (ids === undefined) 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 return {\n default_config: base.default_config,\n configs: {\n ...base.configs,\n apps: { ...appsTool, config: { ...appsTool.config, allowed_apps: ids } },\n },\n };\n}\n\nasync function createAgent(\n client: VettaClient,\n decl: AgentDecl,\n tools: Toolset | undefined,\n identityId: string | 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 ...(decl.system !== undefined ? { system: decl.system } : {}),\n ...(decl.skills !== undefined ? { skills: decl.skills } : {}),\n ...(decl.mcp_servers !== undefined ? { mcp_servers: decl.mcp_servers } : {}),\n ...(tools !== undefined ? { tools } : {}),\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[],\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 const tools = desiredTools(decl, current, appIds);\n if (!current) return dryRun ? { name: decl.name, action: \"created\" } : createAgent(client, decl, tools, identityId);\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(decl.system, current.system)) patch.system = decl.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 // 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/**\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 */\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 for (const decl of declared) {\n const current = rows.find((row) => row.cron === decl.cron);\n await attempt(into, `${agent.name} @ ${decl.cron}`, () => upsertSchedule(client, agent, decl, current, identityIds, dryRun));\n }\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 * 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\";\nimport type { AppDecl } from \"./define\";\nimport { collectFiles, contentHash } from \"./files\";\nimport { 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): 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 `app \"${name}\" is owned by ${held}; this project is \"${project}\". Rename the app 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 /** A scoped organization API key minted for the app that asks for it. */\n api_key: \"NAIVE_API_KEY\",\n} as const;\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 () => generated() });\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 could not have minted\n * the key by hand does not get one minted on its behalf — and \"this API key is missing the `admin`\n * scope\" on its own 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. */\nconst generated = () => randomBytes(32).toString(\"base64url\");\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 for (const [name, value] of Object.entries(env)) {\n await 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 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, env, tree);\n // Re-read: the hostname is assigned by the build `writeApp` just waited on, not by create.\n return { name: decl.name, action: \"created\", id: created.id, url: (await client.apps.get(created.id)).url };\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 /** 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 names = declared.map((one) => one.name);\n const note = (notes: string[]) => (notes.length > 0 ? { reason: notes.join(\"; \") } : {});\n const mcpPlan = decl.mcp !== undefined ? [`will set mcp ${decl.mcp}`] : [];\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}`] : [])]),\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), 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: env, unmade } = await materialize(declared, new Set(held.keys()), opts.dryRun);\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 const 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 ]\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 }\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 * 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"],"mappings":";AA8DA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB,IAAI,OAAO,KAAK,QAAQ,KAAK,aAAa,KAAK;AAW/D,SAAS,KAAK,QAAkB,OAAwB;AAC7D,QAAM,OAAO,GAAG,MAAM;AACtB,MAAI,CAAC,MAAM,WAAW,IAAI,EAAG,QAAO;AACpC,SAAO,eAAe,KAAK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MAAM;AAAA,MAAQ,OAAO;AAAA,MAAQ,KAAK;AAAA,MAAM,MACnD,YAAY,QAAQ,MAAM,UAAU,KAAK,QAAQ,MAAM;AAAA,IACzD;AACA,QAAI,KAAK,cAAc,QAAW;AAChC,YAAM,mBAAmB,QAAQ,MAAM,KAAK,WAAW,aAAa,IAAI,YAAY,QAAQ,OAAO,SAAS;AAAA,IAC9G;AAGA,QAAI,KAAK,WAAW,UAAa,KAAK,WAAW,UAAW,SAAQ,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC;AAAA,EAC9F;AACA,aAAW,QAAQ,UAAU,OAAO,MAAM;AAC1C,QAAM,aAAa,QAAQ,OAAO,SAAS,EAAE,QAAQ,UAAU,OAAO,GAAG,OAAO,MAAM;AAGtF,aAAW,CAAC,MAAM,IAAI,KAAK,SAAS;AAClC,UAAM,QAAQ,OAAO,QAAQ,KAAK,MAAM,MAAM,WAAW,QAAQ,MAAM,MAAM,MAAM,CAAC;AAAA,EACtF;AACA,SAAO;AACT;","names":["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","z","z","z","message","readFileSync","join","createHash","readFileSync","resolve","z","message","row","createHash","resolve","createHash","resolve","readFileSync","resolve","createHash"]}
1
+ {"version":3,"sources":["../../core/src/id.ts","../../core/src/errors.ts","../../core/src/money.ts","../../core/src/session-token.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/session.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/social.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","../src/define.ts","../src/roster.ts","../src/report.ts","../src/template.ts","../src/load.ts","../src/files.ts","../src/up.ts","../src/agents.ts","../src/apps.ts","../src/buckets.ts","../src/migrations.ts","../src/reconcile-cards.ts","../src/reconcile-legal.ts","../src/vaults.ts","../src/reconcile-wallet.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.\n */\n | \"idn\"\n | \"vlt\"\n | \"vcr\"\n | \"dom\"\n | \"eml\"\n | \"pho\"\n | \"inb\"\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 /** 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 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/** 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 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 type { Role, 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\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 return claims;\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 \"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.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 /** 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).\nexport const TOOL_TIERS = [\"search\", \"media\", \"social\", \"browser\", \"storage\"] 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-01\";\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\", 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 = API_VERSION;\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 `.harness-mcp.json`\n * naming the session-scoped bridge and joins `--mcp-config … --strict-mcp-config` to the\n * command, so the platform's tools reach the model as MCP tools of one server. `tools.configs`\n * still governs them, by the same `server.tool` / `<connector>.<tool>` names: the bridge\n * applies `permissionOf` before it answers `tools/list`, so a `deny` is never emitted and\n * cannot be called. `approvals` staying `false` is what makes an `ask` OMITTED rather than\n * gated — nothing under `bypassPermissions` can hold a call, so omission is the only honest\n * enforcement, and `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\";\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 five team tools (§28) are here even though only an agent with a roster is ever offered\n * 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 \"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 \"find_stock_photo\",\n] as const;\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 \"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] as const;\n\n/**\n * Platform tools that publish, spend, file or reveal, and therefore default to `ask` unless the\n * toolset says otherwise (§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]);\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/** The two built-ins that ARE a pause: a person answers them, so neither can ever be `allow`. */\nexport const asksAPerson = (name: string): boolean => name === ASK_OPERATOR || name === REQUEST_TOOLS;\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 // 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 * 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/** The built-ins only a micro-VM can serve (ADR-0102). */\nconst SANDBOX_TOOLS = [\"bash\", \"read\", \"write\", \"edit\", \"ls\", \"find\"] as const;\n\n/**\n * Does this toolset leave any sandbox tool reachable? A session that can call none of them needs\n * no box (ADR-0099), and that judgement is now made in two places — at `POST /v1/sessions` for a\n * session a customer starts, and at spawn for a delegated member whose coordinator has no box to\n * lend it (§28). Two copies of the list would drift, and the one that drifted would either bill a\n * box nothing can use or hand a member a `bash` tool with no machine behind it.\n */\nexport const wantsSandbox = (tools: Toolset): boolean =>\n SANDBOX_TOOLS.some((name) => {\n const config = tools.configs[name];\n if (config?.enabled === false) return false;\n return (config?.permission ?? tools.default_config.permission) !== \"deny\";\n });\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/** 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 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\n/** `proxy: true` with a `\"*\"` allowlist is refused: residential egress needs a bounded destination. */\nexport const BrowserOptionsSchema = z\n .object({\n allowed_domains: z.array(z.string().min(1)).min(1),\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 })\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 but `allowed_domains` 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\nexport const OrganizationSchema = z.object({\n id: idOf(\"org\"),\n object: z.literal(\"organization\"),\n name: z.string(),\n balance_micro_usd: MicroUsdField,\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","/** Sessions, the transcript message, and tool results (canonical-spec §5, §7, §10, §16). */\n\nimport { z } from \"zod\";\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/** 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/** 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/** Normative tool result — the plugin contract depends on this shape (§16). */\nexport const ToolResultSchema = z.object({\n output: z.unknown(),\n is_error: z.boolean().optional(),\n content: z.string().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\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]);\nexport type QuestionField = z.infer<typeof QuestionFieldSchema>;\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 */\nexport const QuestionSchema = z.object({\n prompt: z.string().min(1).max(1000),\n fields: z.array(QuestionFieldSchema).min(1).max(3),\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 */\nexport const AnswersSchema = 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 <= 3, {\n message: \"a question has at most 3 fields, so an answer has at most 3 keys\",\n });\nexport type Answers = z.infer<typeof AnswersSchema>;\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});\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 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/** `POST /v1/sessions/{id}/messages` — one send contract (§7). */\nexport const SendMessageSchema = z.object({\n message: z.string(),\n interrupt: z.boolean().optional(),\n idempotency_key: z.string().optional(),\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\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","/** Events — `{domain}.{action}` types on a gap-free `seq` (canonical-spec §8, §10, §15). */\n\nimport { z } from \"zod\";\nimport { MicroUsdField, Timestamp, TokenUsageSchema, idOf } from \"./common\";\n\nexport const EventTypeSchema = z.enum([\n \"message.delta\",\n \"message.completed\",\n \"tool.started\",\n \"tool.completed\",\n \"tool.confirm\",\n \"session.running\",\n \"session.usage\",\n \"session.idle\",\n \"budget.exceeded\",\n \"span.model_request.start\",\n \"span.model_request.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/** `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 a roster member's name — not an id — because that is what a\n * coordinator writes in a tool call and what a member recognises as itself; `null` is unclaimed.\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 body: z.string(),\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 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 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});\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});\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 (`canonical-spec §24`, `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 { Timestamp, idOf } from \"./common\";\n\n// ── Domain ────────────────────────────────────────────────────────────────────\n\n/**\n * Where the domain lives. `purchased` is accepted by the schema because the state machine is the\n * same, but no route can mint one in P2: buying a domain moves money *outward* at a registrar and\n * nothing in the platform can do that (the ledger is inbound credit only, the agent wallet is P5).\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});\nexport type InboundMessage = z.infer<typeof InboundMessageSchema>;\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\";\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 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 proof that the platform holds that app's `DASHBOARD_TOKEN` — an HMAC\n * keyed by it, never the value — 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\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 * 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 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 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 /** Why a `failed` run threw, in one sentence; `null` on every other row. Never a stack or a key. */\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 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` and `apps` are the\n * halves lifted out of it that a client genuinely needs — the last two because the screen that asks\n * a person to run a company has to show them the company first (§31.5).\n */\n\nimport { z } from \"zod\";\nimport { SkillRefSchema } from \"./agent\";\nimport { AppTypeSchema } from \"./app\";\nimport { MicroUsdField, Timestamp, idOf } from \"./common\";\nimport { QuestionFieldSchema } from \"./session\";\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 * 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 * The built trees, one per deployable app, ordered as the declaration orders its apps. Never\n * empty: an artifact that built nothing is not an artifact, and the column behind it says so\n * (migration 0040) exactly as the single `content_hash` it replaces was `not null`.\n */\n trees: z.array(BlueprintTreeSchema).min(1),\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 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 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","/** 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/** 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\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 * 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 model: z.string().min(1),\n prompt: z.string().min(1),\n image_urls: z.array(PublicUrl).max(1).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 * `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 IdentitySchema,\n IssueCardSchema,\n JsonSchemaDocument,\n McpServerSchema,\n Metadata,\n MicroUsdField,\n QuestionFieldSchema,\n SkillRefSchema,\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 /** 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\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 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 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 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\", 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\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 if (config.template !== undefined && config.questions.length > 3) {\n refuse(`template \"${config.template}\" asks ${config.questions.length} questions, but a template asks at most 3 before anything is provisioned — a fourth 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 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 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 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 * 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(name: string, work: () => Promise<ResourceReport>): Promise<ResourceReport> {\n try {\n return await work();\n } catch (error) {\n return { name, action: \"refused\", 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. It is one repository, and it is shared across its templates. A **template** is DATA — the\n * crew and its prompts, the tool allow-lists, the kinds of work it files, its schedules, the demo\n * seed and the words its screens print. 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/** One kind of work a template files — a deliverable kind, a post kind. `id` is what rows carry. */\nexport interface TemplateKind {\n id: string;\n label: string;\n description?: string;\n}\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 /** The kinds this template's queue holds; the screens list them in this order. */\n kinds: TemplateKind[];\n /** The demo rows the store seeds on first run, keyed by collection (`clients`, `posts`, …). */\n seed: Record<string, unknown>;\n /** Every word a screen prints that changes with the template — headings, labels, onboarding copy. */\n words: Record<string, string>;\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 * two crews spend money in different ways, so defaulting one of them is a bill the operator did\n * not choose. `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 /** Post queue, accounts, calendar, analytics. */\n media: { templates: [\"faceless\", \"clipping\"] },\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.\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 { 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 * 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 * 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\nasync function upsertIdentity(\n client: VettaClient,\n decl: IdentityDecl,\n dryRun: boolean,\n identityIds: Map<string, string>,\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 });\n identityIds.set(decl.name, created.id);\n return { name: decl.name, action: \"created\", id: created.id };\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: [], 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 // 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));\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]: opts.project ?? config.name,\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(decl.name, () =>\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 ),\n )),\n );\n const existing =\n taken.agents.length > 0 || config.removed.agents.length > 0 || config.kept.agents.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 agent = await line(decl.name, () => upsertAgent(client, decl, existing, ids, dryRun, scoped, { project: opts.project ?? config.name, ...applied(config) }));\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 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 * 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 { 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 { 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}\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.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 if (ids === undefined) 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 return {\n default_config: base.default_config,\n configs: {\n ...base.configs,\n apps: { ...appsTool, config: { ...appsTool.config, allowed_apps: ids } },\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.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 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 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 */\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, (decl) =>\n line(`${agent.name} @ ${decl.cron}`, () =>\n upsertSchedule(client, agent, decl, rows.find((row) => row.cron === decl.cron), identityIds, dryRun),\n ),\n )),\n );\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 * 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): 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 `app \"${name}\" is owned by ${held}; this project is \"${project}\". Rename the app 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 /** A scoped organization API key minted for the app that asks for it. */\n api_key: \"NAIVE_API_KEY\",\n} as const;\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 () => generated() });\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 could not have minted\n * the key by hand does not get one minted on its behalf — and \"this API key is missing the `admin`\n * scope\" on its own 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. */\nconst generated = () => randomBytes(32).toString(\"base64url\");\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, env, 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 names = declared.map((one) => one.name);\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: env, unmade } = await materialize(declared, new Set(held.keys()), opts.dryRun);\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 * `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 * 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"],"mappings":";AAkGA,IAAM,WAAW;AACjB,IAAM,gBAAgB;AACtB,IAAM,iB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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","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","line","z","list","message","message","readFileSync","join","createHash","readFileSync","resolve","row","createHash","resolve","readFileSync","readdirSync","join","resolve","applied","createHash","resolve","note","resolve","readFileSync","createHash","latest","report","line"]}