@usenaive-sdk/blueprints 0.1.0 → 0.3.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/vault.ts","../../core/src/schema/social.ts","../src/define.ts","../src/template.ts","../src/load.ts","../src/up.ts","../src/report.ts","../src/agents.ts","../src/apps.ts","../src/files.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 /** A video clipping job (`canonical-spec §30`). */\n | \"clj\"\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/** P3: apps — hosted web applications (`canonical-spec §29`). */\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] 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 loop SURFACES TO ITS MODEL the tools the platform hands it in\n * `RuntimePort.runTurn`'s `input.tools`. `pi` and `vetta` read that array (`harness-pi/src/\n * harness.ts`, `harness-vetta/src/index.ts`); `hermes` and `claude_code` do not read it at all —\n * they drive a CLI process in a micro-VM which carries its own toolset, and an array handed to\n * them goes nowhere. Every tool the PLATFORM adds rides that one seam: the team tools\n * (`send_to_agent`, `wait_for_agents`, `list_agents`, `board_read`, `board_write`), an agent's\n * `mcp_servers`, and a connected account's tools. So a `false` here is one fact with three\n * consequences, and it is the reason a coordinator cannot run on such a loop — its model would\n * never be shown `send_to_agent`, and it would fail to delegate with nothing to read.\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 * ALL FOUR FALSE, AND `approvals` IS THE LOAD-BEARING ONE. The turn runs with\n * `--permission-mode bypassPermissions`, which is not a preference: measured, without it every\n * tool call in one-shot mode is DENIED outright — not prompted — and the turn still exits 0\n * having done nothing. So nothing can hold a call for a decision, and `true` here would admit\n * an `ask` toolset and then bypass it in silence, which is the failure the catalogue exists to\n * prevent. `structured_output`: no schema is passed. `streaming_deltas`: the stream carries\n * whole assistant messages, never token deltas.\n *\n * `injectedTools`: the turn is `claude` in a box with its own toolset, and\n * `harness-claude-code-hosted/src/index.ts` does not mention `input.tools` anywhere — grep it.\n * Nothing the platform hands this loop is ever shown to its model.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: false,\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` is the third, and it was never declared at all until it had to be: the\n * runtime wrapped this loop in `withTeamTools` like every other, and the five team tools were\n * registered against an adapter that never reads `input.tools`. A coordinator on hermes was\n * admitted, billed, and shown a toolset with no `send_to_agent` in it.\n */\n capabilities: {\n approvals: false,\n structuredOutput: false,\n streamingDeltas: false,\n injectedTools: false,\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 */\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] as const;\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/** 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]);\nexport type StopReason = z.infer<typeof StopReasonSchema>;\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/** Tool calls blocking an `awaiting_approval` session (§6 `ask` permission). */\nexport const PendingActionSchema = z.object({\n tool_call_id: z.string(),\n name: z.string(),\n args: z.record(z.string(), z.unknown()),\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","/** 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\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 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 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/** A literal, or a local variable read at apply time — so a secret never sits in the config file. */\nconst EnvValueSchema = z.union([z.string(), z.object({ from_env: z.string().min(1) })]);\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\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 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 * 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 */\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 { reconcileSchedules, upsertAgent, type Ids } from \"./agents\";\nimport { findApp, ownershipRefusal, upsertApp, type Owner } from \"./apps\";\nimport type { 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 * 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\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 },\n): Promise<ResourceReport> {\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: [], 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 for (const decl of config.skills) {\n await attempt(report.skills, decl.slug, () => upsertSkill(client, decl, { dryRun, dir }));\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}`, () => upsertCredential(client, line, cred, rows, dryRun));\n }\n }\n for (const decl of config.apps) {\n await attempt(report.apps, decl.name, () => upsertApp(client, decl, { ...owner, dryRun, dir }, ids.apps));\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 for (const decl of config.agents) {\n const line = await attempt(report.agents, decl.name, () => upsertAgent(client, decl, existing, ids, dryRun));\n if (decl.schedules !== undefined) {\n await reconcileSchedules(client, line, decl.schedules, deployments, ids.identities, dryRun, report.schedules);\n }\n }\n reportKept(config, existing, report.agents);\n await applyRemoved(client, config.removed, { agents: existing, vaults }, owner, report);\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 { z } from \"zod\";\n\nexport type ResourceAction = \"created\" | \"updated\" | \"unchanged\" | \"deleted\" | \"refused\";\n\nexport interface ResourceReport {\n name: string;\n action: ResourceAction;\n id?: string;\n url?: string | null;\n /** Why, for `refused`; what would happen, for a dry-run line that needs explaining. */\n reason?: string;\n}\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 */\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. Undeclared `allowed_apps` leaves whatever\n * toolset the config (or the live agent) already carries alone.\n */\nfunction desiredTools(decl: AgentDecl, current: Agent | null, ids: string[]): Toolset | undefined {\n if (decl.allowed_apps === 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\nexport async function upsertAgent(\n client: VettaClient,\n decl: AgentDecl,\n existing: Agent[],\n ids: Ids,\n dryRun: boolean,\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 = (decl.allowed_apps ?? []).flatMap((name) => ids.apps.get(name) ?? []);\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 * `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 * 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 } 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/**\n * `{ from_env }` reads the author's shell at apply time, so a secret never sits in the config\n * file. An unset variable refuses the app before any write — naming the variable, never a value.\n */\nfunction resolveEnv(decl: AppDecl): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [name, value] of Object.entries(decl.env ?? {})) {\n if (typeof value === \"string\") {\n env[name] = value;\n continue;\n }\n const local = process.env[value.from_env];\n if (local === undefined) throw new Error(`env ${name} reads local variable ${value.from_env}, which is not set`);\n env[name] = local;\n }\n return env;\n}\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/** The `deploy_dir` as it would ship, hashed once so it can be held against the newest live deploy. */\nfunction localTree(decl: AppDecl, dir: string): Tree | null {\n if (!decl.deploy_dir) return null;\n const files = collectFiles(resolve(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 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, localTree(decl, opts.dir));\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\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 const env = resolveEnv(decl);\n const names = Object.keys(env);\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 return createApp(client, decl, env, 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 = decl.env === undefined ? [] : (await client.apps.secrets(current.id)).data;\n const unmanaged = live.map((secret) => secret.name).filter((name) => !(name in env));\n const held = new Map(live.map((secret) => [secret.name, secret.value_hash]));\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);\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 = localTree(decl, opts.dir);\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 * 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\nexport function collectFiles(root: string): Record<string, string> {\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 * 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 * 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): 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 const value = process.env[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":";AAuDA,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,MAAM,MAAM,KAAK,MAAM,EAAE,YAAY,CAAC;AACnE;;;ACvDO,IAAM,sBAAsB,KAAK,KAAK,KAAK;AA0BlD,IAAM,UAAU,IAAI,YAAY;;;AC1BzB,IAAM,wBAAwB;AAAA,EACnC;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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MAAM,UAAU,QAAQ,MAAM,EAAE,GAAG,OAAO,QAAQ,IAAI,GAAG,IAAI,IAAI,CAAC;AAAA,EAC1G;AACA,QAAM,WACJ,OAAO,OAAO,SAAS,KAAK,OAAO,QAAQ,OAAO,SAAS,KAAK,OAAO,KAAK,OAAO,SAAS,IACxF,MAAM,QAAQ,OAAO,QAAQ,cAAc,aAAa,OAAO,OAAO,IACtE,CAAC;AACP,QAAM,cAAc,OAAO,OAAO,KAAK,CAAC,SAAS,KAAK,cAAc,MAAS,IACzE,MAAM,QAAQ,OAAO,QAAQ,mBAAmB,kBAAkB,OAAO,OAAO,IAChF,CAAC;AACL,aAAW,QAAQ,OAAO,QAAQ;AAChC,UAAM,OAAO,MAAM,QAAQ,OAAO,QAAQ,KAAK,MAAM,MAAM,YAAY,QAAQ,MAAM,UAAU,KAAK,MAAM,CAAC;AAC3G,QAAI,KAAK,cAAc,QAAW;AAChC,YAAM,mBAAmB,QAAQ,MAAM,KAAK,WAAW,aAAa,IAAI,YAAY,QAAQ,OAAO,SAAS;AAAA,IAC9G;AAAA,EACF;AACA,aAAW,QAAQ,UAAU,OAAO,MAAM;AAC1C,QAAM,aAAa,QAAQ,OAAO,SAAS,EAAE,QAAQ,UAAU,OAAO,GAAG,OAAO,MAAM;AACtF,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","message","createHash","readFileSync","resolve","z","message","row","createHash","resolve","readFileSync","join","createHash","resolve","readFileSync","resolve","createHash"]}
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,MAAM,MAAM,KAAK,MAAM,EAAE,YAAY,CAAC;AACnE;;;AC9DO,IAAM,sBAAsB,KAAK,KAAK,KAAK;AA0BlD,IAAM,UAAU,IAAI,YAAY;;;AC1BzB,IAAM,wBAAwB;AAAA,EACnC;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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AS,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"]}